answer
stringlengths
17
10.2M
package burlap.behavior.singleagent.learning.lspi; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.ejml.simple.SimpleMatrix; import burlap.behavior.singleagent.EpisodeAnalysis; import burlap.behavior.singleagent.Policy; import burlap.behavior.singleagent.QValue; import burlap.behavior.singleagent.learning.LearningAgent; import burlap.behavior.singleagent.learning.lspi.SARSCollector.UniformRandomSARSCollector; import burlap.behavior.singleagent.learning.lspi.SARSData.SARS; import burlap.behavior.singleagent.planning.OOMDPPlanner; import burlap.behavior.singleagent.planning.QComputablePlanner; import burlap.behavior.singleagent.planning.commonpolicies.EpsilonGreedy; import burlap.behavior.singleagent.planning.commonpolicies.GreedyQPolicy; import burlap.behavior.singleagent.vfa.ActionApproximationResult; import burlap.behavior.singleagent.vfa.ActionFeaturesQuery; import burlap.behavior.singleagent.vfa.FeatureDatabase; import burlap.behavior.singleagent.vfa.StateFeature; import burlap.behavior.singleagent.vfa.ValueFunctionApproximation; import burlap.behavior.singleagent.vfa.common.LinearVFA; import burlap.debugtools.DPrint; import burlap.oomdp.auxiliary.common.ConstantStateGenerator; import burlap.oomdp.core.AbstractGroundedAction; import burlap.oomdp.core.Domain; import burlap.oomdp.core.State; import burlap.oomdp.core.TerminalFunction; import burlap.oomdp.singleagent.GroundedAction; import burlap.oomdp.singleagent.RewardFunction; /** * This class implements the optimized version of last squares policy iteration [1] (runs in quadratic time of the number of state features). Unlike other planning and learning algorithms, * it is reccomended that you use this class differently than the conventional ways. That is, rather than using the {@link #planFromState(State)} or {@link #runLearningEpisodeFrom(State)} * methods, you should instead use a {@link SARSCollector} object to gather a bunch of example state-action-reward-state tuples that are then used for policy iteration. You can * set the dataset to use using the {@link #setDataset(SARSData)} method and then you can run LSPI on it using the {@link #runPolicyIteration(int, double)} method. LSPI requires * initializing a matrix to an identity matrix multiplied by some large positive constant (see the reference for more information). * By default this constant is 100, but you can change it with the {@link #setIdentityScalar(double)} * method. * <p/> * If you do use the {@link #planFromState(State)} method, it will work by creating a {@link UniformRandomSARSCollector} and collecting SARS data from the input state and then calling * the {@link #runPolicyIteration(int, double)} method. You can change the {@link SARSCollector} this method uses, the number of samples it acquires, the maximum weight change for PI termination, * and the maximum number of policy iterations by using the {@link #setPlanningCollector(SARSCollector)}, {@link #setNumSamplesForPlanning(int)}, {@link #setMaxChange(double)}, and * {@link #setMaxNumPlanningIterations(int)} methods repsectively. * <p/> * If you do use the {@link #runLearningEpisodeFrom(State)} method (or the {@link #runLearningEpisodeFrom(State, int)} method), it will work by following a learning policy for the episode and adding its observations to its dataset for its * policy iteration. After enough new data has been acquired, policy iteration will be rereun. You can adjust the learning policy, the maximum number of allowed learning steps in an * episode, and the minimum number of new observations until LSPI is rerun using the {@link #setLearningPolicy(Policy)}, {@link #setMaxLearningSteps(int)}, {@link #setMinNewStepsForLearningPI(int)} * methods respectively. The LSPI termination parameters are set using the same methods that you use for adjusting the results from the {@link #planFromState(State)} method discussed above. * <p/> * This data gathering and replanning behavior from learning episodes is not expected to be an especailly good choice. Therefore, if you want a better online data acquisition, you should consider subclassing this class * and overriding the methods {@link #updateDatasetWithLearningEpisode(EpisodeAnalysis)} and {@link #shouldRereunPolicyIteration(EpisodeAnalysis)}, or the {@link #runLearningEpisodeFrom(State, int)} method * itself. * * <p/> * 1. Lagoudakis, Michail G., and Ronald Parr. "Least-squares policy iteration." The Journal of Machine Learning Research 4 (2003): 1107-1149. * * @author James MacGlashan * */ public class LSPI extends OOMDPPlanner implements QComputablePlanner, LearningAgent { /** * The object that performs value function approximation given the weights that are estimated */ protected ValueFunctionApproximation vfa; /** * The SARS dataset on which LSPI is performed */ protected SARSData dataset; /** * The state feature database on which the linear VFA is performed */ protected FeatureDatabase featureDatabase; /** * The initial LSPI identity matrix scalar; default is 100. */ protected double identityScalar = 100.; /** * The last weight values set from LSTDQ */ protected SimpleMatrix lastWeights; /** * the number of samples that are acquired for this object's dataset when the {@link #planFromState(State)} method is called. */ protected int numSamplesForPlanning = 10000; /** * The maximum change in weights permitted to terminate LSPI. Default is 1e-6. */ protected double maxChange = 1e-6; /** * The data collector used by the {@link #planFromState(State)} method. */ protected SARSCollector planningCollector; /** * The maximum number of policy iterations permitted when LSPI is run from the {@link #planFromState(State)} or {@link #runLearningEpisodeFrom(State)} methods. */ protected int maxNumPlanningIterations = 30; /** * The learning policy followed in {@link #runLearningEpisodeFrom(State)} method calls. Default is 0.1 epsilon greedy. */ protected Policy learningPolicy; /** * The maximum number of learning steps in an episode when the {@link #runLearningEpisodeFrom(State)} method is called. Default is INT_MAX. */ protected int maxLearningSteps = Integer.MAX_VALUE; /** * Number of new observations received from learning episodes since LSPI was run */ protected int numStepsSinceLastLearningPI = 0; /** * The minimum number of new observations received from learning episodes before LSPI will be run again. */ protected int minNewStepsForLearningPI = 100; /** * the saved previous learning episodes */ protected LinkedList<EpisodeAnalysis> episodeHistory = new LinkedList<EpisodeAnalysis>(); /** * The number of the most recent learning episodes to store. */ protected int numEpisodesToStore; /** * Initializes for the given domain, reward function, terminal state function, discount factor and the feature database that provides the state features used by LSPI. * @param domain the problem domain * @param rf the reward function * @param tf the terminal state function * @param gamma the discount factor * @param fd the feature database defining state features on which LSPI will run. */ public LSPI(Domain domain, RewardFunction rf, TerminalFunction tf, double gamma, FeatureDatabase fd){ this.plannerInit(domain, rf, tf, gamma, null); this.featureDatabase = fd; this.vfa = new LinearVFA(this.featureDatabase); this.learningPolicy = new EpsilonGreedy(this, 0.1); } /** * Sets the SARS dataset this object will use for LSPI * @param dataset the SARSA dataset */ public void setDataset(SARSData dataset){ this.dataset = dataset; } /** * Returns the dataset this object uses for LSPI * @return the dataset this object uses for LSPI */ public SARSData getDataset(){ return this.dataset; } /** * Returns the feature database defining state features * @return the feature database defining state features */ public FeatureDatabase getFeatureDatabase() { return featureDatabase; } /** * Sets the feature datbase defining state features * @param featureDatabase the feature database defining state features */ public void setFeatureDatabase(FeatureDatabase featureDatabase) { this.featureDatabase = featureDatabase; } /** * Returns the initial LSPI identity matrix scalar used * @return the initial LSPI identity matrix scalar used */ public double getIdentityScalar() { return identityScalar; } /** * Sets the initial LSPI identity matrix scalar used. * @param identityScalar the initial LSPI identity matrix scalar used. */ public void setIdentityScalar(double identityScalar) { this.identityScalar = identityScalar; } /** * Gets the number of SARS samples that will be gathered by the {@link #planFromState(State)} method. * @return the number of SARS samples that will be gathered by the {@link #planFromState(State)} method. */ public int getNumSamplesForPlanning() { return numSamplesForPlanning; } /** * Sets the number of SARS samples that will be gathered by the {@link #planFromState(State)} method. * @param numSamplesForPlanning the number of SARS samples that will be gathered by the {@link #planFromState(State)} method. */ public void setNumSamplesForPlanning(int numSamplesForPlanning) { this.numSamplesForPlanning = numSamplesForPlanning; } /** * Gets the {@link SARSCollector} used by the {@link #planFromState(State)} method for collecting data. * @return the {@link SARSCollector} used by the {@link #planFromState(State)} method for collecting data. */ public SARSCollector getPlanningCollector() { return planningCollector; } /** * Sets the {@link SARSCollector} used by the {@link #planFromState(State)} method for collecting data. * @param planningCollector the {@link SARSCollector} used by the {@link #planFromState(State)} method for collecting data. */ public void setPlanningCollector(SARSCollector planningCollector) { this.planningCollector = planningCollector; } /** * The maximum number of policy iterations that will be used by the {@link #planFromState(State)} method. * @return the maximum number of policy iterations that will be used by the {@link #planFromState(State)} method. */ public int getMaxNumPlanningIterations() { return maxNumPlanningIterations; } /** * Sets the maximum number of policy iterations that will be used by the {@link #planFromState(State)} method. * @param maxNumPlanningIterations the maximum number of policy iterations that will be used by the {@link #planFromState(State)} method. */ public void setMaxNumPlanningIterations(int maxNumPlanningIterations) { this.maxNumPlanningIterations = maxNumPlanningIterations; } /** * The learning policy followed by the {@link #runLearningEpisodeFrom(State)} and {@link #runLearningEpisodeFrom(State, int)} methods. * @return learning policy followed by the {@link #runLearningEpisodeFrom(State)} and {@link #runLearningEpisodeFrom(State, int)} methods. */ public Policy getLearningPolicy() { return learningPolicy; } /** * Sets the learning policy followed by the {@link #runLearningEpisodeFrom(State)} and {@link #runLearningEpisodeFrom(State, int)} methods. * @param learningPolicy the learning policy followed by the {@link #runLearningEpisodeFrom(State)} and {@link #runLearningEpisodeFrom(State, int)} methods. */ public void setLearningPolicy(Policy learningPolicy) { this.learningPolicy = learningPolicy; } /** * The maximum number of learning steps permitted by the {@link #runLearningEpisodeFrom(State)} method. * @return maximum number of learning steps permitted by the {@link #runLearningEpisodeFrom(State)} method. */ public int getMaxLearningSteps() { return maxLearningSteps; } /** * Sets the maximum number of learning steps permitted by the {@link #runLearningEpisodeFrom(State)} method. * @param maxLearningSteps the maximum number of learning steps permitted by the {@link #runLearningEpisodeFrom(State)} method. */ public void setMaxLearningSteps(int maxLearningSteps) { this.maxLearningSteps = maxLearningSteps; } /** * The minimum number of new learning observations before policy iteration is run again. * @return the minimum number of new learning observations before policy iteration is run again. */ public int getMinNewStepsForLearningPI() { return minNewStepsForLearningPI; } /** * Sets the minimum number of new learning observations before policy iteration is run again. * @param minNewStepsForLearningPI the minimum number of new learning observations before policy iteration is run again. */ public void setMinNewStepsForLearningPI(int minNewStepsForLearningPI) { this.minNewStepsForLearningPI = minNewStepsForLearningPI; } /** * The maximum change in weights required to terminate policy iteration when called from the {@link #planFromState(State)}, {@link #runLearningEpisodeFrom(State)} or {@link #runLearningEpisodeFrom(State, int)} methods. * @return the maximum change in weights required to terminate policy iteration when called from the {@link #planFromState(State)}, {@link #runLearningEpisodeFrom(State)} or {@link #runLearningEpisodeFrom(State, int)} methods. */ public double getMaxChange() { return maxChange; } /** * Sets the maximum change in weights required to terminate policy iteration when called from the {@link #planFromState(State)}, {@link #runLearningEpisodeFrom(State)} or {@link #runLearningEpisodeFrom(State, int)} methods. * @param maxChange the maximum change in weights required to terminate policy iteration when called from the {@link #planFromState(State)}, {@link #runLearningEpisodeFrom(State)} or {@link #runLearningEpisodeFrom(State, int)} methods. */ public void setMaxChange(double maxChange) { this.maxChange = maxChange; } /** * Runs LSTDQ on this object's current {@link SARSData} dataset. * @return the new weight matrix as a {@link SimpleMatrix} object. */ public SimpleMatrix LSTDQ(){ //set our policy Policy p = new GreedyQPolicy(this); //first we want to get all the features for all of our states in our data set; this is important if our feature database generates new features on the fly //and will also restrict our focus to only the action features that we want List<SSFeatures> features = new ArrayList<LSPI.SSFeatures>(this.dataset.size()); for(SARS sars : this.dataset.dataset){ features.add(new SSFeatures(this.featureDatabase.getActionFeaturesSets(sars.s, this.gaListWrapper(sars.a)), this.featureDatabase.getActionFeaturesSets(sars.sp, this.gaListWrapper(p.getAction(sars.sp))))); } int nf = this.featureDatabase.numberOfFeatures(); SimpleMatrix B = SimpleMatrix.identity(nf).scale(this.identityScalar); SimpleMatrix b = new SimpleMatrix(nf, 1); for(int i = 0; i < features.size(); i++){ SimpleMatrix phi = this.phiConstructor(features.get(i).sActionFeatures, nf); SimpleMatrix phiPrime = this.phiConstructor(features.get(i).sPrimeActionFeatures, nf); double r = this.dataset.get(i).r; SimpleMatrix numerator = B.mult(phi).mult(phi.minus(phiPrime.scale(gamma)).transpose()).mult(B); SimpleMatrix denomenatorM = phi.minus(phiPrime.scale(this.gamma)).transpose().mult(B).mult(phi); double denomenator = denomenatorM.get(0) + 1; B = B.minus(numerator.scale(1./denomenator)); b = b.plus(phi.scale(r)); //DPrint.cl(0, "updated matrix for row " + i + "/" + features.size()); } SimpleMatrix w = B.mult(b); this.vfa = new LinearVFA(this.featureDatabase); for(int i = 0; i < nf; i++){ this.vfa.setWeight(i, w.get(i, 0)); } return w; } /** * Runs LSPI for either numIterations or until the change in the weight matrix is no greater than maxChange. * @param numIterations the maximum number of policy iterations. * @param maxChange when the weight change is smaller than this value, LSPI terminates. */ public void runPolicyIteration(int numIterations, double maxChange){ boolean converged = false; for(int i = 0; i < numIterations && !converged; i++){ SimpleMatrix nw = this.LSTDQ(); double change = Double.POSITIVE_INFINITY; if(this.lastWeights != null){ change = this.lastWeights.minus(nw).normF(); if(change <= maxChange){ converged = true; } } this.lastWeights = nw; DPrint.cl(0, "Finished iteration: " + i + ". Weight change: " + change); } DPrint.cl(0, "Finished Policy Iteration."); } /** * Constructs the state-action feature vector as a {@link SimpleMatrix}. * @param features the state-action features that have non-zero values * @param nf the total number of state-action features. * @return the state-action feature vector as a {@link SimpleMatrix}. */ protected SimpleMatrix phiConstructor(List<ActionFeaturesQuery> features, int nf){ SimpleMatrix phi = new SimpleMatrix(nf, 1); if(features.size() != 1){ throw new RuntimeException("Expected only one actions's set of features."); } for(StateFeature f : features.get(0).features){ phi.set(f.id, f.value); } return phi; } /** * Wraps a {@link GroundedAction} in a list of size 1. * @param ga the {@link GroundedAction} to wrap. * @return a {@link List} consisting of just the input {@link GroundedAction} object. */ protected List<GroundedAction> gaListWrapper(AbstractGroundedAction ga){ List<GroundedAction> la = new ArrayList<GroundedAction>(1); la.add((GroundedAction)ga); return la; } @Override public List<QValue> getQs(State s) { List<GroundedAction> gas = this.getAllGroundedActions(s); List <QValue> qs = new ArrayList<QValue>(gas.size()); List<ActionApproximationResult> results = vfa.getStateActionValues(s, gas); for(GroundedAction ga : gas){ qs.add(this.getQFromFeaturesFor(results, s, ga)); } return qs; } @Override public QValue getQ(State s, AbstractGroundedAction a) { List <GroundedAction> gaList = new ArrayList<GroundedAction>(1); gaList.add((GroundedAction)a); List<ActionApproximationResult> results = vfa.getStateActionValues(s, gaList); return this.getQFromFeaturesFor(results, s, (GroundedAction)a); } /** * Creates a Q-value object in which the Q-value is determined from VFA. * @param results the VFA prediction results for each action. * @param s the state of the Q-value * @param ga the action taken * @return a Q-value object in which the Q-value is determined from VFA. */ protected QValue getQFromFeaturesFor(List<ActionApproximationResult> results, State s, GroundedAction ga){ ActionApproximationResult result = ActionApproximationResult.extractApproximationForAction(results, ga); QValue q = new QValue(s, ga, result.approximationResult.predictedValue); return q; } @Override public void planFromState(State initialState) { if(planningCollector == null){ this.planningCollector = new SARSCollector.UniformRandomSARSCollector(this.actions); } this.dataset = this.planningCollector.collectNInstances(new ConstantStateGenerator(initialState), this.rf, this.numSamplesForPlanning, Integer.MAX_VALUE, this.tf, this.dataset); this.runPolicyIteration(this.maxNumPlanningIterations, this.maxChange); } @Override public void resetPlannerResults() { this.dataset.clear(); this.vfa.resetWeights(); } /** * Pair of the the state-action features and the next state-action features. * @author James MacGlashan * */ protected class SSFeatures{ /** * State-action features */ public List<ActionFeaturesQuery> sActionFeatures; /** * Next state-action features. */ public List<ActionFeaturesQuery> sPrimeActionFeatures; /** * Initializes. * @param sActionFeatures state-action features * @param sPrimeActionFeatures next state-action features */ public SSFeatures(List<ActionFeaturesQuery> sActionFeatures, List<ActionFeaturesQuery> sPrimeActionFeatures){ this.sActionFeatures = sActionFeatures; this.sPrimeActionFeatures = sPrimeActionFeatures; } } @Override public EpisodeAnalysis runLearningEpisodeFrom(State initialState) { return this.runLearningEpisodeFrom(initialState, this.maxLearningSteps); } @Override public EpisodeAnalysis runLearningEpisodeFrom(State initialState, int maxSteps) { EpisodeAnalysis ea = this.learningPolicy.evaluateBehavior(initialState, this.rf, this.tf, maxSteps); this.updateDatasetWithLearningEpisode(ea); if(this.shouldRereunPolicyIteration(ea)){ this.runPolicyIteration(this.maxNumPlanningIterations, this.maxChange); this.numStepsSinceLastLearningPI = 0; } else{ this.numStepsSinceLastLearningPI += ea.numTimeSteps()-1; } if(episodeHistory.size() >= numEpisodesToStore){ episodeHistory.poll(); } episodeHistory.offer(ea); return ea; } /** * Updates this object's {@link SARSData} to include the results of a learning episode. * @param ea the learning episode as an {@link EpisodeAnalysis} object. */ protected void updateDatasetWithLearningEpisode(EpisodeAnalysis ea){ if(this.dataset == null){ this.dataset = new SARSData(ea.numTimeSteps()-1); } for(int i = 0; i < ea.numTimeSteps()-1; i++){ this.dataset.add(ea.getState(i), ea.getAction(i), ea.getReward(i+1), ea.getState(i+1)); } } /** * Returns whether LSPI should be rereun given the latest learning episode results. Default behavior is to return true * if the number of leanring episode steps plus the number of steps since the last run is greater than the {@link #numStepsSinceLastLearningPI} threshold. * @param ea the most recent learning episode * @return true if LSPI should be rerun; false otherwise. */ protected boolean shouldRereunPolicyIteration(EpisodeAnalysis ea){ if(this.numStepsSinceLastLearningPI+ea.numTimeSteps()-1 > this.minNewStepsForLearningPI){ return true; } return false; } @Override public EpisodeAnalysis getLastLearningEpisode() { return this.episodeHistory.getLast(); } @Override public void setNumEpisodesToStore(int numEps) { this.numEpisodesToStore = numEps; } @Override public List<EpisodeAnalysis> getAllStoredLearningEpisodes() { return this.episodeHistory; } }
package ca.cumulonimbus.pressurenetsdk; /** * Store configurations for the PressureNet SDK * @author jacob * */ public class CbConfiguration { public static final String SERVER_URL = "https://pressurenet.io/"; public static final String STAGING_URL = "http://pressurenet-staging.elasticbeanstalk.com/"; public static final String CB_WEBSITE = "http://cumulonimbus.ca/"; public static final String API_SIGNUP_URL = "https://pressurenet.io/developers/"; public static final String API_KEY = "YOUR_API_KEY_HERE"; public static final boolean DEBUG_MODE = true; public static final String SDK_VERSION = "1.4.2"; // External API keys public static final String EXTERNAL_URL = ""; public static final String EXTERNAL_KEY = ""; }
package com.dmdirc.addons.nowplaying; import com.dmdirc.MessageTarget; import com.dmdirc.Server; import com.dmdirc.commandparser.CommandArguments; import com.dmdirc.commandparser.commands.ChatCommand; import com.dmdirc.commandparser.CommandManager; import com.dmdirc.commandparser.commands.IntelligentCommand; import com.dmdirc.config.IdentityManager; import com.dmdirc.ui.input.AdditionalTabTargets; import com.dmdirc.ui.interfaces.InputWindow; import java.util.List; /** * The now playing command retrieves the currently playing song from a * variety of media players. * @author chris */ public final class NowPlayingCommand extends ChatCommand implements IntelligentCommand { /** The plugin that's using this command. */ final NowPlayingPlugin parent; /** * Creates a new instance of NowPlayingCommand. * * @param parent The plugin that's instansiating this command */ public NowPlayingCommand(final NowPlayingPlugin parent) { super(); this.parent = parent; CommandManager.registerCommand(this); } /** {@inheritDoc} */ @Override public void execute(final InputWindow origin, final Server server, final MessageTarget target, final boolean isSilent, final CommandArguments args) { if (args.getArguments().length > 0 && args.getArguments()[0] .equalsIgnoreCase("--sources")) { doSourceList(origin, isSilent, args.getArgumentsAsString(1)); } else if (args.getArguments().length > 0 && args.getArguments()[0] .equalsIgnoreCase("--source")) { if (args.getArguments().length > 1) { final String sourceName = args.getArguments()[1]; final MediaSource source = parent.getSource(sourceName); if (source == null) { sendLine(origin, isSilent, FORMAT_ERROR, "Source not found."); } else { if (source.getState() != MediaSourceState.CLOSED) { target.getFrame().getCommandParser().parseCommand(origin, getInformation(source, args.getArgumentsAsString(2))); } else { sendLine(origin, isSilent, FORMAT_ERROR, "Source is not running."); } } } else { sendLine(origin, isSilent, FORMAT_ERROR, "You must specify a source when using --source."); } } else { if (parent.hasRunningSource()) { target.getFrame().getCommandParser().parseCommand(origin, getInformation(parent.getBestSource(), args. getArgumentsAsString(0))); } else { sendLine(origin, isSilent, FORMAT_ERROR, "No running media sources available."); } } } /** * Outputs a list of sources for the nowplaying command. * * @param origin The input window where the command was entered * @param isSilent Whether this command is being silenced * @param format Format to be passed to getInformation */ private void doSourceList(final InputWindow origin, final boolean isSilent, final String format) { final List<MediaSource> sources = parent.getSources(); if (sources.isEmpty()) { sendLine(origin, isSilent, FORMAT_ERROR, "No media sources available."); } else { final String[] headers = {"Source", "Status", "Information"}; final String[][] data = new String[sources.size()][3]; int i = 0; for (MediaSource source : sources) { data[i][0] = source.getAppName(); if (source.getState() != MediaSourceState.CLOSED) { data[i][1] = source.getState().getNiceName().toLowerCase(); data[i][2] = getInformation(source, format); } else { data[i][1] = "not running"; data[i][2] = "-"; } i++; } sendLine(origin, isSilent, FORMAT_OUTPUT, doTable(headers, data)); } } /** * Returns a formatted information string from the requested soruce. * * @param source MediaSource to query * @param format Format to use * * @return Formatted information string * @since 0.6.3 */ private String getInformation(final MediaSource source, final String format) { if (format.isEmpty()) { return parent.doSubstitution(IdentityManager.getGlobalConfig() .getOption(parent.getDomain(), "format"), source); } else { return parent.doSubstitution(format, source); } } /** {@inheritDoc}. */ @Override public String getName() { return "nowplaying"; } /** {@inheritDoc}. */ @Override public boolean showInHelp() { return true; } /** {@inheritDoc}. */ @Override public String getHelp() { return "nowplaying [--sources|--source <source>] - " + "tells the channel the song you're currently playing"; } /** {@inheritDoc} */ @Override public AdditionalTabTargets getSuggestions(final int arg, final List<String> previousArgs) { final AdditionalTabTargets res = new AdditionalTabTargets(); res.excludeAll(); if (arg == 0) { res.add("--sources"); res.add("--source"); } else if (arg == 1 && previousArgs.get(0).equalsIgnoreCase("--source")) { for (MediaSource source : parent.getSources()) { if (source.getState() != MediaSourceState.CLOSED) { res.add(source.getAppName()); } } } return res; } }
package com.dmdirc.addons.ui_swing.components; import com.dmdirc.Channel; import com.dmdirc.addons.ui_swing.SwingController; import com.dmdirc.addons.ui_swing.UIUtilities; import com.dmdirc.addons.ui_swing.actions.NoNewlinesPasteAction; import com.dmdirc.addons.ui_swing.components.frames.ChannelFrame; import com.dmdirc.config.IdentityManager; import com.dmdirc.interfaces.ConfigChangeListener; import com.dmdirc.parser.interfaces.ChannelInfo; import com.dmdirc.parser.interfaces.Parser; import com.dmdirc.parser.interfaces.callbacks.ChannelTopicListener; import com.dmdirc.ui.IconManager; import com.dmdirc.ui.messages.ColourManager; import com.dmdirc.ui.messages.Styliser; import com.dmdirc.util.URLHandler; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JScrollPane; import javax.swing.KeyStroke; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.text.AbstractDocument; import javax.swing.text.BadLocationException; import javax.swing.text.BoxView; import javax.swing.text.ComponentView; import javax.swing.text.DefaultStyledDocument; import javax.swing.text.Element; import javax.swing.text.GlyphView; import javax.swing.text.IconView; import javax.swing.text.LabelView; import javax.swing.text.ParagraphView; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; import javax.swing.text.StyledEditorKit; import javax.swing.text.View; import javax.swing.text.ViewFactory; import net.miginfocom.swing.MigLayout; /** * Component to show and edit topics for a channel. */ public class TopicBar extends JComponent implements ActionListener, ConfigChangeListener, ChannelTopicListener, HyperlinkListener { /** * A version number for this class. It should be changed whenever the class * structure is changed (or anything else that would prevent serialized * objects being unserialized with the new class). */ private static final long serialVersionUID = 1; /** Topic text. */ private final TextPaneInputField topicText; /** Edit button. */ private final JButton topicEdit; /** Cancel button. */ private final JButton topicCancel; /** Associated channel. */ private Channel channel; /** Controller. */ private SwingController controller; /** Empty Attrib set. */ private SimpleAttributeSet as; /** Foreground Colour. */ private Color foregroundColour; /** Background Colour. */ private Color backgroundColour; /** * Instantiates a new topic bar. * * @param channelFrame Parent channel frame */ public TopicBar(final ChannelFrame channelFrame) { controller = channelFrame.getController(); topicText = new TextPaneInputField(); //TODO issue 3251 //if (channelFrame.getConfigManager().getOptionBool(controller. // getDomain(), "showfulltopic")) { // topicText.setEditorKit(new StyledEditorKit()); //} else { topicText.setEditorKit(new WrapEditorKit()); ((DefaultStyledDocument) topicText.getDocument()).setDocumentFilter( new NewlinesDocumentFilter()); topicText.getActionMap().put("paste-from-clipboard", new NoNewlinesPasteAction()); topicEdit = new ImageButton("edit", IconManager.getIconManager(). getIcon("edit-inactive"), IconManager.getIconManager(). getIcon("edit")); topicCancel = new ImageButton("cancel", IconManager.getIconManager(). getIcon("close"), IconManager.getIconManager(). getIcon("close-active")); this.channel = channelFrame.getChannel(); new SwingInputHandler(topicText, channelFrame.getCommandParser(), channelFrame).setTypes(false, false, true, false); topicText.setEditable(false); topicCancel.setVisible(false); final JScrollPane sp = new JScrollPane(topicText); sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); setLayout(new MigLayout("fillx, ins 0, hidemode 3")); add(sp, "growx, pushx"); add(topicCancel, ""); add(topicEdit, ""); channel.getChannelInfo().getParser().getCallbackManager().addCallback( ChannelTopicListener.class, this, channel.getChannelInfo(). getName()); topicText.addActionListener(this); topicEdit.addActionListener(this); topicCancel.addActionListener(this); topicText.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "enterButton"); topicText.getActionMap().put("enterButton", new AbstractAction( "enterButton") { private static final long serialVersionUID = 1; /** {@inheritDoc} */ @Override public void actionPerformed(ActionEvent e) { TopicBar.this.actionPerformed(e); } }); topicText.getInputMap().put(KeyStroke.getKeyStroke("ESCAPE"), "escapeButton"); topicText.getActionMap().put("escapeButton", new AbstractAction( "escapeButton") { private static final long serialVersionUID = 1; /** {@inheritDoc} */ @Override public void actionPerformed(ActionEvent e) { e.setSource(topicCancel); TopicBar.this.actionPerformed(e); } }); topicText.addHyperlinkListener(this); IdentityManager.getGlobalConfig().addChangeListener( "ui", "backgroundcolour", this); IdentityManager.getGlobalConfig().addChangeListener( "ui", "foregroundcolour", this); IdentityManager.getGlobalConfig().addChangeListener( "ui", "inputbackgroundcolour", this); IdentityManager.getGlobalConfig().addChangeListener( "ui", "inputforegroundcolour", this); IdentityManager.getGlobalConfig().addChangeListener( controller.getDomain(), "showfulltopic", this); setColours(); } /** {@inheritDoc} */ @Override public void onChannelTopic(final Parser tParser, ChannelInfo cChannel, boolean bIsJoinTopic) { topicChanged(); } /** * Topic has changed, update topic. */ private void topicChanged() { topicText.setText(""); setAttributes(); ((DefaultStyledDocument) topicText.getDocument()).setCharacterAttributes( 0, Integer.MAX_VALUE, as, true); if (channel.getCurrentTopic() != null) { Styliser.addStyledString((StyledDocument) topicText.getDocument(), new String[]{Styliser.CODE_HEXCOLOUR + ColourManager.getHex( foregroundColour) + channel.getCurrentTopic().getTopic(),}, as); } topicText.setCaretPosition(0); } /** * {@inheritDoc} * * @param e Action event */ @Override public void actionPerformed(final ActionEvent e) { if (e.getSource() == topicEdit || e.getSource() == topicText) { if (topicText.isEditable()) { channel.setTopic(topicText.getText()); ((ChannelFrame) channel.getFrame()).getInputField(). requestFocusInWindow(); topicChanged(); topicText.setEditable(false); topicCancel.setVisible(false); } else { topicText.setVisible(false); topicText.setText(""); setAttributes(); ((DefaultStyledDocument) topicText.getDocument()). setCharacterAttributes( 0, Integer.MAX_VALUE, as, true); topicText.setText(channel.getCurrentTopic().getTopic()); topicText.setCaretPosition(0); topicText.setEditable(true); topicText.setVisible(true); topicText.requestFocusInWindow(); topicCancel.setVisible(true); } } else if (e.getSource() == topicCancel) { topicText.setEditable(false); topicCancel.setVisible(false); ((ChannelFrame) channel.getFrame()).getInputField(). requestFocusInWindow(); topicChanged(); } } /** {@inheritDoc} */ @Override public void hyperlinkUpdate(final HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { URLHandler.getURLHander().launchApp(e.getURL()); } } private void setColours() { backgroundColour = channel.getConfigManager().getOptionColour( "ui", "inputbackgroundcolour", "ui", "backgroundcolour"); foregroundColour = channel.getConfigManager().getOptionColour( "ui", "inputforegroundcolour", "ui", "foregroundcolour"); setBackground(backgroundColour); setForeground(foregroundColour); setDisabledTextColour(foregroundColour); setCaretColor(foregroundColour); setAttributes(); } private void setAttributes() { as = new SimpleAttributeSet(); StyleConstants.setFontFamily(as, topicText.getFont().getFamily()); StyleConstants.setFontSize(as, topicText.getFont().getSize()); StyleConstants.setBackground(as, backgroundColour); StyleConstants.setForeground(as, foregroundColour); StyleConstants.setUnderline(as, false); StyleConstants.setBold(as, false); StyleConstants.setItalic(as, false); } /** * Sets the caret position in this topic bar. * * @param position New position */ public void setCaretPosition(final int position) { UIUtilities.invokeLater(new Runnable() { /** {@inheritDoc} */ @Override public void run() { topicText.setCaretPosition(position); } }); } /** * Sets the caret colour to the specified coloour. * * @param optionColour Colour for the caret */ public void setCaretColor(final Color optionColour) { UIUtilities.invokeLater(new Runnable() { /** {@inheritDoc} */ @Override public void run() { topicText.setCaretColor(optionColour); } }); } /** * Sets the foreground colour to the specified coloour. * * @param optionColour Colour for the foreground */ @Override public void setForeground(final Color optionColour) { UIUtilities.invokeLater(new Runnable() { /** {@inheritDoc} */ @Override public void run() { topicText.setForeground(optionColour); } }); } /** * Sets the disabled text colour to the specified coloour. * * @param optionColour Colour for the disabled text */ public void setDisabledTextColour(final Color optionColour) { UIUtilities.invokeLater(new Runnable() { /** {@inheritDoc} */ @Override public void run() { topicText.setDisabledTextColor(optionColour); } }); } /** * Sets the background colour to the specified coloour. * * @param optionColour Colour for the caret */ @Override public void setBackground(final Color optionColour) { UIUtilities.invokeLater(new Runnable() { /** {@inheritDoc} */ @Override public void run() { topicText.setBackground(optionColour); } }); } /** {@inheritDoc} */ @Override public void configChanged(String domain, String key) { //TODO issue 3251 //if ("showfulltopic".equals(key)) { // if (channel.getConfigManager().getOptionBool(controller.getDomain(), // "showfulltopic")) { // topicText.setEditorKit(new StyledEditorKit()); // } else { // topicText.setEditorKit(new WrapEditorKit()); // ((DefaultStyledDocument) topicText.getDocument()).setDocumentFilter( // new NewlinesDocumentFilter()); //} else { setColours(); } /** * Closes this topic bar. */ public void close() { channel.getChannelInfo().getParser().getCallbackManager().delCallback( ChannelTopicListener.class, this); } } /** * @author Stanislav Lapitsky * @version 1.0 */ class WrapEditorKit extends StyledEditorKit { private static final long serialVersionUID = 1; private ViewFactory defaultFactory = new WrapColumnFactory(); /** {@inheritDoc} */ @Override public ViewFactory getViewFactory() { return defaultFactory; } } /** * @author Stanislav Lapitsky * @version 1.0 */ class WrapColumnFactory implements ViewFactory { /** {@inheritDoc} */ @Override public View create(final Element elem) { String kind = elem.getName(); if (kind != null) { if (kind.equals(AbstractDocument.ContentElementName)) { return new WrapLabelView(elem); } else if (kind.equals(AbstractDocument.ParagraphElementName)) { return new NoWrapParagraphView(elem); } else if (kind.equals(AbstractDocument.SectionElementName)) { return new BoxView(elem, View.Y_AXIS); } else if (kind.equals(StyleConstants.ComponentElementName)) { return new ComponentView(elem); } else if (kind.equals(StyleConstants.IconElementName)) { return new IconView(elem); } } // default to text display return new LabelView(elem); } } /** * @author Stanislav Lapitsky * @version 1.0 */ class NoWrapParagraphView extends ParagraphView { /** * Creates a new no wrap paragraph view. * * @param elem Element to view */ public NoWrapParagraphView(final Element elem) { super(elem); } /** {@inheritDoc} */ @Override public void layout(final int width, final int height) { super.layout(Short.MAX_VALUE, height); } /** {@inheritDoc} */ @Override public float getMinimumSpan(final int axis) { return super.getPreferredSpan(axis); } } /** * @author Stanislav Lapitsky * @version 1.0 */ class WrapLabelView extends LabelView { /** * Creates a new wrap label view. * * @param elem Element to view */ public WrapLabelView(final Element elem) { super(elem); } /** {@inheritDoc} */ @Override public int getBreakWeight(final int axis, final float pos, final float len) { if (axis == View.X_AXIS) { checkPainter(); int p0 = getStartOffset(); int p1 = getGlyphPainter().getBoundedPosition(this, p0, pos, len); if (p1 == p0) { // can't even fit a single character return View.BadBreakWeight; } try { //if the view contains line break char return forced break if (getDocument().getText(p0, p1 - p0).indexOf("\r") >= 0) { return View.ForcedBreakWeight; } } catch (BadLocationException ex) { //should never happen } } return super.getBreakWeight(axis, pos, len); } /** {@inheritDoc} */ @Override public View breakView(final int axis, final int p0, final float pos, final float len) { if (axis == View.X_AXIS) { checkPainter(); int p1 = getGlyphPainter().getBoundedPosition(this, p0, pos, len); try { //if the view contains line break char break the view int index = getDocument().getText(p0, p1 - p0).indexOf("\r"); if (index >= 0) { GlyphView v = (GlyphView) createFragment(p0, p0 + index + 1); return v; } } catch (BadLocationException ex) { //should never happen } } return super.breakView(axis, p0, pos, len); } }
package com.gmail.fthielisch.chestkits; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.block.Chest; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.java.JavaPlugin; public class ChestKitsPlugin extends JavaPlugin { public static final String LORE_KEY = "Contains a bunch of items!"; private ChestKitsConfiguration config = null; @Override public void onEnable() { config = new ChestKitsConfiguration(this.getConfig(), this.getLogger()); this.getServer().getPluginManager().registerEvents(new ChestKitsListener(this), this); } @Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { Player toGive; boolean fromConsole = false; if (!(sender instanceof Player)) { if (args.length == 0) { sender.sendMessage("You must specify a target player."); sender.sendMessage("Usage: /ckit (PLAYER) (command)"); return true; } toGive = sender.getServer().getPlayer(args[0]); if (toGive == null || !toGive.isOnline()) { sender.sendMessage("The player " + args[0] + " is not online!"); return true; } String[] args2 = new String[args.length - 1]; for (int i = 1; i < args.length; i++) { args2[i - 1] = args[i]; } args = args2; fromConsole = true; } else { toGive = (Player) sender; } if (args.length < 1) { sender.sendMessage("Usage: /ckit {kitname}"); if (sender.hasPermission("ckit.create")) { sender.sendMessage("Usage: /ckit create {kitName}"); } if (sender.hasPermission("ckit.delete")) { sender.sendMessage("Usage: /ckit delete {kitName}"); } if (sender.hasPermission("ckit.save")) { sender.sendMessage("Usage: /ckit save config"); } if (sender.hasPermission("ckit.give")) { sender.sendMessage("Usage: /ckit give {playerName} {kitName}"); } return true; } if (args.length == 1) { String kitName = args[0]; ChestKitsKit kit = config.getKit(kitName); if (kit == null) { sender.sendMessage(ChatColor.RED + "The kit '" + kitName + "' does not exist."); return true; } if (!sender.hasPermission("ckit.get." + kitName) && !sender.hasPermission("ckit.get.*")) { sender.sendMessage(ChatColor.RED + "You do not have access to that kit."); return true; } ItemStack is = new ItemStack(Material.CHEST, 1); ItemMeta meta = is.getItemMeta(); meta.setDisplayName("Kit " + kitName); meta.setLore(Arrays.asList(LORE_KEY)); is.setItemMeta(meta); if (!toGive.getInventory().addItem(is).isEmpty()) { sender.sendMessage(ChatColor.RED + "Your inventory is too full to hold the kit."); } else if (fromConsole) { toGive.sendMessage(ChatColor.GREEN + "You have been given a " + kitName + " kit!"); } return true; } if (args[0].equals("create")) { if (!sender.hasPermission("ckit.create")) { sender.sendMessage(ChatColor.RED + "You are not allowed to create new kits."); return true; } String kitName = args[1]; Player p = toGive; List<ItemStack> items = new LinkedList<ItemStack>(); for (ItemStack is : p.getInventory()) { if (is == null) { continue; } items.add(new ItemStack(is)); } ChestKitsKit kit = new ChestKitsKit(kitName, items); config.addKit(kitName, kit); sender.sendMessage("Kit '" + kitName + "' created. You may want to save the configuration."); } else if (args[0].equals("cooldown")) { if (!sender.hasPermission("ckit.cooldown")) { sender.sendMessage(ChatColor.RED + "You are not allowed to give kits cooldowns."); return true; } if (args.length < 3) { sender.sendMessage(ChatColor.RED + "You must specify how long to set the cooldown to."); sender.sendMessage(ChatColor.RED + "You may set the cooldown to 0 to remove it.") } String kitName = args[1]; ChestKitsKit kit = config.getKit(kitName); if (kit == null) { sender.sendMessage(ChatColor.RED + "The kit '" + kitName + "' does not exist."); return true; } long cooldown; try { cooldown = Long.parseLong(args[2]); } catch (Exception e) { sender.sendMessage("Invalid number provided for cooldown."); return true; } kit.setCooldown(cooldown); sender.sendMessage("Kit '" + kitName + "' removed. You may want to save the configuration."); } else if (args[0].equals("delete")) { if (!sender.hasPermission("ckit.delete")) { sender.sendMessage(ChatColor.RED + "You are not allowed to delete kits."); return true; } String kitName = args[1]; ChestKitsKit kit = config.getKit(kitName); if (kit == null) { sender.sendMessage(ChatColor.RED + "The kit '" + kitName + "' does not exist."); return true; } config.removeKit(kitName); sender.sendMessage("Kit '" + kitName + "' removed. You may want to save the configuration."); } else if (args[0].equals("save")) { if (!sender.hasPermission("ckit.save")) { sender.sendMessage(ChatColor.RED + "You do not have access to this command."); return true; } config.saveConfig(this); sender.sendMessage("Kits saved to file."); } else if (args[0].equals("give")) { if (!sender.hasPermission("ckit.give")) { sender.sendMessage(ChatColor.RED + "You do not have access to this command."); return true; } toGive = sender.getServer().getPlayer(args[1]); if (toGive == null || !toGive.isOnline()) { sender.sendMessage("The player " + args[0] + " is not online!"); return true; } if (args.length < 3) { sender.sendMessage(ChatColor.RED + "You must specify which kit to give the player!"); return true; } String kitName = args[2]; ChestKitsKit kit = config.getKit(kitName); if (kit == null) { sender.sendMessage(ChatColor.RED + "The kit '" + kitName + "' does not exist."); return true; } if (!sender.hasPermission("ckit.get." + kitName) && !sender.hasPermission("ckit.get.*")) { sender.sendMessage(ChatColor.RED + "You do not have access to that kit."); return true; } ItemStack is = new ItemStack(Material.CHEST, 1); ItemMeta meta = is.getItemMeta(); meta.setDisplayName("Kit " + kitName); meta.setLore(Arrays.asList(LORE_KEY)); is.setItemMeta(meta); if (!toGive.getInventory().addItem(is).isEmpty()) { sender.sendMessage(ChatColor.RED + "Your inventory is too full to hold the kit."); } else { toGive.sendMessage(ChatColor.GREEN + "You have been given a " + kitName + " kit!"); } } else { sender.sendMessage(ChatColor.RED + "Invalid secondary command. Valid secondary commands: create, delete, save config, give"); return true; } return true; } public void addItemsToChest(Block b1, String kitName) { ChestKitsKit kit = config.getKit(kitName); if (kit == null) { getLogger().severe("Unknown kit was placed: " + kitName); return; } BlockState bs1 = b1.getState(); if (!(bs1 instanceof Chest)) { getLogger().severe("Chest conversion failed? (" + bs1 + ")"); return; } Inventory i = ((Chest) bs1).getInventory(); int maxSlot = i.getSize(); int slot = 0; boolean updated = false; Iterator<ItemStack> itms = kit.getItems().iterator(); while (itms.hasNext()) { ItemStack itm = new ItemStack(itms.next()); if (slot >= maxSlot) { getLogger().severe("Kit " + kitName + " contains too many items! Removing excess..."); itms.remove(); updated = true; continue; } i.setItem(slot, itm); slot++; } if (updated) { config.saveConfig(this); } } }
package org.apdplat.extractor.html.demo; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class BBC { public static void main(String[] args) { String path = "/Users/apple//BBC/"; download("lower-intermediate", 30, path); download("intermediate", 25, path); download("emw", 15, path); } public static void download(String type, int count, String path) { int timeout = 300000; for(int i=1; i<=count; i++) { try { String url = "http: System.out.println("connect " + url); Document doc = Jsoup.connect(url).timeout(timeout).get(); Elements elements = doc.select("a"); for (Element element : elements) { try { String href = element.attr("href"); //mp3pdf if (href.endsWith(".mp3") || href.endsWith(".pdf")) { String[] attr = href.split("/"); String fileName = attr[attr.length - 1]; System.out.println("unit " + i + "find resource: " + href); Path dir = Paths.get(path, type); if(!Files.exists(dir)){ dir.toFile().mkdirs(); } Path out = Paths.get(path, type, fileName); //BBC if (!Files.exists(out)) { Connection.Response response = Jsoup.connect(href).maxBodySize(0).ignoreContentType(true).timeout(timeout).execute(); Files.write(out, response.bodyAsBytes()); System.out.println("unit " + i + "save resource to: " + out); } else { System.out.println("unit " + i + "resource exist, don't need to download"); } } } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } } } }
package com.google.sps.data; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; public final class User { private String name; private String email; private Set<String> interests; private Set<String> skills; private Set<Event> eventsHosting; private Set<Event> eventsParticipating; private Set<Event> eventsVolunteering; private String imageUrl; public static class Builder { // Required parameters private long userId; private String name; private String email; // Optional parameters private Set<String> interests = new HashSet<>(); private Set<String> skills = new HashSet<>(); private Set<Event> eventsHosting = new HashSet<>(); private Set<Event> eventsParticipating = new HashSet<>(); private Set<Event> eventsVolunteering = new HashSet<>(); private String imageUrl = ""; public Builder(String name, String email) { this.name = name; this.email = email; } public Builder setUserId(long id) { this.userId = id; return this; } public Builder setName(String name) { this.name = name; return this; } public Builder setEmail(String email) { this.email = email; return this; } public Builder setInterests(Set<String> interests) { this.interests = interests; return this; } public Builder addInterest(String interest) { this.interests.add(interest); return this; } public Builder removeInterest(String interest) { this.interests.remove(interest); return this; } public Builder setSkills(Set<String> skills) { this.skills = skills; return this; } public Builder addSkill(String skill) { this.skills.add(skill); return this; } public Builder removeSkill(String skill) { this.skills.remove(skill); return this; } public Builder setEventsHosting(Set<Event> eventsHosting) { this.eventsHosting = eventsHosting; return this; } public Builder addEventHosting(Event eventHosting) { this.eventsHosting.add(eventHosting); return this; } public Builder removeEventHosting(Event eventHosting) { this.eventsHosting.remove(eventHosting); return this; } public Builder setEventsParticipating(Set<Event> eventsParticipating) { this.eventsParticipating = eventsParticipating; return this; } public Builder addEventParticipating(Event eventParticipating) { this.eventsParticipating.add(eventParticipating); return this; } public Builder removeEventParticipating(Event eventParticipating) { this.eventsParticipating.remove(eventParticipating); return this; } public Builder setEventsVolunteering(Set<Event> eventsVolunteering) { this.eventsVolunteering = eventsVolunteering; return this; } public Builder addEventVolunteering(Event eventVolunteering) { this.eventsVolunteering.add(eventVolunteering); return this; } public Builder removeEventVolunteering(Event eventVolunteering) { this.eventsVolunteering.remove(eventVolunteering); return this; } public Builder setImageUrl(String imageUrl) { this.imageUrl = imageUrl; return this; } public User build() { return new User(this); } private Builder mergeFrom(User other) { this.name = other.getName(); this.email = other.getEmail(); if (!other.getInterests().isEmpty()) { this.interests = other.getInterests(); } if (!other.getSkills().isEmpty()) { this.skills = other.getSkills(); } if (!other.getEventsHosting().isEmpty()) { this.eventsHosting = other.getEventsHosting(); } if (!other.getEventsParticipating().isEmpty()) { this.eventsParticipating = other.getEventsParticipating(); } if (!other.getEventsVolunteering().isEmpty()) { this.eventsVolunteering = other.getEventsVolunteering(); } if (!other.getImageUrl().isEmpty()) { this.imageUrl = other.getImageUrl(); } return this; } } private User(Builder builder) { this.name = builder.name; this.email = builder.email; this.interests = builder.interests; this.skills = builder.skills; this.eventsHosting = builder.eventsHosting; this.eventsParticipating = builder.eventsParticipating; this.eventsVolunteering = builder.eventsVolunteering; this.imageUrl = builder.imageUrl; } public String getName() { return this.name; } public String getEmail() { return this.email; } public Set<String> getInterests() { return this.interests; } public Set<String> getSkills() { return this.skills; } public Set<Event> getEventsHosting() { return this.eventsHosting; } public Set<String> getEventsHostingIds() { return eventsHosting.stream().map(Event::getId).collect(Collectors.toSet()); } public Set<Event> getEventsParticipating() { return this.eventsParticipating; } public Set<String> getEventsParticipatingIds() { return eventsParticipating.stream().map(Event::getId).collect(Collectors.toSet()); } public Set<Event> getEventsVolunteering() { return this.eventsVolunteering; } public Set<String> getEventsVolunteeringIds() { return eventsVolunteering.stream().map(Event::getId).collect(Collectors.toSet()); } public String getImageUrl() { return this.imageUrl; } public Builder toBuilder() { return new Builder(this.name, this.email).mergeFrom(this); } @Override public String toString() { return String.format("User:\t%s\nE-mail:\t%s", this.name, this.email); } }
package eu.amidst.huginlink.learning; import COM.hugin.HAPI.*; import com.google.common.base.Stopwatch; import eu.amidst.core.datastream.DataInstance; import eu.amidst.core.datastream.DataOnMemory; import eu.amidst.core.datastream.DataStream; import eu.amidst.core.distribution.Multinomial; import eu.amidst.core.learning.parametric.ParallelMLMissingData; import eu.amidst.core.learning.parametric.ParallelMaximumLikelihood; import eu.amidst.core.models.BayesianNetwork; import eu.amidst.core.models.DAG; import eu.amidst.core.utils.*; import eu.amidst.core.variables.Variable; import eu.amidst.core.variables.Variables; import eu.amidst.huginlink.converters.BNConverterToAMIDST; import eu.amidst.huginlink.converters.BNConverterToHugin; import eu.amidst.huginlink.inference.HuginInference; import java.io.IOException; import java.util.Arrays; public class ParallelTAN implements AmidstOptionsHandler { /** Represents the number of samples on memory. */ private int numSamplesOnMemory; /** Represents the number of cores to be exploited during the parallel learning. */ private int numCores; /** Represents the batch size. */ private int batchSize; /** Represents the name of the variable acting as a root of the tree in the TAN model. */ String nameRoot; /** Represents the name of the class variable in the TAN model */ String nameTarget; /** Indicates if the learning is performed in parallel or not. */ boolean parallelMode; /** Represents the learned BN**/ BayesianNetwork learnedBN; /** Represents the inference engine for the predections*/ HuginInference inference = null; /** Represents the class varible of the model*/ private Variable targetVar; /** * Class constructor. */ public ParallelTAN() { } /** * Sets the running mode, i.e., either parallel or sequential. * @param parallelMode true if the running mode is parallel, false otherwise. */ public void setParallelMode(boolean parallelMode) { this.parallelMode = parallelMode; if (parallelMode) this.numCores = Runtime.getRuntime().availableProcessors(); else this.numCores=1; } /** * Returns the batch size to be used during the learning process. * @return the batch size. */ public int getBatchSize() { return batchSize; } /** * Sets the batch size. * @param batchSize the batch size. */ public void setBatchSize(int batchSize) { this.batchSize = batchSize; } /** * Returns the number of samples on memory. * @return the number of samples on memory. */ public int getNumSamplesOnMemory() { return numSamplesOnMemory; } /** * Sets the number of samples on memory * @param numSamplesOnMemory_ the number of samples on memory */ public void setNumSamplesOnMemory(int numSamplesOnMemory_) { this.numSamplesOnMemory = numSamplesOnMemory_; } /** * Returns the number of cores to be used during the learning process. * @return the number of cores. */ public int getNumCores() { return numCores; } /** * Sets the number of cores to be used during the learning process. * @param numCores_ the number of cores. */ public void setNumCores(int numCores_) { this.numCores = numCores_; } /** * Sets the name of the variable acting as a root of the tree in the TAN model. * @param nameRoot the name of the root variable. */ public void setNameRoot(String nameRoot) { this.nameRoot = nameRoot; } /** * Sets the name of the class variable in the TAN model. * @param nameTarget the name of the class variable. */ public void setNameTarget(String nameTarget) { this.nameTarget = nameTarget; } /** * Gets the name of the class variable in the TAN model. */ public String getNameTarget() { return this.nameTarget; } /** * Predicts the class membership probabilities for a given instance. * @param instance the data instance to be classified. * @return an array of doubles containing the estimated membership probabilities of the data instance for each class label. */ public double[] predict(DataInstance instance) { if (learnedBN==null) throw new IllegalArgumentException("The model has not been learned"); if (!Utils.isMissingValue(instance.getValue(targetVar))) System.out.println("Class Variable can not be set."); this.inference.setEvidence(instance); this.inference.runInference(); Multinomial dist = this.inference.getPosterior(targetVar); return dist.getParameters(); } /** * Learns a TAN structure from data using the Chow-Liu algorithm included in the Hugin API. * Parallel learning is performed only if the parallel mode was set to true. * @param dataStream a stream of data instances to be processed during the TAN structural learning. * @return a <code>DAG</code> structure in AMIDST format. * @throws ExceptionHugin */ public DAG learnDAG(DataStream dataStream) throws ExceptionHugin { Variables modelHeader = new Variables(dataStream.getAttributes()); this.targetVar = modelHeader.getVariableByName(this.nameTarget); DAG dag = new DAG(modelHeader); BayesianNetwork bn = new BayesianNetwork(dag); Domain huginNetwork = null; try { huginNetwork = BNConverterToHugin.convertToHugin(bn); } catch (ExceptionHugin exceptionHugin) { System.out.println("ParallelTan LearnDAG Error 1"); exceptionHugin.printStackTrace(); throw new IllegalStateException("Hugin Exception: " + exceptionHugin.getMessage()); } DataOnMemory dataOnMemory = ReservoirSampling.samplingNumberOfSamples(this.numSamplesOnMemory, dataStream); // Set the number of cases int numCases = dataOnMemory.getNumberOfDataInstances(); try { huginNetwork.setNumberOfCases(numCases); huginNetwork.setConcurrencyLevel(this.numCores); } catch (ExceptionHugin exceptionHugin) { System.out.println("ParallelTan LearnDAG Error 2"); exceptionHugin.printStackTrace(); throw new IllegalStateException("Hugin Exception: " + exceptionHugin.getMessage()); } NodeList nodeList = huginNetwork.getNodes(); // It is more efficient to loop the matrix of values in this way. 1st variables and 2nd cases for (int i = 0; i < nodeList.size(); i++) { Variable var = bn.getDAG().getVariables().getVariableById(i); Node n = nodeList.get(i); try { if (n.getKind().compareTo(NetworkModel.H_KIND_DISCRETE) == 0) { ((DiscreteChanceNode) n).getExperienceTable(); for (int j = 0; j < numCases; j++) { double state = dataOnMemory.getDataInstance(j).getValue(var); if (!Utils.isMissingValue(state)) { ((DiscreteChanceNode) n).setCaseState(j, (int) state); } } } else { ((ContinuousChanceNode) n).getExperienceTable(); for (int j = 0; j < numCases; j++) { double value = dataOnMemory.getDataInstance(j).getValue(var); if (!Utils.isMissingValue(value)) ((ContinuousChanceNode) n).setCaseValue(j, value); } } } catch (ExceptionHugin exceptionHugin) { System.out.println("ParallelTan LearnDAG Error 3 with node " + Integer.toString(i)); exceptionHugin.printStackTrace(); throw new IllegalStateException("Hugin Exception: " + exceptionHugin.getMessage()); } // if(i==0 || i==6) { // System.out.println("Node " + i); // System.out.println(Arrays.toString(n.getTable().getData())); // System.out.println(Arrays.toString (((DiscreteChanceNode) n).getExperienceTable().getData())); // System.out.println(((DiscreteChanceNode) n).getEnteredValue()); // System.out.println(n.getChildren().stream().count()); } //Structural learning DiscreteChanceNode root, target; try { root = (DiscreteChanceNode)huginNetwork.getNodeByName(nameRoot); target = (DiscreteChanceNode)huginNetwork.getNodeByName(nameTarget); } catch (ExceptionHugin exceptionHugin) { System.out.println("ParallelTan LearnDAG Error 4"); exceptionHugin.printStackTrace(); throw new IllegalStateException("Hugin Exception: " + exceptionHugin.getMessage()); } Stopwatch watch = Stopwatch.createStarted(); try { System.out.println("Root: " + root.getName()); System.out.println("Target: " + target.getName()); //root.getHome().getNodes().stream().forEach(node -> System.out.println(node.getName()) huginNetwork.learnChowLiuTree(root, target); } catch (ExceptionHugin exceptionHugin) { System.out.println("ParallelTan LearnDAG Error 5"); exceptionHugin.printStackTrace(); throw new IllegalStateException("Hugin Exception: " + exceptionHugin.getMessage()); } System.out.println("Structural Learning in Hugin: " + watch.stop()); DAG dagLearned; try { dagLearned = (BNConverterToAMIDST.convertToAmidst(huginNetwork)).getDAG(); dagLearned.getVariables().setAttributes(dataStream.getAttributes()); } catch (ExceptionHugin exceptionHugin) { System.out.println("ParallelTan LearnDAG Error 6"); exceptionHugin.printStackTrace(); throw new IllegalStateException("Hugin Exception: " + exceptionHugin.getMessage()); } return dagLearned; } /** * Learns the parameters of a TAN structure using the {@link eu.amidst.core.learning.parametric.ParallelMaximumLikelihood}. * @param dataStream a stream of data instances for learning the parameters. * @return a <code>BayesianNetwork</code> object in ADMIST format. * @throws ExceptionHugin */ public BayesianNetwork learn(DataStream<DataInstance> dataStream) { try { ParallelMLMissingData parameterLearningAlgorithm = new ParallelMLMissingData(); parameterLearningAlgorithm.setLaplace(true); parameterLearningAlgorithm.setParallelMode(this.parallelMode); parameterLearningAlgorithm.setDAG(this.learnDAG(dataStream)); parameterLearningAlgorithm.setDataStream(dataStream); parameterLearningAlgorithm.initLearning(); parameterLearningAlgorithm.runLearning(); learnedBN = parameterLearningAlgorithm.getLearntBayesianNetwork(); this.inference = new HuginInference(); this.inference.setModel(this.learnedBN); return this.learnedBN; }catch (ExceptionHugin ex){ throw new IllegalStateException("Hugin Exception: " + ex.getMessage()); } } /** * Learns the parameters of a TAN structure using the {@link eu.amidst.core.learning.parametric.ParallelMaximumLikelihood}. * @param dataStream a stream of data instances for learning the parameters. * @param batchSize the size of the batch for the parallel ML algorithm. * @return a <code>BayesianNetwork</code> object in ADMIST format. * @throws ExceptionHugin */ public BayesianNetwork learn(DataStream<DataInstance> dataStream, int batchSize) throws ExceptionHugin { ParallelMLMissingData parameterLearningAlgorithm = new ParallelMLMissingData(); parameterLearningAlgorithm.setBatchSize(batchSize); parameterLearningAlgorithm.setParallelMode(this.parallelMode); parameterLearningAlgorithm.setDAG(this.learnDAG(dataStream)); parameterLearningAlgorithm.setDataStream(dataStream); parameterLearningAlgorithm.initLearning(); parameterLearningAlgorithm.runLearning(); learnedBN = parameterLearningAlgorithm.getLearntBayesianNetwork(); this.inference = new HuginInference(); this.inference.setModel(this.learnedBN); return this.learnedBN; } /** * {@inheritDoc} */ @Override public String listOptions(){ return this.classNameID() +",\\"+ "-numSamplesOnMemory, 1000, Number of samples on memory\\" + "-numCores,"+Runtime.getRuntime().availableProcessors()+", Number of cores\\" + "-batchSize, 1000, Batch size\\"+ "-nameRoot, root, Name of root variable.\\" + "-nameTarget, target, Name of target variable\\" + "-parallelMode, true, Run in parallel\\"; } /** * {@inheritDoc} */ public void loadOptions(){ this.setNumSamplesOnMemory(this.getIntOption("-numSamplesOnMemory")); this.setNumCores(this.getIntOption("-numCores")); this.setBatchSize(this.getIntOption("-batchSize")); this.setNameRoot(this.getOption("-nameRoot")); this.setNameTarget(this.getOption("-nameTarget")); this.setParallelMode(this.getBooleanOption("-parallelMode")); } /** * {@inheritDoc} */ @Override public String listOptionsRecursively() { return this.listOptions() + "\n" + BayesianNetwork.listOptionsRecursively() + "\n" + AmidstOptionsHandler.listOptionsRecursively(BayesianNetworkSampler.class); } /** * {@inheritDoc} */ @Override public String classNameID() { return "ParallelTAN"; } public static void main(String[] args) throws IOException { OptionParser.setArgsOptions(ParallelTAN.class, args); BayesianNetworkGenerator.loadOptions(); BayesianNetworkGenerator.setNumberOfGaussianVars(0); BayesianNetworkGenerator.setNumberOfMultinomialVars(2000, 10); BayesianNetworkGenerator.setSeed(0); BayesianNetwork bn = BayesianNetworkGenerator.generateNaiveBayes(2); int sampleSize = 5000; BayesianNetworkSampler sampler = new BayesianNetworkSampler(bn); sampler.loadOptions(); DataStream<DataInstance> data = sampler.sampleToDataStream(sampleSize); for (int i = 1; i <= 4; i++) { int samplesOnMemory = 1000; int numCores = i; System.out.println("Learning TAN: " + samplesOnMemory + " samples on memory, " + numCores + "core/s ..."); ParallelTAN tan = new ParallelTAN(); tan.setOptions(args); //tan.loadOptionsFromFile("configurationFiles/conf.txt"); tan.setNumCores(numCores); tan.setNumSamplesOnMemory(samplesOnMemory); tan.setNameRoot(bn.getVariables().getListOfVariables().get(0).getName()); tan.setNameTarget(bn.getVariables().getListOfVariables().get(1).getName()); Stopwatch watch = Stopwatch.createStarted(); BayesianNetwork model = tan.learn(data); System.out.println(watch.stop()); } } }
package com.jcwhatever.bukkit.rental.region; import com.jcwhatever.bukkit.generic.file.GenericsByteReader; import com.jcwhatever.bukkit.generic.file.GenericsByteWriter; import com.jcwhatever.bukkit.generic.pathing.InteriorFinder; import com.jcwhatever.bukkit.generic.pathing.InteriorFinder.InteriorResults; import com.jcwhatever.bukkit.generic.regions.BuildMethod; import com.jcwhatever.bukkit.generic.regions.RestorableRegion; import com.jcwhatever.bukkit.generic.storage.IDataNode; import com.jcwhatever.bukkit.generic.utils.DateUtils; import com.jcwhatever.bukkit.generic.utils.LocationUtils; import com.jcwhatever.bukkit.generic.utils.PreCon; import com.jcwhatever.bukkit.rental.BillCollector; import com.jcwhatever.bukkit.rental.Msg; import com.jcwhatever.bukkit.rental.RentalRooms; import com.jcwhatever.bukkit.rental.Tenant; import com.jcwhatever.bukkit.rental.events.RentMoveInEvent; import com.jcwhatever.bukkit.rental.events.RentMoveOutEvent; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; public class RentRegion extends RestorableRegion { private Tenant _tenant; private Set<Location> _tenantArea; private boolean _isEditModeOn = false; private Date _rentExpiration = null; private FriendManager _friendManager; private static final int INTERIOR_FILE_VERSION = 1; IDataNode _tenantInfo; public RentRegion(String name, IDataNode dataNode) { super(RentalRooms.getInstance(), name, dataNode); PreCon.notNull(dataNode); _tenantArea = new HashSet<Location>(100); _tenantInfo = dataNode.getNode("tenant"); loadSettings(); loadInterior(); _friendManager = new FriendManager(this, dataNode.getNode("friends")); } public FriendManager getFriendManager() { return _friendManager; } public void setPayed() { BillCollector billCollector = RentalRooms.getInstance().getBillCollector(); _rentExpiration = _rentExpiration == null ? org.apache.commons.lang.time.DateUtils.addDays(new Date(), billCollector.getRentCycle()) : org.apache.commons.lang.time.DateUtils.addDays(_rentExpiration, billCollector.getRentCycle()); SimpleDateFormat dateFormat = new SimpleDateFormat(); getDataNode().set("rent-expiration", dateFormat.format(_rentExpiration)); getDataNode().saveAsync(null); } public Date getExpirationDate() { return _rentExpiration; } public String getFormattedExpiration() { return DateUtils.format(getExpirationDate(), RentalRooms.DATE_FORMAT); } public boolean isEditModeOn() { return _isEditModeOn; } public void setIsEditModeOn(boolean isEditModeOn) { _isEditModeOn = isEditModeOn; } @Override protected String getFilePrefix() { return "rent." + getName(); } @Override protected boolean onOwnerChanged(UUID oldOwnerId, UUID ownerId) { if (_tenant != null) { evict(); } _tenant = Tenant.add(ownerId, this); RentMoveInEvent.callEvent(this, _tenant); return true; } public void setTenant(Player p) { setOwner(p.getUniqueId()); } public void setTenant(UUID playerId) { setOwner(playerId); } public boolean hasTenant() { return _tenant != null; } public Tenant getTenant() { return _tenant; } public void evict() { super.setOwner(null); Tenant oldTenant = _tenant; _tenant = null; if (this.canRestore()) { try { this.restoreData(BuildMethod.PERFORMANCE); } catch (IOException e) { e.printStackTrace(); } } _rentExpiration = null; //noinspection ConstantConditions getDataNode().set("rent-expiration", null); getDataNode().saveAsync(null); RentMoveOutEvent.callEvent(this, oldTenant); } public int getRentSpaceVolume() { return _tenantArea.size(); } public boolean isTenantArea(Location location) { return _tenantArea.contains(location); } public boolean canInteract(Player p, Location location) { return canInteract(p.getUniqueId(), location); } public boolean canInteract(UUID playerId, Location location) { if (_isEditModeOn) return true; location = LocationUtils.getBlockLocation(location); if (_tenant == null || playerId == null || location == null || !isDefined()) return false; // tenant equals method works with UUID's return (_tenant.equals(playerId) || _friendManager.hasFriend(playerId)) && _tenantArea.contains(location); } public boolean isTenantOrFriend(Player p) { return isTenantOrFriend(p.getUniqueId()); } public boolean isTenantOrFriend(UUID playerId) { return _tenant != null && (_tenant.equals(playerId) || _friendManager.hasFriend(playerId)); } public int addInterior(Location start) { InteriorFinder finder = new InteriorFinder(); InteriorResults results = finder.searchInterior(start, this); Set<Location> interior = results.getNodes(); _tenantArea.addAll(interior); saveInterior(); return interior.size(); } public void clearInterior() { _tenantArea.clear(); try { getInteriorFile(true); // delete interior file } catch (IOException e) { e.printStackTrace(); } } private void loadSettings() { UUID tenantId = super.getOwnerId(); if (tenantId == null) return; _tenant = Tenant.add(tenantId, this); _rentExpiration = null; //noinspection ConstantConditions String expiresStr = getDataNode().getString("rent-expiration"); if (expiresStr != null) { SimpleDateFormat format = new SimpleDateFormat(); try { _rentExpiration = format.parse(expiresStr); } catch (ParseException e) { e.printStackTrace(); } } } private File getInteriorFile(boolean deleteIfExists) throws IOException { File interiorDir = new File(getDataFolder(), "interiors"); if (!interiorDir.exists() && !interiorDir.mkdir()) throw new IOException("Failed to create interior file folder."); File file = new File(interiorDir, getFilePrefix() + ".bin"); if (deleteIfExists && file.exists() && !file.delete()) throw new IOException("Failed to delete interior file."); return file; } private void loadInterior() { File file; try { file = getInteriorFile(false); } catch (IOException e) { e.printStackTrace(); return; } if (!file.exists()) return; Bukkit.getScheduler().runTaskAsynchronously(RentalRooms.getInstance(), new LoadInterior(this, file)); } private void saveInterior() { File file; try { file = getInteriorFile(true); } catch (IOException e) { e.printStackTrace(); return; } Bukkit.getScheduler().runTaskAsynchronously(RentalRooms.getInstance(), new SaveInterior(this, _tenantArea, file)); } private static final class LoadInterior implements Runnable { private RentRegion _region; private List<Location> _interior; private File _file; public LoadInterior(RentRegion region, File file) { _region = region; _file = file; } @Override public void run() { GenericsByteReader reader = null; try { reader = new GenericsByteReader(new FileInputStream(_file)); int fileVersion = reader.getInteger(); if (fileVersion != INTERIOR_FILE_VERSION) { Msg.warning("Failed to load interior file because it's not the correct version: {0}", _file.getName()); return; } reader.getString(); // get region name String worldName = reader.getString(); World world = Bukkit.getWorld(worldName); if (world == null) { Msg.warning("Failed to load interior file because the world it's in ({0}) is not loaded: {1}", worldName, _file.getName()); return; } reader.getLocation(); reader.getLocation(); int size = reader.getInteger(); _interior = new ArrayList<Location>(size + 2); for (int i=0; i < size; i++) { Location loc = reader.getLocation(); if (loc != null) _interior.add(loc); } } catch (IOException e) { e.printStackTrace(); return; } finally { try { if (reader != null) reader.close(); } catch (IOException e) { e.printStackTrace(); } } Bukkit.getScheduler().scheduleSyncDelayedTask(RentalRooms.getInstance(), new Runnable () { @Override public void run() { _region._tenantArea.clear(); _region._tenantArea.addAll(_interior); } }); } } private static final class SaveInterior implements Runnable { private RentRegion _region; private List<Location> _interior; private File _file; public SaveInterior(RentRegion region, Set<Location> interior, File file) { _region = region; _interior = new ArrayList<Location>(interior); _file = file; } @Override public void run() { GenericsByteWriter writer = null; try { _file.createNewFile(); writer = new GenericsByteWriter(new FileOutputStream(_file)); writer.write(INTERIOR_FILE_VERSION); writer.write(_region.getName()); writer.write(_region.getWorld().getName()); writer.write(_region.getP1()); writer.write(_region.getP2()); writer.write(_interior.size()); for (Location loc : _interior) { writer.write(loc); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (writer != null) writer.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
package com.nilhcem.hostseditor.list; import java.util.ArrayList; import java.util.List; import java.util.Locale; import javax.inject.Inject; import android.os.Bundle; import android.util.Log; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ListView; import com.actionbarsherlock.view.ActionMode; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.nilhcem.hostseditor.R; import com.nilhcem.hostseditor.bus.event.StartAddEditActivityEvent; import com.nilhcem.hostseditor.bus.event.RefreshHostsEvent; import com.nilhcem.hostseditor.bus.event.TaskCompletedEvent; import com.nilhcem.hostseditor.core.BaseFragment; import com.nilhcem.hostseditor.core.HostsManager; import com.nilhcem.hostseditor.model.Host; import com.nilhcem.hostseditor.task.AddEditHostAsync; import com.nilhcem.hostseditor.task.GenericTaskAsync; import com.nilhcem.hostseditor.task.ListHostsAsync; import com.nilhcem.hostseditor.task.RemoveHostsAsync; import com.nilhcem.hostseditor.task.ToggleHostsAsync; import com.squareup.otto.Subscribe; public class ListHostsFragment extends BaseFragment implements OnItemClickListener, OnItemLongClickListener { static final String TAG = "ListHostsFragment"; @Inject HostsManager mHostsManager; private ListHostsAdapter mAdapter; private ActionMode mMode; private ListView mListView; private MenuItem mEditMenuItem; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAdapter = new ListHostsAdapter(mActivity.getApplicationContext()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (mListView == null) { mListView = new ListView(mActivity.getApplicationContext()); mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); mListView.setFastScrollEnabled(true); mListView.setItemsCanFocus(false); mListView.setOnItemClickListener(this); mListView.setOnItemLongClickListener(this); refreshHosts(false); } else { // detach from container and return the same view ((ViewGroup) mListView.getParent()).removeAllViews(); } return mListView; } @Override public void onPause() { finishActionMode(); super.onPause(); } @Override public void onResume() { super.onResume(); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { int nbCheckedElements = 0; SparseBooleanArray checked = mListView.getCheckedItemPositions(); for (int i = 0; i < checked.size(); i++) { if (checked.valueAt(i)) { nbCheckedElements++; } } if (nbCheckedElements > 0) { if (mMode == null) { mMode = mActivity.startActionMode(new ModeCallback()); } if (mEditMenuItem != null) { mEditMenuItem.setVisible(nbCheckedElements == 1); } mMode.setTitle(String.format(Locale.US, getString(R.string.list_menu_selected), nbCheckedElements)); } else { finishActionMode(); } } @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { if (mMode == null) { Host host = mAdapter.getItem(position); mBus.post(new StartAddEditActivityEvent(host)); return true; } return false; } @Subscribe public void onTaskFinished(TaskCompletedEvent task) { Log.d(TAG, "Task " + task.getTag() + " finished"); if (task.isSuccessful()) { refreshHosts(false); } else { // Display error message // Force reload } } @Subscribe public void onHostsRefreshed(RefreshHostsEvent hosts) { Log.d(TAG, "Refreshing listview"); finishActionMode(); mAdapter.updateHosts(hosts.get()); mListView.setAdapter(mAdapter); } public void addHost(Host[] hosts) { runGenericTask(AddEditHostAsync.class, hosts); } public void refreshHosts(boolean forceRefresh) { mAdapter.updateHosts(new ArrayList<Host>()); mApp.getObjectGraph().get(ListHostsAsync.class).execute(forceRefresh); } private final class ModeCallback implements ActionMode.Callback { @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = mActivity.getSupportMenuInflater(); inflater.inflate(R.menu.hosts_list_contextual_actions, menu); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { mEditMenuItem = menu.findItem(R.id.cab_action_edit); return false; } @Override public void onDestroyActionMode(ActionMode mode) { for (int i = 0; i < mListView.getAdapter().getCount(); i++) { mListView.setItemChecked(i, false); } mMode = null; mEditMenuItem = null; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { Host[] selectedItems = getSelectedItems(); switch (item.getItemId()) { case R.id.cab_action_edit: mBus.post(new StartAddEditActivityEvent(selectedItems[0])); break; case R.id.cab_action_delete: runGenericTask(RemoveHostsAsync.class, selectedItems); break; case R.id.cab_action_toggle: runGenericTask(ToggleHostsAsync.class, selectedItems); break; default: return false; } mode.finish(); return true; } private Host[] getSelectedItems() { List<Host> items = new ArrayList<Host>(); int len = mListView.getCount(); SparseBooleanArray checked = mListView.getCheckedItemPositions(); for (int i = 0; i < len ; i++) { if (checked.get(i)) { items.add(mAdapter.getItem(i)); } } return items.toArray(new Host[items.size()]); } }; private void runGenericTask(Class<? extends GenericTaskAsync> clazz, Host[] hosts) { GenericTaskAsync task = mApp.getObjectGraph().get(clazz); task.setAppContext(mActivity.getApplicationContext()); task.execute(hosts); } private void finishActionMode() { if (mMode != null) { mMode.finish(); } } }
package com.pauldavdesign.mineauz.minigames; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.FireworkEffect; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.OfflinePlayer; import org.bukkit.FireworkEffect.Type; import org.bukkit.configuration.Configuration; import org.bukkit.entity.EntityType; import org.bukkit.entity.Firework; import org.bukkit.entity.Player; import org.bukkit.entity.Vehicle; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.FireworkMeta; import org.bukkit.potion.PotionEffect; import org.bukkit.scoreboard.Scoreboard; import com.pauldavdesign.mineauz.minigames.events.EndMinigameEvent; import com.pauldavdesign.mineauz.minigames.events.EndTeamMinigameEvent; import com.pauldavdesign.mineauz.minigames.events.JoinMinigameEvent; import com.pauldavdesign.mineauz.minigames.events.QuitMinigameEvent; import com.pauldavdesign.mineauz.minigames.events.RevertCheckpointEvent; import com.pauldavdesign.mineauz.minigames.events.SpectateMinigameEvent; import com.pauldavdesign.mineauz.minigames.scoring.ScoreTypes; public class PlayerData { private Map<String, Minigame> minigamePlayers = new HashMap<String, Minigame>(); private Map<String, Location> playerCheckpoints = new HashMap<String, Location>(); private Map<String, StoredPlayerCheckpoints> storedPlayerCheckpoints = new HashMap<String, StoredPlayerCheckpoints>(); private Map<String, ItemStack[]> itemStore = new HashMap<String, ItemStack[]>(); private Map<String, ItemStack[]> armourStore = new HashMap<String, ItemStack[]>(); private Map<String, List<String>> playerFlags = new HashMap<String, List<String>>(); private Map<String, Integer> playerFood = new HashMap<String, Integer>(); private Map<String, Integer> playerHealth = new HashMap<String, Integer>(); private Map<String, Float> playerSaturation = new HashMap<String, Float>(); private Map<String, Boolean> allowTP = new HashMap<String, Boolean>(); private Map<String, Boolean> allowGMChange = new HashMap<String, Boolean>(); private Map<String, GameMode> lastGM = new HashMap<String, GameMode>(); private Map<String, Scoreboard> lastScoreboard = new HashMap<String, Scoreboard>(); private boolean partyMode = false; private Map<String, Location> dcPlayers = new HashMap<String, Location>(); private List<String> deniedCommands = new ArrayList<String>(); //Stats private Map<String, Integer> plyDeaths = new HashMap<String, Integer>(); private Map<String, Integer> plyKills = new HashMap<String, Integer>(); private Map<String, Integer> plyScore = new HashMap<String, Integer>(); private static Minigames plugin = Minigames.plugin; private MinigameData mdata = plugin.mdata; MinigameSave invsave = new MinigameSave("playerinv"); public PlayerData(){} public void joinMinigame(Player player, Minigame minigame) { String gametype = minigame.getType(); JoinMinigameEvent event = new JoinMinigameEvent(player, minigame); Bukkit.getServer().getPluginManager().callEvent(event); if(!event.isCancelled()){ if(mdata.getMinigameTypes().contains(gametype)){ setAllowTP(player, true); if(mdata.minigameType(gametype).joinMinigame(player, minigame)){ plugin.getLogger().info(player.getName() + " started " + minigame.getName()); mdata.sendMinigameMessage(minigame, player.getName() + " has joined " + minigame.getName(), null, player); setAllowGMChange(player, true); setAllowGMChange(player, false); player.setAllowFlight(false); setAllowTP(player, false); if(hasStoredPlayerCheckpoint(player)){ if(getPlayersStoredCheckpoints(player).hasCheckpoint(minigame.getName())){ playerCheckpoints.put(player.getName(), getPlayersStoredCheckpoints(player).getCheckpoint(minigame.getName())); if(getPlayersStoredCheckpoints(player).hasFlags(minigame.getName())){ playerFlags.put(player.getName(), getPlayersStoredCheckpoints(player).getFlags(minigame.getName())); } getPlayersStoredCheckpoints(player).removeCheckpoint(minigame.getName()); getPlayersStoredCheckpoints(player).removeFlags(minigame.getName()); if(getPlayersStoredCheckpoints(player).hasNoCheckpoints() && !getPlayersStoredCheckpoints(player).hasGlobalCheckpoint()){ storedPlayerCheckpoints.remove(player.getName()); } revertToCheckpoint(player); } } for(Player pl : minigame.getSpectators()){ player.hidePlayer(pl); } for(PotionEffect potion : player.getActivePotionEffects()){ player.removePotionEffect(potion.getType()); } } } else{ player.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "That gametype doesn't exist!"); } } } public void spectateMinigame(Player player, Minigame minigame) { SpectateMinigameEvent event = new SpectateMinigameEvent(player, minigame); Bukkit.getServer().getPluginManager().callEvent(event); if(!event.isCancelled()){ storePlayerData(player, GameMode.ADVENTURE); addPlayerMinigame(player, minigame); setAllowTP(player, true); setAllowGMChange(player, true); minigame.addSpectator(player); player.getInventory().clear(); player.teleport(minigame.getStartLocations().get(0)); setAllowTP(player, false); setAllowGMChange(player, false); if(minigame.canSpectateFly()){ player.setAllowFlight(true); } for(Player pl : minigame.getPlayers()){ pl.hidePlayer(player); } player.setScoreboard(minigame.getScoreboardManager()); for(PotionEffect potion : player.getActivePotionEffects()){ player.removePotionEffect(potion.getType()); } player.sendMessage(ChatColor.AQUA + "[Minigames] " + ChatColor.WHITE + "You have started spectating " + minigame + ".\n" + "Type \"/minigame quit\" to leave spectator mode."); mdata.sendMinigameMessage(minigame, player.getName() + " is now spectating " + minigame, null, player); } } public void joinWithBet(Player player, Minigame minigame, Double money){ JoinMinigameEvent event = new JoinMinigameEvent(player, minigame, true); Bukkit.getServer().getPluginManager().callEvent(event); if(!event.isCancelled()){ if(minigame != null && minigame.isEnabled() && (minigame.getMpTimer() == null || minigame.getMpTimer().getPlayerWaitTimeLeft() != 0)){ if(minigame.getMpBets() == null && (player.getItemInHand().getType() != Material.AIR || money != 0)){ minigame.setMpBets(new MultiplayerBets()); } MultiplayerBets pbet = minigame.getMpBets(); ItemStack item = player.getItemInHand().clone(); if(pbet != null && ((money != 0 && pbet.canBet(player, money) && plugin.getEconomy().getBalance(player.getName()) >= money) || (pbet.canBet(player, item) && item.getType() != Material.AIR && pbet.betValue(item.getType()) > 0))){ if(minigame.getPlayers().isEmpty() || minigame.getPlayers().size() != minigame.getMaxPlayers()){ player.sendMessage(ChatColor.AQUA + "[Minigames] " + ChatColor.WHITE + "You've placed your bet! Good Luck!"); if(money == 0){ pbet.addBet(player, item); } else{ pbet.addBet(player, money); plugin.getEconomy().withdrawPlayer(player.getName(), money); } player.getInventory().removeItem(new ItemStack(item.getType(), 1)); joinMinigame(player, minigame); } else{ player.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "Sorry, this minigame is full."); } } else if(item.getType() == Material.AIR && money == 0){ player.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "You can not bet nothing!"); } else if(money != 0 && !pbet.canBet(player, money)){ player.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "You haven't placed the correct bet amount for this round!"); player.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "You must bet $" + minigame.getMpBets().getHighestMoneyBet() + "."); } else if(money != 0 && plugin.getEconomy().getBalance(player.getName()) < money){ player.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "You haven't got enough money!"); player.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "You must have $" + minigame.getMpBets().getHighestMoneyBet() + "."); } else{ player.sendMessage(ChatColor.RED + "You haven't bet the correct item for this round!"); player.sendMessage(ChatColor.RED + "You must bet a " + minigame.getMpBets().highestBetName() + "."); } } else if(minigame != null && minigame.getMpTimer() != null && minigame.getMpTimer().getPlayerWaitTimeLeft() == 0){ player.sendMessage(ChatColor.RED + "The game has already started. Please try again later."); } } } public void startMPMinigame(String minigame){ List<Player> players = new ArrayList<Player>(); players.addAll(mdata.getMinigame(minigame).getPlayers()); for(Player pl : players){ setAllowTP(pl, true); } Collections.shuffle(players); Minigame mgm = mdata.getMinigame(minigame); if(mgm.getType().equals("teamdm") && ScoreTypes.getScoreType(mgm.getScoreType()) != null){ ScoreTypes.getScoreType(mgm.getScoreType()).balanceTeam(players, mgm); } Location start = null; int pos = 0; int bluepos = 0; int redpos = 0; for(Player ply : players){ if(!mgm.getType().equals("teamdm")){ if(pos < mgm.getStartLocations().size()){ start = mgm.getStartLocations().get(pos); ply.teleport(start); setPlayerCheckpoints(ply, start); if(mgm.getMaxScore() != 0 && mgm.getType().equals("dm") && !mgm.getScoreType().equals("none")){ ply.sendMessage(ChatColor.AQUA + "[Minigames] " + ChatColor.WHITE + "Score to win: " + mgm.getMaxScorePerPlayer(mgm.getPlayers().size())); } } else{ pos = 0; if(!mgm.getStartLocations().isEmpty()){ start = mgm.getStartLocations().get(0); ply.teleport(start); setPlayerCheckpoints(ply, start); if(mgm.getMaxScore() != 0 && mgm.getType().equals("dm") && !mgm.getScoreType().equals("none")){ ply.sendMessage(ChatColor.AQUA + "[Minigames] " + ChatColor.WHITE + "Score to win: " + mgm.getMaxScorePerPlayer(mgm.getPlayers().size())); } } else { ply.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "Starting positions are incorrectly configured!"); quitMinigame(ply, false); } } } else{ int team = -1; if(mgm.getBlueTeam().contains(ply)){ team = 1; } else if(mgm.getRedTeam().contains(ply)){ team = 0; } if(!mgm.getStartLocationsRed().isEmpty() && !mgm.getStartLocationsBlue().isEmpty()){ if(team == 0 && redpos < mgm.getStartLocationsRed().size()){ start = mgm.getStartLocationsRed().get(redpos); redpos++; } else if(team == 1 && bluepos < mgm.getStartLocationsBlue().size()){ start = mgm.getStartLocationsBlue().get(bluepos); bluepos++; } else if(team == 0 && !mgm.getStartLocationsRed().isEmpty()){ redpos = 0; start = mgm.getStartLocationsRed().get(redpos); redpos++; } else if(team == 1 && !mgm.getStartLocationsBlue().isEmpty()){ bluepos = 0; start = mgm.getStartLocationsBlue().get(bluepos); bluepos++; } else if(mgm.getStartLocationsBlue().isEmpty() || mgm.getStartLocationsRed().isEmpty()){ ply.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "Starting positions are incorrectly configured!"); quitMinigame(ply, false); } } else{ if(pos <= mgm.getStartLocations().size()){ start = mgm.getStartLocations().get(pos); ply.teleport(start); setPlayerCheckpoints(ply, start); } else{ pos = 1; if(!mgm.getStartLocations().isEmpty()){ start = mgm.getStartLocations().get(0); ply.teleport(start); setPlayerCheckpoints(ply, start); } else { ply.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "Starting positions are incorrectly configured!"); quitMinigame(ply, false); } } } if(start != null){ ply.teleport(start); setPlayerCheckpoints(ply, start); if(mgm.getMaxScore() != 0 && !mgm.getScoreType().equals("none")){ ply.sendMessage(ChatColor.AQUA + "[Minigames] " + ChatColor.WHITE + "Score to win: " + mgm.getMaxScorePerPlayer(mgm.getPlayers().size())); } } if(mgm.getLives() > 0){ ply.sendMessage(ChatColor.AQUA + "[Minigame] " + ChatColor.WHITE + "Lives left: " + mgm.getLives()); } } pos++; if(!mgm.getPlayersLoadout(ply).getItems().isEmpty()){ mgm.getPlayersLoadout(ply).equiptLoadout(ply); } ply.setScoreboard(mgm.getScoreboardManager()); mgm.setScore(ply, 1); mgm.setScore(ply, 0); } if(mgm.hasPlayers()){ if(mgm.getSpleefFloor1() != null && mgm.getSpleefFloor2() != null){ mgm.addFloorDegenerator(); mgm.getFloorDegenerator().startDegeneration(); } if(mgm.hasRestoreBlocks()){ for(RestoreBlock block : mgm.getRestoreBlocks().values()){ mgm.getBlockRecorder().addBlock(block.getLocation().getBlock(), null); } } for(Player pl : players){ setAllowTP(pl, false); } if(mgm.getTimer() > 0){ mgm.setMinigameTimer(new MinigameTimer(mgm, mgm.getTimer())); mdata.sendMinigameMessage(mgm, MinigameUtils.convertTime(mgm.getTimer()) + " left.", null, null); } } } public void revertToCheckpoint(Player player) { RevertCheckpointEvent event = new RevertCheckpointEvent(player); Bukkit.getServer().getPluginManager().callEvent(event); if(!event.isCancelled()){ setAllowTP(player, true); Location loc = getPlayerCheckpoint(player); player.teleport(loc); player.sendMessage(ChatColor.AQUA + "[Minigames] " + ChatColor.WHITE + "You have been reverted to the checkpoint."); setAllowTP(player, false); } } public void quitMinigame(Player player, boolean forced){ Minigame mgm = getPlayersMinigame(player); QuitMinigameEvent event = new QuitMinigameEvent(player, mgm, forced); Bukkit.getServer().getPluginManager().callEvent(event); if(!event.isCancelled()){ if(!mgm.isSpectator(player)){ setAllowTP(player, true); if(player.getVehicle() != null){ Vehicle vehicle = (Vehicle) player.getVehicle(); vehicle.eject(); } player.closeInventory(); MinigameUtils.removePlayerArrows(player); if(!forced){ mdata.sendMinigameMessage(mgm, player.getName() + " has left " + mgm, "error", player); } else{ mdata.sendMinigameMessage(mgm, player.getName() + " was removed from " + mgm, "error", player); } mgm.removePlayersLoadout(player); final Player ply = player; Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { if(ply.isOnline() && !ply.isDead()){ restorePlayerData(ply); } } }); removePlayerMinigame(player); mgm.removePlayer(player); mdata.minigameType(mgm.getType()).quitMinigame(player, mgm, forced); for(PotionEffect potion : player.getActivePotionEffects()){ player.removePotionEffect(potion.getType()); } final Player fplayer = player; Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { fplayer.setFireTicks(0); fplayer.setNoDamageTicks(60); } }); removeAllPlayerFlags(player); removePlayerDeath(player); removePlayerKills(player); removePlayerScore(player); removePlayerCheckpoints(player); plugin.getLogger().info(player.getName() + " quit " + mgm); if(mgm.getPlayers().size() == 0){ if(mgm.getMinigameTimer() != null){ mgm.getMinigameTimer().stopTimer(); mgm.setMinigameTimer(null); } if(mgm.getFloorDegenerator() != null){ mgm.getFloorDegenerator().stopDegenerator(); } if(mgm.getBlockRecorder().hasData()){ mgm.getBlockRecorder().restoreBlocks(); mgm.getBlockRecorder().restoreEntities(); } if(mgm.getMpBets() != null){ mgm.setMpBets(null); } } mgm.getScoreboardManager().resetScores(player); removeAllowTP(player); removeAllowGMChange(player); for(Player pl : mgm.getSpectators()){ player.showPlayer(pl); } } else{ setAllowTP(player, true); setAllowGMChange(player, true); if(player.getVehicle() != null){ Vehicle vehicle = (Vehicle) player.getVehicle(); vehicle.eject(); } player.closeInventory(); final Player fplayer = player; Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { fplayer.setFireTicks(0); fplayer.setNoDamageTicks(60); } }); final Player ply = player; Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { if(ply.isOnline()){ restorePlayerData(ply); } } }); player.teleport(mgm.getQuitPosition()); removePlayerMinigame(player); mgm.removeSpectator(player); for(PotionEffect potion : player.getActivePotionEffects()){ player.removePotionEffect(potion.getType()); } for(Player pl : mgm.getPlayers()){ pl.showPlayer(player); } removeAllowTP(player); removeAllowGMChange(player); player.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "You quit spectator mode in " + mgm); mdata.sendMinigameMessage(mgm, player.getName() + " is no longer spectating " + mgm, "error", player); } } } public void endMinigame(final Player player){ Minigame mgm = getPlayersMinigame(player); EndMinigameEvent event = new EndMinigameEvent(player, mgm); Bukkit.getServer().getPluginManager().callEvent(event); if(!event.isCancelled()){ setAllowTP(player, true); if(player.getVehicle() != null){ Vehicle vehicle = (Vehicle) player.getVehicle(); vehicle.eject(); } player.closeInventory(); Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { if(player.isOnline() && !player.isDead()){ restorePlayerData(player); } } }); MinigameUtils.removePlayerArrows(player); removePlayerMinigame(player); mgm.removePlayer(player); mgm.removePlayersLoadout(player); mdata.minigameType(mgm.getType()).endMinigame(player, mgm); for(PotionEffect potion : player.getActivePotionEffects()){ player.removePotionEffect(potion.getType()); } player.setFireTicks(0); player.setNoDamageTicks(60); removeAllPlayerFlags(player); if(plugin.getSQL() == null || plugin.getSQL().getSql() == null){ removePlayerDeath(player); removePlayerKills(player); removePlayerScore(player); } if(mgm.getMinigameTimer() != null){ mgm.getMinigameTimer().stopTimer(); mgm.setMinigameTimer(null); } if(mgm.getFloorDegenerator() != null && mgm.getPlayers().size() == 0){ mgm.getFloorDegenerator().stopDegenerator(); } if(mgm.getMpBets() != null && mgm.getPlayers().size() == 0){ mgm.setMpBets(null); } if(mgm.getBlockRecorder().hasData()){ if(!mgm.getType().equalsIgnoreCase("sp") || mgm.getPlayers().isEmpty()){ mgm.getBlockRecorder().restoreBlocks(); mgm.getBlockRecorder().restoreEntities(); } else if(mgm.getPlayers().isEmpty()){ mgm.getBlockRecorder().restoreBlocks(player); mgm.getBlockRecorder().restoreEntities(player); } } for(Player pl : mgm.getSpectators()){ player.showPlayer(pl); } removeAllowTP(player); removeAllowGMChange(player); plugin.getLogger().info(player.getName() + " completed " + mgm); mgm.getScoreboardManager().resetScores(player); } } public void endTeamMinigame(int teamnum, Minigame mgm){ List<Player> losers = new ArrayList<Player>(); List<Player> winners = new ArrayList<Player>(); if(teamnum == 1){ //Blue team for(OfflinePlayer ply : mgm.getRedTeam()){ losers.add(ply.getPlayer()); } for(OfflinePlayer ply : mgm.getBlueTeam()){ winners.add(ply.getPlayer()); } } else{ //Red team for(OfflinePlayer ply : mgm.getRedTeam()){ winners.add(ply.getPlayer()); } for(OfflinePlayer ply : mgm.getBlueTeam()){ losers.add(ply.getPlayer()); } } EndTeamMinigameEvent event = new EndTeamMinigameEvent(losers, winners, mgm, teamnum); Bukkit.getServer().getPluginManager().callEvent(event); if(!event.isCancelled()){ if(event.getWinningTeamInt() == 1){ if(plugin.getConfig().getBoolean("multiplayer.broadcastwin")){ String score = ""; if(mgm.getRedTeamScore() != 0 && mgm.getBlueTeamScore() != 0){ score = ", " + ChatColor.BLUE + mgm.getBlueTeamScore() + ChatColor.WHITE + " to " + ChatColor.RED + mgm.getRedTeamScore(); } plugin.getServer().broadcastMessage(ChatColor.GREEN + "[Minigames] " + ChatColor.BLUE + "Blue Team" + ChatColor.WHITE + " won " + mgm.getName() + score); } } else{ if(plugin.getConfig().getBoolean("multiplayer.broadcastwin")){ String score = ""; if(mgm.getRedTeamScore() != 0 && mgm.getBlueTeamScore() != 0){ score = ", " + ChatColor.RED + mgm.getRedTeamScore() + ChatColor.WHITE + " to " + ChatColor.BLUE + mgm.getBlueTeamScore(); } plugin.getServer().broadcastMessage(ChatColor.GREEN + "[Minigames] " + ChatColor.RED + "Red Team" + ChatColor.WHITE + " won " + mgm.getName() + score); } } mgm.setRedTeamScore(0); mgm.setBlueTeamScore(0); mgm.getMpTimer().setStartWaitTime(0); List<Player> winplayers = new ArrayList<Player>(); winplayers.addAll(event.getWinnningPlayers()); if(plugin.getSQL() != null){ new SQLCompletionSaver(mgm.getName(), winplayers, mdata.minigameType(mgm.getType())); } if(mgm.getMpBets() != null){ if(mgm.getMpBets().hasMoneyBets()){ List<Player> plys = new ArrayList<Player>(); plys.addAll(event.getWinnningPlayers()); double bets = mgm.getMpBets().claimMoneyBets() / (double) plys.size(); BigDecimal roundBets = new BigDecimal(bets); roundBets = roundBets.setScale(2, BigDecimal.ROUND_HALF_UP); bets = roundBets.doubleValue(); for(Player ply : plys){ plugin.getEconomy().depositPlayer(ply.getName(), bets); ply.sendMessage(ChatColor.AQUA + "[Minigames] " + ChatColor.WHITE + "You won $" + bets); } } mgm.setMpBets(null); } if(!event.getLosingPlayers().isEmpty()){ List<Player> loseplayers = new ArrayList<Player>(); loseplayers.addAll(event.getLosingPlayers()); for(int i = 0; i < loseplayers.size(); i++){ if(loseplayers.get(i) instanceof Player){ final Player p = loseplayers.get(i); Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { p.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "You have been beaten! Bad luck!"); quitMinigame(p, true); } }); } else{ loseplayers.remove(i); } } mgm.setMpTimer(null); for(Player pl : loseplayers){ mgm.getPlayers().remove(pl); } } for(int i = 0; i < winplayers.size(); i++){ if(winplayers.get(i) instanceof Player){ final Player p = winplayers.get(i); Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { endMinigame(p); } }); } else{ winplayers.remove(i); } } mgm.setMpTimer(null); } } public boolean playerInMinigame(Player player){ return minigamePlayers.containsKey(player.getName()); } public List<Player> playersInMinigame(){ List<Player> players = new ArrayList<Player>(); for(Player player : plugin.getServer().getOnlinePlayers()){ if(playerInMinigame(player)){ players.add(player); } } return players; } public void addPlayerMinigame(Player player, Minigame minigame){ minigamePlayers.put(player.getName(), minigame); } public void removePlayerMinigame(Player player){ if(minigamePlayers.containsKey(player.getName())){ minigamePlayers.remove(player.getName()); } } public Minigame getPlayersMinigame(Player player){ return minigamePlayers.get(player.getName()); } @SuppressWarnings("deprecation") public void storePlayerData(Player player, GameMode gm){ ItemStack[] items = player.getInventory().getContents(); ItemStack[] armour = player.getInventory().getArmorContents(); itemStore.put(player.getName(), items); armourStore.put(player.getName(), armour); playerFood.put(player.getName(), player.getFoodLevel()); playerHealth.put(player.getName(), player.getHealth()); playerSaturation.put(player.getName(), player.getSaturation()); lastScoreboard.put(player.getName(), player.getScoreboard()); //lastGM.put(player, player.getGameMode()); setPlayersLastGameMode(player, player.getGameMode()); player.setGameMode(gm); player.setSaturation(15); player.setFoodLevel(20); player.setHealth(player.getMaxHealth()); player.getInventory().clear(); player.getInventory().setArmorContents(null); saveItems(player); player.updateInventory(); } public void storePlayerInventory(String player, ItemStack[] items, ItemStack[] armour, Integer health, Integer food, Float saturation){ itemStore.put(player, items); armourStore.put(player, armour); playerHealth.put(player, health); playerFood.put(player, food); playerSaturation.put(player, saturation); } @SuppressWarnings("deprecation") public void restorePlayerData(final Player player){ player.getInventory().clear(); player.getInventory().setArmorContents(null); ItemStack[] items = itemStore.get(player.getName()); ItemStack[] armour = armourStore.get(player.getName()); player.getInventory().setContents(items); player.getInventory().setArmorContents(armour); player.setFoodLevel(playerFood.get(player.getName())); player.setHealth(playerHealth.get(player.getName())); player.setSaturation(playerSaturation.get(player.getName())); if(lastScoreboard.containsKey(player.getName())) player.setScoreboard(lastScoreboard.get(player.getName())); else player.setScoreboard(plugin.getServer().getScoreboardManager().getMainScoreboard()); setAllowGMChange(player, true); player.setGameMode(getPlayersLastGameMode(player)); removePlayersLastGameMode(player); setAllowGMChange(player, false); invsave.getConfig().set("inventories." + player.getName(), null); invsave.saveConfig(); itemStore.remove(player.getName()); armourStore.remove(player.getName()); playerFood.remove(player.getName()); playerHealth.remove(player.getName()); playerSaturation.remove(player.getName()); lastScoreboard.remove(player.getName()); player.updateInventory(); } public boolean playerHasStoredItems(Player player){ return itemStore.containsKey(player.getName()); } public Boolean getAllowTP(Player player){ return allowTP.get(player.getName()); } public void setAllowTP(Player player, Boolean var){ allowTP.put(player.getName(), var); } public void removeAllowTP(Player player){ allowTP.remove(player.getName()); } public Boolean getAllowGMChange(Player player){ return allowGMChange.get(player.getName()); } public void setAllowGMChange(Player player, Boolean var){ allowGMChange.put(player.getName(), var); } public void removeAllowGMChange(Player player){ allowGMChange.remove(player.getName()); } public void setPlayerCheckpoints(Player player, Location checkpoint){ playerCheckpoints.put(player.getName(), checkpoint); } public void removePlayerCheckpoints(Player player){ if(playerCheckpoints.containsKey(player.getName())){ playerCheckpoints.remove(player.getName()); } } public Location getPlayerCheckpoint(Player player){ if(playerCheckpoints.containsKey(player.getName())){ return playerCheckpoints.get(player.getName()); } return null; } public void addPlayerFlags(Player player, String flag){ List<String> list; if(playerFlags.containsKey(player.getName())){ list = playerFlags.get(player.getName()); } else{ list = new ArrayList<String>(); } list.add(flag); playerFlags.put(player.getName(), list); } public List<String> checkRequiredFlags(Player player, String minigame){ List<String> checkpoints = new ArrayList<String>(); checkpoints.addAll(mdata.getMinigame(minigame).getFlags()); List<String> pchecks = playerFlags.get(player.getName()); if(playerFlags.containsKey(player.getName()) && !pchecks.isEmpty()){ checkpoints.removeAll(pchecks); } return checkpoints; } public boolean playerHasFlag(Player player, String flag){ if(playerFlags.containsKey(player.getName())){ List<String> flags = playerFlags.get(player.getName()); if(flags.contains("flag")){ return true; } } return false; } public void removeAllPlayerFlags(Player player){ if(playerFlags.containsKey(player.getName())){ playerFlags.remove(player.getName()); } } public boolean playerHasFlags(Player player){ if(playerFlags.containsKey(player.getName())){ return true; } return false; } public List<String> getPlayerFlags(Player player){ return playerFlags.get(player.getName()); } public void addPlayerKill(Player ply){ if(!plyKills.containsKey(ply.getName())){ plyKills.put(ply.getName(), 0); } plyKills.put(ply.getName(), plyKills.get(ply.getName()) + 1); } public Integer getPlayerKills(Player ply){ if(!plyKills.containsKey(ply.getName())){ return 0; } return plyKills.get(ply.getName()); } public void removePlayerKills(Player ply){ if(plyKills.containsKey(ply.getName())){ plyKills.remove(ply.getName()); } } public void addPlayerDeath(Player ply){ if(!plyDeaths.containsKey(ply.getName())){ plyDeaths.put(ply.getName(), 0); } plyDeaths.put(ply.getName(), plyDeaths.get(ply.getName()) + 1); } public Integer getPlayerDeath(Player ply){ if(!plyDeaths.containsKey(ply.getName())){ return 0; } return plyDeaths.get(ply.getName()); } public void removePlayerDeath(Player ply){ if(plyDeaths.containsKey(ply.getName())){ plyDeaths.remove(ply.getName()); } } public void addPlayerScore(Player ply){ if(!plyScore.containsKey(ply.getName())){ plyScore.put(ply.getName(), 0); } plyScore.put(ply.getName(), plyScore.get(ply.getName()) + 1); } public void setPlayerScore(Player ply, int amount){ if(!plyScore.containsKey(ply.getName())){ plyScore.put(ply.getName(), 0); } plyScore.put(ply.getName(), amount); } public void takePlayerScore(Player ply){ if(!plyScore.containsKey(ply.getName())){ plyScore.put(ply.getName(), 0); } plyScore.put(ply.getName(), plyScore.get(ply.getName()) - 1); } public Integer getPlayerScore(Player ply){ if(plyScore.containsKey(ply.getName())){ return plyScore.get(ply.getName()); } return 0; } public void removePlayerScore(Player ply){ if(plyScore.containsKey(ply.getName())){ plyScore.remove(ply.getName()); } } public GameMode getPlayersLastGameMode(Player player){ if(lastGM.containsKey(player.getName())){ return lastGM.get(player.getName()); } else{ return player.getGameMode(); } } public void setPlayersLastGameMode(Player player, GameMode gm){ lastGM.put(player.getName(), gm); } public boolean removePlayersLastGameMode(Player player){ if(lastGM.containsKey(player.getName())){ lastGM.remove(player.getName()); return true; } return false; } public void saveItems(Player player){ if(itemStore.get(player.getName()) != null){ int num = 0; for(ItemStack item : itemStore.get(player.getName())){ if(item != null){ invsave.getConfig().set("inventories." + player.getName() + "." + num, item); } num++; } } else{ invsave.getConfig().set("inventories." + player.getName(), null); } if(armourStore.get(player.getName()) != null){ int num = 0; for(ItemStack item : armourStore.get(player.getName())){ if(item != null){ invsave.getConfig().set("inventories." + player.getName() + ".armour." + num, item); } num++; } } if(playerFood.containsKey(player.getName())){ invsave.getConfig().set("inventories." + player.getName() + ".food", playerFood.get(player.getName())); } if(playerSaturation.containsKey(player.getName())){ invsave.getConfig().set("inventories." + player.getName() + ".saturation", playerSaturation.get(player.getName())); } if(playerHealth.containsKey(player.getName())){ invsave.getConfig().set("inventories." + player.getName() + ".health", playerHealth.get(player.getName())); } invsave.saveConfig(); } public Configuration getInventorySaveConfig(){ return invsave.getConfig(); } public void saveInventoryConfig(){ invsave.saveConfig(); } public boolean onPartyMode(){ return partyMode; } public void setPartyMode(boolean mode){ partyMode = mode; } public void partyMode(Player player){ if(onPartyMode()){ Location loc = player.getLocation(); Firework firework = (Firework) player.getWorld().spawnEntity(loc, EntityType.FIREWORK); FireworkMeta fwm = firework.getFireworkMeta(); Random chance = new Random(); Type type = Type.BALL_LARGE; if(chance.nextInt(100) < 50){ type = Type.BALL; } Color col = Color.fromRGB(chance.nextInt(255), chance.nextInt(255), chance.nextInt(255)); FireworkEffect effect = FireworkEffect.builder().with(type).withColor(col).flicker(chance.nextBoolean()).trail(chance.nextBoolean()).build(); fwm.addEffect(effect); fwm.setPower(0); firework.setFireworkMeta(fwm); } } public void addDCPlayer(Player player, Location location){ dcPlayers.put(player.getName(), location); } public void addDCPlayer(String player, Location location){ dcPlayers.put(player, location); } public Location getDCPlayer(Player player){ return dcPlayers.get(player.getName()); } public boolean hasDCPlayer(Player player){ return dcPlayers.containsKey(player.getName()); } public void removeDCPlayer(Player player){ dcPlayers.remove(player.getName()); } public void saveDCPlayers(){ MinigameSave save = new MinigameSave("dcPlayers"); for(String player : dcPlayers.keySet()){ mdata.minigameSetLocations(player, dcPlayers.get(player), "rejoin", save.getConfig()); } save.saveConfig(); } public void loadDCPlayers(){ MinigameSave save = new MinigameSave("dcPlayers"); for(String player : save.getConfig().getKeys(false)){ addDCPlayer(player, mdata.minigameLocations(player, "rejoin", save.getConfig())); save.getConfig().set(player, null); } save.saveConfig(); save.deleteFile(); } public List<String> getDeniedCommands() { return deniedCommands; } public void setDeniedCommands(List<String> deniedCommands) { this.deniedCommands = deniedCommands; } public void addDeniedCommand(String command){ deniedCommands.add(command); } public void removeDeniedCommand(String command){ deniedCommands.remove(command); } public void saveDeniedCommands(){ plugin.getConfig().set("disabledCommands", deniedCommands); plugin.saveConfig(); } public void loadDeniedCommands(){ setDeniedCommands(plugin.getConfig().getStringList("disabledCommands")); } public boolean hasStoredPlayerCheckpoint(Player player){ if(storedPlayerCheckpoints.containsKey(player.getName())){ return true; } return false; } public StoredPlayerCheckpoints getPlayersStoredCheckpoints(Player player){ return storedPlayerCheckpoints.get(player.getName()); } public void addStoredPlayerCheckpoint(Player player, String minigame, Location checkpoint){ StoredPlayerCheckpoints spc = new StoredPlayerCheckpoints(player.getName(), minigame, checkpoint); storedPlayerCheckpoints.put(player.getName(), spc); } public void addStoredPlayerCheckpoints(String name, StoredPlayerCheckpoints spc){ storedPlayerCheckpoints.put(name, spc); } public void minigameTeleport(Player player, Location location){ if(playerInMinigame(player)){ setAllowTP(player, true); player.teleport(location); setAllowTP(player, false); } } }
package algorithms.imageProcessing; import junit.framework.TestCase; /** * * @author nichole */ public class MorphologicalFilterTest extends TestCase { public MorphologicalFilterTest() { } public void testBwMorphThin() { System.out.println("bwMorphThin"); int[][] img = new int[4][]; img[0] = new int[]{0, 1, 1, 1, 0}; img[1] = new int[]{0, 1, 1, 1, 0}; img[2] = new int[]{0, 1, 1, 1, 0}; img[3] = new int[]{0, 1, 1, 1, 0}; MorphologicalFilter mFilter = new MorphologicalFilter(); int[][] skel = mFilter.bwMorphThin(img, Integer.MAX_VALUE); int[][] expected = new int[4][]; expected[0] = new int[]{0, 0, 1, 0, 0}; expected[1] = new int[]{0, 0, 1, 0, 0}; expected[2] = new int[]{0, 0, 1, 0, 0}; expected[3] = new int[]{0, 0, 1, 0, 0}; for (int i = 0; i < expected.length; ++i) { for (int j = 0; j < expected[i].length; ++j) { assertEquals(expected[i][j], skel[i][j]); } } } }
package com.redhat.ceylon.model.typechecker.model; import static com.redhat.ceylon.model.typechecker.model.Module.LANGUAGE_MODULE_NAME; import static com.redhat.ceylon.model.typechecker.model.Util.addToIntersection; import static com.redhat.ceylon.model.typechecker.model.Util.addToUnion; import static com.redhat.ceylon.model.typechecker.model.Util.intersectionType; import static com.redhat.ceylon.model.typechecker.model.Util.isNameMatching; import static com.redhat.ceylon.model.typechecker.model.Util.isOverloadedVersion; import static com.redhat.ceylon.model.typechecker.model.Util.isToplevelAnonymousClass; import static com.redhat.ceylon.model.typechecker.model.Util.isToplevelClassConstructor; import static com.redhat.ceylon.model.typechecker.model.Util.producedType; import static com.redhat.ceylon.model.typechecker.model.Util.unionType; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.TreeMap; import com.redhat.ceylon.model.typechecker.context.ProducedTypeCache; public class Unit { private Package pkg; private List<Import> imports = new ArrayList<Import>(); private List<Declaration> declarations = new ArrayList<Declaration>(); private String filename; private List<ImportList> importLists = new ArrayList<ImportList>(); private Set<Declaration> duplicateDeclarations = new HashSet<Declaration>(); private final Set<String> dependentsOf = new HashSet<String>(); private String fullPath; private String relativePath; public List<Import> getImports() { return imports; } public List<ImportList> getImportLists() { return importLists; } /** * @return the dependentsOf */ public Set<String> getDependentsOf() { return dependentsOf; } public Set<Declaration> getDuplicateDeclarations() { return duplicateDeclarations; } public Package getPackage() { return pkg; } public void setPackage(Package p) { pkg = p; } public List<Declaration> getDeclarations() { synchronized (declarations) { return new ArrayList<Declaration>(declarations); } } public void addDeclaration(Declaration declaration) { synchronized (declarations) { declarations.add(declaration); } } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public String getFullPath() { return fullPath; } public void setFullPath(String fullPath) { this.fullPath = fullPath; } public String getRelativePath() { return relativePath; } public void setRelativePath(String relativePath) { this.relativePath = relativePath; } @Override public String toString() { return "Unit[" + filename + "]"; } public Import getImport(String name) { for (Import i: getImports()) { if (!i.isAmbiguous() && i.getTypeDeclaration()==null && i.getAlias().equals(name)) { return i; } } return null; } public String getAliasedName(Declaration dec) { for (Import i: getImports()) { if (!i.isAmbiguous() && i.getDeclaration().equals(getAbstraction(dec))) { return i.getAlias(); } } return dec.getName(); } public static Declaration getAbstraction(Declaration dec){ if (isOverloadedVersion(dec)) { return dec.getContainer() .getDirectMember(dec.getName(), null, false); } else { return dec; } } /** * Search the imports of a compilation unit * for the named toplevel declaration. */ public Declaration getImportedDeclaration(String name, List<ProducedType> signature, boolean ellipsis) { for (Import i: getImports()) { if (!i.isAmbiguous() && i.getAlias().equals(name)) { //in case of an overloaded member, this will //be the "abstraction", so search for the //correct overloaded version Declaration d = i.getDeclaration(); if (isToplevelImport(i, d)) { return d.getContainer() .getMember(d.getName(), signature, ellipsis); } } } return null; } static boolean isToplevelImport(Import i, Declaration d) { return d.isToplevel() || d.isStaticallyImportable() || isToplevelClassConstructor(i.getTypeDeclaration(), d) || isToplevelAnonymousClass(i.getTypeDeclaration()); } /** * Search the imports of a compilation unit * for the named member declaration. */ public Declaration getImportedDeclaration(TypeDeclaration td, String name, List<ProducedType> signature, boolean ellipsis) { for (Import i: getImports()) { TypeDeclaration itd = i.getTypeDeclaration(); if (itd!=null && itd.equals(td) && !i.isAmbiguous() && i.getAlias().equals(name)) { //in case of an overloaded member, this will //be the "abstraction", so search for the //correct overloaded version Declaration d = i.getDeclaration(); return d.getContainer() .getMember(d.getName(), signature, ellipsis); } } return null; } public Map<String, DeclarationWithProximity> getMatchingImportedDeclarations(String startingWith, int proximity) { Map<String, DeclarationWithProximity> result = new TreeMap<String, DeclarationWithProximity>(); for (Import i: new ArrayList<Import>(getImports())) { if (i.getAlias()!=null && !i.isAmbiguous() && isNameMatching(startingWith, i)) { Declaration d = i.getDeclaration(); if (isToplevelImport(i, d)) { result.put(i.getAlias(), new DeclarationWithProximity(i, proximity)); } } } return result; } public Map<String, DeclarationWithProximity> getMatchingImportedDeclarations(TypeDeclaration td, String startingWith, int proximity) { Map<String, DeclarationWithProximity> result = new TreeMap<String, DeclarationWithProximity>(); for (Import i: new ArrayList<Import>(getImports())) { TypeDeclaration itd = i.getTypeDeclaration(); if (i.getAlias()!=null && !i.isAmbiguous() && itd!=null && itd.equals(td) && isNameMatching(startingWith, i)) { result.put(i.getAlias(), new DeclarationWithProximity(i, proximity)); } } return result; } @Override public boolean equals(Object obj) { if (obj instanceof Unit) { Unit that = (Unit) obj; return that==this || that.getPackage() .equals(getPackage()) && Objects.equals(getFilename(), that.getFilename()) && Objects.equals(that.getFullPath(), getFullPath()); } else { return false; } } @Override public int hashCode() { return getFullPath().hashCode(); } private Module languageModule; private Package languagePackage; /** * Search for a declaration in the language module. */ public Declaration getLanguageModuleDeclaration(String name) { //all elements in ceylon.language are auto-imported //traverse all default module packages provided they //have not been traversed yet Module languageModule = getLanguageModule(); if (languageModule!=null && languageModule.isAvailable()) { if ("Nothing".equals(name)) { return getNothingDeclaration(); } if (languagePackage==null) { languagePackage = languageModule.getPackage(LANGUAGE_MODULE_NAME); } if (languagePackage != null) { Declaration d = languagePackage.getMember(name, null, false); if (d != null && d.isShared()) { return d; } } } return null; } private Module getLanguageModule() { if (languageModule==null) { languageModule = getPackage().getModule() .getLanguageModule(); } return languageModule; } /** * Search for a declaration in {@code ceylon.language.meta.model} */ public Declaration getLanguageModuleModelDeclaration(String name) { Module languageModule = getPackage().getModule() .getLanguageModule(); if (languageModule!=null && languageModule.isAvailable()) { Package languageScope = languageModule.getPackage("ceylon.language.meta.model"); if (languageScope!=null) { Declaration d = languageScope.getMember(name, null, false); if (d!=null && d.isShared()) { return d; } } } return null; } /** * Search for a declaration in {@code ceylon.language.meta.declaration} */ public Declaration getLanguageModuleDeclarationDeclaration(String name) { Module languageModule = getPackage().getModule() .getLanguageModule(); if (languageModule!=null && languageModule.isAvailable()) { Package languageScope = languageModule.getPackage("ceylon.language.meta.declaration"); if (languageScope!=null) { Declaration d = languageScope.getMember(name, null, false); if (d!=null && d.isShared()) { return d; } } } return null; } /** * Search for a declaration in {@code ceylon.language.serialization} */ public Declaration getLanguageModuleSerializationDeclaration(String name) { Module languageModule = getPackage().getModule() .getLanguageModule(); if (languageModule!=null && languageModule.isAvailable()) { Package languageScope = languageModule.getPackage("ceylon.language.serialization"); if (languageScope!=null) { Declaration d = languageScope.getMember(name, null, false); if (d != null && d.isShared()) { return d; } } } return null; } public Interface getCorrespondenceDeclaration() { return (Interface) getLanguageModuleDeclaration("Correspondence"); } public Class getAnythingDeclaration() { return (Class) getLanguageModuleDeclaration("Anything"); } public Class getNullDeclaration() { return (Class) getLanguageModuleDeclaration("Null"); } public Value getNullValueDeclaration() { return (Value) getLanguageModuleDeclaration("null"); } public Interface getEmptyDeclaration() { return (Interface) getLanguageModuleDeclaration("Empty"); } public Interface getSequenceDeclaration() { return (Interface) getLanguageModuleDeclaration("Sequence"); } public Class getObjectDeclaration() { return (Class) getLanguageModuleDeclaration("Object"); } public Class getBasicDeclaration() { return (Class) getLanguageModuleDeclaration("Basic"); } public Interface getIdentifiableDeclaration() { return (Interface) getLanguageModuleDeclaration("Identifiable"); } public Class getThrowableDeclaration() { return (Class) getLanguageModuleDeclaration("Throwable"); } public Class getErrorDeclaration() { return (Class) getLanguageModuleDeclaration("Error"); } public Class getExceptionDeclaration() { return (Class) getLanguageModuleDeclaration("Exception"); } public Interface getCategoryDeclaration() { return (Interface) getLanguageModuleDeclaration("Category"); } public Interface getIterableDeclaration() { return (Interface) getLanguageModuleDeclaration("Iterable"); } public Interface getSequentialDeclaration() { return (Interface) getLanguageModuleDeclaration("Sequential"); } public Interface getListDeclaration() { return (Interface) getLanguageModuleDeclaration("List"); } public Interface getCollectionDeclaration() { return (Interface) getLanguageModuleDeclaration("Collection"); } public Interface getIteratorDeclaration() { return (Interface) getLanguageModuleDeclaration("Iterator"); } public Interface getCallableDeclaration() { return (Interface) getLanguageModuleDeclaration("Callable"); } public Interface getScalableDeclaration() { return (Interface) getLanguageModuleDeclaration("Scalable"); } public Interface getSummableDeclaration() { return (Interface) getLanguageModuleDeclaration("Summable"); } public Interface getNumericDeclaration() { return (Interface) getLanguageModuleDeclaration("Numeric"); } public Interface getIntegralDeclaration() { return (Interface) getLanguageModuleDeclaration("Integral"); } public Interface getInvertableDeclaration() { return (Interface) getLanguageModuleDeclaration("Invertible"); } public Interface getExponentiableDeclaration() { return (Interface) getLanguageModuleDeclaration("Exponentiable"); } public Interface getSetDeclaration() { return (Interface) getLanguageModuleDeclaration("Set"); } public TypeDeclaration getComparisonDeclaration() { return (TypeDeclaration) getLanguageModuleDeclaration("Comparison"); } public TypeDeclaration getBooleanDeclaration() { return (TypeDeclaration) getLanguageModuleDeclaration("Boolean"); } public Value getTrueValueDeclaration() { return (Value) getLanguageModuleDeclaration("true"); } public Value getFalseValueDeclaration() { return (Value) getLanguageModuleDeclaration("false"); } public TypeDeclaration getStringDeclaration() { return (TypeDeclaration) getLanguageModuleDeclaration("String"); } public TypeDeclaration getFloatDeclaration() { return (TypeDeclaration) getLanguageModuleDeclaration("Float"); } public TypeDeclaration getIntegerDeclaration() { return (TypeDeclaration) getLanguageModuleDeclaration("Integer"); } public TypeDeclaration getCharacterDeclaration() { return (TypeDeclaration) getLanguageModuleDeclaration("Character"); } public TypeDeclaration getByteDeclaration() { return (TypeDeclaration) getLanguageModuleDeclaration("Byte"); } public Interface getComparableDeclaration() { return (Interface) getLanguageModuleDeclaration("Comparable"); } public Interface getUsableDeclaration() { return (Interface) getLanguageModuleDeclaration("Usable"); } public Interface getDestroyableDeclaration() { return (Interface) getLanguageModuleDeclaration("Destroyable"); } public Interface getObtainableDeclaration() { return (Interface) getLanguageModuleDeclaration("Obtainable"); } public Interface getOrdinalDeclaration() { return (Interface) getLanguageModuleDeclaration("Ordinal"); } public Interface getEnumerableDeclaration() { return (Interface) getLanguageModuleDeclaration("Enumerable"); } public Class getRangeDeclaration() { return (Class) getLanguageModuleDeclaration("Range"); } public Class getSpanDeclaration() { return (Class) getLanguageModuleDeclaration("Span"); } public Class getMeasureDeclaration() { return (Class) getLanguageModuleDeclaration("Measure"); } public Class getTupleDeclaration() { return (Class) getLanguageModuleDeclaration("Tuple"); } public TypeDeclaration getArrayDeclaration() { return (Class) getLanguageModuleDeclaration("Array"); } public Interface getRangedDeclaration() { return (Interface) getLanguageModuleDeclaration("Ranged"); } public Class getEntryDeclaration() { return (Class) getLanguageModuleDeclaration("Entry"); } ProducedType getCallableType(ProducedReference ref, ProducedType rt) { ProducedType result = rt; Declaration declaration = ref.getOverloadedVersion(); if (declaration instanceof Functional) { Functional fd = (Functional) declaration; List<ParameterList> pls = fd.getParameterLists(); for (int i=pls.size()-1; i>=0; i boolean hasSequenced = false; boolean atLeastOne = false; int firstDefaulted = -1; List<Parameter> ps = pls.get(i).getParameters(); List<ProducedType> args = new ArrayList<ProducedType> (ps.size()); for (int j=0; j<ps.size(); j++) { Parameter p = ps.get(j); if (p.getModel()==null) { args.add(new UnknownType(this).getType()); } else { ProducedTypedReference np = ref.getTypedParameter(p); ProducedType npt = np.getType(); if (npt==null) { args.add(new UnknownType(this).getType()); } else { if (p.isDefaulted() && firstDefaulted==-1) { firstDefaulted = j; } if (np.getDeclaration() instanceof Functional) { args.add(getCallableType(np, npt)); } else if (p.isSequenced()) { args.add(getIteratedType(npt)); hasSequenced = true; atLeastOne = p.isAtLeastOne(); } else { args.add(npt); } } } } ProducedType paramListType = getTupleType(args, hasSequenced, atLeastOne, firstDefaulted); result = producedType(getCallableDeclaration(), result, paramListType); } } return result; } public ProducedType getTupleType(List<ProducedType> elemTypes, ProducedType variadicTailType, int firstDefaulted) { boolean hasVariadicTail = variadicTailType!=null; ProducedType result = hasVariadicTail ? variadicTailType : getType(getEmptyDeclaration()); ProducedType union = hasVariadicTail ? getSequentialElementType(variadicTailType) : getType(getNothingDeclaration()); return getTupleType(elemTypes, false, false, firstDefaulted, result, union); } public ProducedType getTupleType(List<ProducedType> elemTypes, boolean variadic, boolean atLeastOne, int firstDefaulted) { ProducedType result = getType(getEmptyDeclaration()); ProducedType union = getType(getNothingDeclaration()); return getTupleType(elemTypes, variadic, atLeastOne, firstDefaulted, result, union); } private ProducedType getTupleType(List<ProducedType> elemTypes, boolean variadic, boolean atLeastOne, int firstDefaulted, ProducedType result, ProducedType union) { int last = elemTypes.size()-1; for (int i=last; i>=0; i ProducedType elemType = elemTypes.get(i); union = unionType(union, elemType, this); if (variadic && i==last) { result = atLeastOne ? getSequenceType(elemType) : getSequentialType(elemType); } else { result = producedType(getTupleDeclaration(), union, elemType, result); if (firstDefaulted>=0 && i>=firstDefaulted) { result = unionType(result, getType(getEmptyDeclaration()), this); } } } return result; } public ProducedType getEmptyType(ProducedType pt) { return pt==null ? null : unionType(pt, getType(getEmptyDeclaration()), this); /*else if (isEmptyType(pt)) { //Null|Null|T == Null|T return pt; } else if (pt.getDeclaration() instanceof NothingType) { //Null|0 == Null return getEmptyDeclaration().getType(); } else { UnionType ut = new UnionType(); List<ProducedType> types = new ArrayList<ProducedType>(); addToUnion(types,getEmptyDeclaration().getType()); addToUnion(types,pt); ut.setCaseTypes(types); return ut.getType(); }*/ } public ProducedType getPossiblyEmptyType(ProducedType pt) { return pt==null ? null : producedType(getSequentialDeclaration(), getSequentialElementType(pt)); } public ProducedType getOptionalType(ProducedType pt) { return pt==null ? null : unionType(pt, getType(getNullDeclaration()), this); /*else if (isOptionalType(pt)) { //Null|Null|T == Null|T return pt; } else if (pt.getDeclaration() instanceof NothingType) { //Null|0 == Null return getNullDeclaration().getType(); } else { UnionType ut = new UnionType(); List<ProducedType> types = new ArrayList<ProducedType>(); addToUnion(types,getNullDeclaration().getType()); addToUnion(types,pt); ut.setCaseTypes(types); return ut.getType(); }*/ } public ProducedType getSequenceType(ProducedType et) { return producedType(getSequenceDeclaration(), et); } public ProducedType getSequentialType(ProducedType et) { return producedType(getSequentialDeclaration(), et); } public ProducedType getIterableType(ProducedType et) { return producedType(getIterableDeclaration(), et, getType(getNullDeclaration())); } public ProducedType getNonemptyIterableType(ProducedType et) { return producedType(getIterableDeclaration(), et, getNothingDeclaration().getType()); } public ProducedType getSetType(ProducedType et) { return producedType(getSetDeclaration(), et); } /** * Returns a ProducedType corresponding to {@code Iterator<T>} * @param et The ProducedType corresponding to {@code T} * @return The ProducedType corresponding to {@code Iterator<T>} */ public ProducedType getIteratorType(ProducedType et) { return producedType(getIteratorDeclaration(), et); } /** * Returns a ProducedType corresponding to {@code Span<T>} * @param rt The ProducedType corresponding to {@code T} * @return The ProducedType corresponding to {@code Span<T>} */ public ProducedType getSpanType(ProducedType rt) { return producedType(getRangeDeclaration(), rt); } /** * Returns a ProducedType corresponding to {@code SizedRange<T>|[]} * @param rt The ProducedType corresponding to {@code T} * @return The ProducedType corresponding to {@code SizedRange<T>|[]} */ public ProducedType getMeasureType(ProducedType rt) { return unionType(producedType(getRangeDeclaration(), rt), getType(getEmptyDeclaration()), this); } public ProducedType getEntryType(ProducedType kt, ProducedType vt) { return producedType(getEntryDeclaration(), kt, vt); } public ProducedType getKeyType(ProducedType type) { ProducedType st = type.getSupertype(getEntryDeclaration()); if (st!=null && st.getTypeArguments().size()==2) { return st.getTypeArgumentList().get(0); } else { return null; } } public ProducedType getValueType(ProducedType type) { ProducedType st = type.getSupertype(getEntryDeclaration()); if (st!=null && st.getTypeArguments().size()==2) { return st.getTypeArgumentList().get(1); } else { return null; } } public ProducedType getIteratedType(ProducedType type) { ProducedType st = type.getSupertype(getIterableDeclaration()); if (st!=null && st.getTypeArguments().size()>0) { return st.getTypeArgumentList().get(0); } else { return null; } } public ProducedType getFirstType(ProducedType type) { ProducedType st = type.getSupertype(getIterableDeclaration()); if (st!=null && st.getTypeArguments().size()>1) { return st.getTypeArgumentList().get(1); } else { return null; } } public boolean isNonemptyIterableType(ProducedType type) { ProducedType ft = getFirstType(type); return ft!=null && ft.isNothing(); } public ProducedType getSetElementType(ProducedType type) { ProducedType st = type.getSupertype(getSetDeclaration()); if (st!=null && st.getTypeArguments().size()==1) { return st.getTypeArgumentList().get(0); } else { return null; } } public ProducedType getSequentialElementType(ProducedType type) { ProducedType st = type.getSupertype(getSequentialDeclaration()); if (st!=null && st.getTypeArguments().size()==1) { return st.getTypeArgumentList().get(0); } else { return null; } } public ProducedType getDefiniteType(ProducedType pt) { return intersectionType(getType(getObjectDeclaration()), pt, pt.getDeclaration().getUnit()); /*if (pt.getDeclaration().equals(getAnythingDeclaration())) { return getObjectDeclaration().getType(); } else { return pt.minus(getNullDeclaration()); }*/ } public ProducedType getNonemptyType(ProducedType pt) { return intersectionType(producedType(getSequenceDeclaration(), getSequentialElementType(pt)), pt, pt.getDeclaration().getUnit()); /*if (pt.getDeclaration().equals(getAnythingDeclaration())) { return getObjectDeclaration().getType(); } else { return pt.minus(getNullDeclaration()); }*/ } public ProducedType getNonemptyDefiniteType(ProducedType pt) { return getNonemptyType(getDefiniteType(pt)); } public boolean isEntryType(ProducedType pt) { return pt.getDeclaration() .inherits(getEntryDeclaration()); } public boolean isIterableType(ProducedType pt) { return pt.getDeclaration() .inherits(getIterableDeclaration()); } public boolean isUsableType(ProducedType pt) { return pt.getDeclaration() .inherits(getUsableDeclaration()); } public boolean isSequentialType(ProducedType pt) { return pt.getDeclaration() .inherits(getSequentialDeclaration()); } public boolean isSequenceType(ProducedType pt) { return pt.getDeclaration() .inherits(getSequenceDeclaration()); } public boolean isEmptyType(ProducedType pt) { return pt.getDeclaration() .inherits(getEmptyDeclaration()); } public boolean isTupleType(ProducedType pt) { return pt.getDeclaration() .inherits(getTupleDeclaration()); } public boolean isOptionalType(ProducedType pt) { //must have non-empty intersection with Null //and non-empty intersection with Value return !intersectionType(getType(getNullDeclaration()), pt, this) .isNothing() && !intersectionType(getType(getObjectDeclaration()), pt, this) .isNothing(); } public boolean isPossiblyEmptyType(ProducedType pt) { //must be a subtype of Sequential<Anything> return isSequentialType(getDefiniteType(pt)) && //must have non-empty intersection with Empty //and non-empty intersection with Sequence<Nothing> !intersectionType(getType(getEmptyDeclaration()), pt, this) .isNothing() && !intersectionType(getSequentialType(getNothingDeclaration().getType()), pt, this) .isNothing(); } public boolean isCallableType(ProducedType pt) { return pt!=null && pt.getDeclaration() .inherits(getCallableDeclaration()); } public NothingType getNothingDeclaration() { return new NothingType(this); } public ProducedType denotableType(ProducedType pt) { if (pt!=null) { TypeDeclaration d = pt.getDeclaration(); if (d instanceof UnionType) { List<ProducedType> cts = d.getCaseTypes(); List<ProducedType> list = new ArrayList<ProducedType> (cts.size()+1); for (ProducedType ct: cts) { addToUnion(list, denotableType(ct)); } UnionType ut = new UnionType(this); ut.setCaseTypes(list); return ut.getType(); } if (d instanceof IntersectionType) { List<ProducedType> sts = d.getSatisfiedTypes(); List<ProducedType> list = new ArrayList<ProducedType> (sts.size()+1); for (ProducedType st: sts) { addToIntersection(list, denotableType(st), this); } IntersectionType it = new IntersectionType(this); it.setSatisfiedTypes(list); return it.canonicalize().getType(); } if (d instanceof Functional) { Functional fd = (Functional) d; if (fd.isOverloaded()) { pt = pt.getSupertype( d.getExtendedTypeDeclaration()); } } if (d instanceof Constructor) { return pt.getSupertype( d.getExtendedTypeDeclaration()); } if (d!=null && d.isAnonymous()) { ClassOrInterface etd = d.getExtendedTypeDeclaration(); List<TypeDeclaration> stds = d.getSatisfiedTypeDeclarations(); List<ProducedType> list = new ArrayList<ProducedType> (stds.size()+1); if (etd!=null) { addToIntersection(list, pt.getSupertype(etd), this); } for (TypeDeclaration td: stds) { if (td!=null) { addToIntersection(list, pt.getSupertype(td), this); } } IntersectionType it = new IntersectionType(this); it.setSatisfiedTypes(list); return it.getType(); } else { List<ProducedType> typeArgList = pt.getTypeArgumentList(); if (typeArgList.isEmpty()) { return pt; } else { d = pt.getDeclaration(); List<TypeParameter> typeParamList = d.getTypeParameters(); List<ProducedType> typeArguments = new ArrayList<ProducedType> (typeArgList.size()); for (int i=0; i<typeParamList.size() && i<typeArgList.size(); i++) { ProducedType at = typeArgList.get(i); TypeParameter tp = typeParamList.get(i); typeArguments.add(tp.isCovariant() ? denotableType(at) : at); } ProducedType qt = pt.getQualifyingType(); ProducedType dt = d.getProducedType(qt, typeArguments); dt.setUnderlyingType(pt.getUnderlyingType()); dt.setVarianceOverrides(pt.getVarianceOverrides()); dt.setTypeConstructor(pt.getTypeConstructorParameter()); dt.setRaw(pt.isRaw()); return dt; } } } else { return null; } } public ProducedType nonemptyArgs(ProducedType args) { return getType(getEmptyDeclaration()) .isSubtypeOf(args) ? getNonemptyType(args) : args; } public List<ProducedType> getTupleElementTypes(ProducedType args) { if (args!=null) { List<ProducedType> simpleResult = getSimpleTupleElementTypes(args, 0); if (simpleResult!=null){ return simpleResult; } if (isEmptyType(args)) { return new LinkedList<ProducedType>(); } ProducedType tst = nonemptyArgs(args) .getSupertype(getTupleDeclaration()); if (tst!=null) { List<ProducedType> tal = tst.getTypeArgumentList(); if (tal.size()>=3) { List<ProducedType> result = getTupleElementTypes(tal.get(2)); ProducedType arg = tal.get(1); if (arg==null) { arg = new UnknownType(this).getType(); } result.add(0, arg); return result; } } else if (isSequentialType(args)) { //this is pretty weird: return the whole //tail type as the element of the list! LinkedList<ProducedType> sequenced = new LinkedList<ProducedType>(); sequenced.add(args); return sequenced; } } LinkedList<ProducedType> unknown = new LinkedList<ProducedType>(); unknown.add(new UnknownType(this).getType()); return unknown; } private List<ProducedType> getSimpleTupleElementTypes(ProducedType args, int count) { // can be a defaulted tuple of Empty|Tuple TypeDeclaration declaration = args.getDeclaration(); if (declaration instanceof UnionType) { List<ProducedType> caseTypes = declaration.getCaseTypes(); if (caseTypes == null || caseTypes.size() != 2) { return null; } ProducedType caseA = caseTypes.get(0); TypeDeclaration caseADecl = caseA.getDeclaration(); ProducedType caseB = caseTypes.get(1); TypeDeclaration caseBDecl = caseB.getDeclaration(); if (!(caseADecl instanceof ClassOrInterface) || !(caseBDecl instanceof ClassOrInterface)) { return null; } String caseAName = caseADecl.getQualifiedNameString(); String caseBName = caseBDecl.getQualifiedNameString(); if (caseAName.equals("ceylon.language::Empty") && caseBName.equals("ceylon.language::Tuple")) { return getSimpleTupleElementTypes(caseB, count); } if (caseBName.equals("ceylon.language::Empty") && caseAName.equals("ceylon.language::Tuple")) { return getSimpleTupleElementTypes(caseA, count); } return null; } // can be Tuple, Empty, Sequence or Sequential if (!(declaration instanceof ClassOrInterface)) { return null; } String name = declaration.getQualifiedNameString(); if (name.equals("ceylon.language::Tuple")){ List<ProducedType> tal = args.getTypeArgumentList(); ProducedType first = tal.get(1); ProducedType rest = tal.get(2); List<ProducedType> ret = getSimpleTupleElementTypes(rest, count+1); if (ret == null) return null; ret.set(count, first); return ret; } if (name.equals("ceylon.language::Empty")){ ArrayList<ProducedType> ret = new ArrayList<ProducedType>(count); for (int i=0;i<count;i++) { ret.add(null); } return ret; } if (name.equals("ceylon.language::Sequential") || name.equals("ceylon.language::Sequence") || name.equals("ceylon.language::Range")) { ArrayList<ProducedType> ret = new ArrayList<ProducedType>(count+1); for (int i=0;i<count;i++) { ret.add(null); } ret.add(args); return ret; } return null; } public boolean isTupleLengthUnbounded(ProducedType args) { if (args!=null) { Boolean simpleTupleLengthUnbounded = isSimpleTupleLengthUnbounded(args); if (simpleTupleLengthUnbounded != null) { return simpleTupleLengthUnbounded.booleanValue(); } if (args.isSubtypeOf(getType(getEmptyDeclaration()))) { return false; } //TODO: this doesn't account for the case where // a tuple occurs in a union with [] ProducedType tst = nonemptyArgs(args) .getSupertype(getTupleDeclaration()); if (tst==null) { return true; } else { List<ProducedType> tal = tst.getTypeArgumentList(); if (tal.size()>=3) { return isTupleLengthUnbounded(tal.get(2)); } } } return false; } protected Boolean isSimpleTupleLengthUnbounded(ProducedType args) { // can be a defaulted tuple of Empty|Tuple TypeDeclaration declaration = args.getDeclaration(); if (declaration instanceof UnionType){ List<ProducedType> caseTypes = declaration.getCaseTypes(); if (caseTypes == null || caseTypes.size() != 2) { return null; } ProducedType caseA = caseTypes.get(0); TypeDeclaration caseADecl = caseA.getDeclaration(); ProducedType caseB = caseTypes.get(1); TypeDeclaration caseBDecl = caseB.getDeclaration(); if (!(caseADecl instanceof ClassOrInterface) || !(caseBDecl instanceof ClassOrInterface)) { return null; } String caseAName = caseADecl.getQualifiedNameString(); String caseBName = caseBDecl.getQualifiedNameString(); if (caseAName.equals("ceylon.language::Empty") && caseBName.equals("ceylon.language::Tuple")) { return isSimpleTupleLengthUnbounded(caseB); } if (caseBName.equals("ceylon.language::Empty") && caseAName.equals("ceylon.language::Tuple")) { return isSimpleTupleLengthUnbounded(caseA); } return null; } // can be Tuple, Empty, Sequence or Sequential if (!(declaration instanceof ClassOrInterface)) { return null; } String name = declaration.getQualifiedNameString(); if (name.equals("ceylon.language::Tuple")) { ProducedType rest = args.getTypeArgumentList().get(2); return isSimpleTupleLengthUnbounded(rest); } if (name.equals("ceylon.language::Empty")) { return false; } if (name.equals("ceylon.language::Range")) { return true; } if (name.equals("ceylon.language::Sequential") || name.equals("ceylon.language::Sequence")) { return true; } return null; } public boolean isTupleVariantAtLeastOne(ProducedType args) { if (args!=null) { Boolean simpleTupleVariantAtLeastOne = isSimpleTupleVariantAtLeastOne(args); if (simpleTupleVariantAtLeastOne != null) { return simpleTupleVariantAtLeastOne.booleanValue(); } if (getType(getEmptyDeclaration()).isSubtypeOf(args)) { return false; } ProducedType snt = getSequenceType(getType(getNothingDeclaration())); if (snt.isSubtypeOf(args)) { return true; } ProducedType tst = nonemptyArgs(args) .getSupertype(getTupleDeclaration()); if (tst == null) { return false; } else { List<ProducedType> tal = tst.getTypeArgumentList(); if (tal.size()>=3) { return isTupleVariantAtLeastOne(tal.get(2)); } } } return false; } private Boolean isSimpleTupleVariantAtLeastOne(ProducedType args) { // can be a defaulted tuple of Empty|Tuple TypeDeclaration declaration = args.getDeclaration(); if (declaration instanceof UnionType) { List<ProducedType> caseTypes = declaration.getCaseTypes(); if (caseTypes == null || caseTypes.size() != 2) { return null; } ProducedType caseA = caseTypes.get(0); TypeDeclaration caseADecl = caseA.getDeclaration(); ProducedType caseB = caseTypes.get(1); TypeDeclaration caseBDecl = caseB.getDeclaration(); if (!(caseADecl instanceof ClassOrInterface) || !(caseBDecl instanceof ClassOrInterface)) { return null; } String caseAName = caseADecl.getQualifiedNameString(); String caseBName = caseBDecl.getQualifiedNameString(); if (caseAName.equals("ceylon.language::Empty") && caseBName.equals("ceylon.language::Tuple")) { return isSimpleTupleVariantAtLeastOne(caseB); } if (caseBName.equals("ceylon.language::Empty") && caseAName.equals("ceylon.language::Tuple")) { return isSimpleTupleVariantAtLeastOne(caseA); } return null; } // can be Tuple, Empty, Sequence or Sequential if (!(declaration instanceof ClassOrInterface)) { return null; } String name = declaration.getQualifiedNameString(); if (name.equals("ceylon.language::Tuple")) { ProducedType rest = args.getTypeArgumentList().get(2); return isSimpleTupleVariantAtLeastOne(rest); } if (name.equals("ceylon.language::Empty")) { return false; } if (name.equals("ceylon.language::Range")) { return true; } if (name.equals("ceylon.language::Sequential")) { return false; } if (name.equals("ceylon.language::Sequence")) { return true; } return null; } public int getTupleMinimumLength(ProducedType args) { if (args!=null) { int simpleMinimumLength = getSimpleTupleMinimumLength(args); if (simpleMinimumLength != -1) { return simpleMinimumLength; } if (getType(getEmptyDeclaration()).isSubtypeOf(args)) { return 0; } ProducedType snt = getSequenceType(getType(getNothingDeclaration())); if (snt.isSubtypeOf(args)) { return 1; } ProducedType tst = nonemptyArgs(args) .getSupertype(getTupleDeclaration()); if (tst == null) { return 0; } else { List<ProducedType> tal = tst.getTypeArgumentList(); if (tal.size()>=3) { return getTupleMinimumLength(tal.get(2))+1; } } } return 0; } private int getSimpleTupleMinimumLength(ProducedType args) { // can be a defaulted tuple of Empty|Tuple TypeDeclaration declaration = args.getDeclaration(); if (declaration instanceof UnionType){ List<ProducedType> caseTypes = declaration.getCaseTypes(); if (caseTypes == null || caseTypes.size() != 2) { return -1; } ProducedType caseA = caseTypes.get(0); TypeDeclaration caseADecl = caseA.getDeclaration(); ProducedType caseB = caseTypes.get(1); TypeDeclaration caseBDecl = caseB.getDeclaration(); if (!(caseADecl instanceof ClassOrInterface) || !(caseBDecl instanceof ClassOrInterface)) { return -1; } String caseAName = caseADecl.getQualifiedNameString(); String caseBName = caseBDecl.getQualifiedNameString(); if (caseAName.equals("ceylon.language::Empty") && caseBName.equals("ceylon.language::Tuple")) { return 0; } if (caseBName.equals("ceylon.language::Empty") && caseAName.equals("ceylon.language::Tuple")) { return 0; } return -1; } // can be Tuple, Empty, Sequence or Sequential if (!(declaration instanceof ClassOrInterface)) { return -1; } String name = declaration.getQualifiedNameString(); if (name.equals("ceylon.language::Tuple")) { ProducedType rest = args.getTypeArgumentList().get(2); int ret = getSimpleTupleMinimumLength(rest); return ret == -1 ? -1 : ret + 1; } if (name.equals("ceylon.language::Empty")) { return 0; } if (name.equals("ceylon.language::Range")) { return 1; } if (name.equals("ceylon.language::Sequential")) { return 0; } if (name.equals("ceylon.language::Sequence")) { return 1; } return -1; } public List<ProducedType> getCallableArgumentTypes(ProducedType t) { ProducedType tuple = getCallableTuple(t); if (tuple == null) { return Collections.emptyList(); } else { return getTupleElementTypes(tuple); } } public ProducedType getCallableTuple(ProducedType t) { if (t==null) return null; ProducedType ct = t.getSupertype(getCallableDeclaration()); if (ct!=null) { List<ProducedType> typeArgs = ct.getTypeArgumentList(); if (typeArgs.size()>=2) { return typeArgs.get(1); } } return null; } public ProducedType getCallableReturnType(ProducedType t) { if (t==null) return null; if (t.isNothing()) return t; ProducedType ct = t.getSupertype(getCallableDeclaration()); if (ct!=null) { List<ProducedType> typeArgs = ct.getTypeArgumentList(); if (typeArgs.size()>=1) { return typeArgs.get(0); } } return null; } public boolean isIterableParameterType(ProducedType t) { return t.getDeclaration() instanceof Interface && t.getDeclaration().equals(getIterableDeclaration()); } public TypeDeclaration getLanguageModuleModelTypeDeclaration(String name) { return (TypeDeclaration) getLanguageModuleModelDeclaration(name); } public TypeDeclaration getLanguageModuleDeclarationTypeDeclaration(String name) { return (TypeDeclaration) getLanguageModuleDeclarationDeclaration(name); } private final Map<String,String> modifiers = new HashMap<String,String>(); private void put(String modifier) { modifiers.put(modifier, modifier); } { put("shared"); put("default"); put("formal"); put("native"); put("actual"); put("abstract"); put("final"); put("sealed"); put("variable"); put("late"); put("deprecated"); put("annotation"); put("optional"); put("serializable"); } public Map<String, String> getModifiers() { return modifiers; } public ProducedType getValueMetatype(ProducedTypedReference pr) { boolean variable = pr.getDeclaration().isVariable(); ProducedType getType = pr.getType(); ProducedType setType = variable ? pr.getType() : new NothingType(this).getType(); ProducedType qualifyingType = pr.getQualifyingType(); if (qualifyingType!=null) { TypeDeclaration ad = getLanguageModuleModelTypeDeclaration( "Attribute"); return producedType(ad, qualifyingType, getType, setType); } else { TypeDeclaration vd = getLanguageModuleModelTypeDeclaration( "Value"); return producedType(vd, getType, setType); } } public ProducedType getFunctionMetatype(ProducedTypedReference pr) { TypedDeclaration d = pr.getDeclaration(); Functional f = (Functional) d; if (f.getParameterLists().isEmpty()) { return null; } ParameterList fpl = f.getParameterLists().get(0); ProducedType parameterTuple = getParameterTypesAsTupleType(fpl.getParameters(), pr); ProducedType returnType = getCallableReturnType(pr.getFullType()); if (returnType == null) { return null; } else { ProducedType qualifyingType = pr.getQualifyingType(); if (qualifyingType!=null) { TypeDeclaration md = getLanguageModuleModelTypeDeclaration( "Method"); return producedType(md, qualifyingType, returnType, parameterTuple); } else { TypeDeclaration fd = getLanguageModuleModelTypeDeclaration( "Function"); return producedType(fd, returnType, parameterTuple); } } } public ProducedType getConstructorMetatype(ProducedType pr) { TypeDeclaration d = pr.getDeclaration(); Functional f = (Functional) d; if (f.getParameterLists().isEmpty()) { return null; } ParameterList fpl = f.getParameterLists().get(0); ProducedType parameterTuple = getParameterTypesAsTupleType(fpl.getParameters(), pr); ProducedType returnType = getCallableReturnType(pr.getFullType()); if (returnType == null) { return null; } else { ProducedType qt = pr.getQualifyingType(); if (qt!=null && !qt.getDeclaration().isToplevel()) { ProducedType qqt = qt.getQualifyingType(); TypeDeclaration mccd = getLanguageModuleModelTypeDeclaration( "MemberClassConstructor"); return producedType(mccd, qqt, returnType, parameterTuple); } else { TypeDeclaration cd = getLanguageModuleModelTypeDeclaration( "Constructor"); return producedType(cd, returnType, parameterTuple); } } } public ProducedType getClassMetatype(ProducedType literalType) { Class c = (Class) literalType.getDeclaration(); ParameterList parameterList = c.getParameterList(); ProducedType parameterTuple; if ((c.isClassOrInterfaceMember() || c.isToplevel()) && parameterList!=null) { parameterTuple = getParameterTypesAsTupleType( parameterList.getParameters(), literalType); } else { parameterTuple = new NothingType(this).getType(); } ProducedType qualifyingType = literalType.getQualifyingType(); if (qualifyingType!=null) { TypeDeclaration mcd = getLanguageModuleModelTypeDeclaration( "MemberClass"); return producedType(mcd, qualifyingType, literalType, parameterTuple); } else { TypeDeclaration cd = getLanguageModuleModelTypeDeclaration( "Class"); return producedType(cd, literalType, parameterTuple); } } public ProducedType getInterfaceMetatype(ProducedType literalType) { ProducedType qualifyingType = literalType.getQualifyingType(); if (qualifyingType!=null) { TypeDeclaration mid = getLanguageModuleModelTypeDeclaration( "MemberInterface"); return producedType(mid, qualifyingType, literalType); } else { TypeDeclaration id = getLanguageModuleModelTypeDeclaration( "Interface"); return producedType(id, literalType); } } public ProducedType getTypeMetaType(ProducedType literalType) { TypeDeclaration declaration = literalType.getDeclaration(); if (declaration instanceof UnionType) { TypeDeclaration utd = getLanguageModuleModelTypeDeclaration( "UnionType"); return producedType(utd, literalType); } else if (declaration instanceof IntersectionType) { TypeDeclaration itd = getLanguageModuleModelTypeDeclaration( "IntersectionType"); return producedType(itd, literalType); } else { TypeDeclaration td = getLanguageModuleModelTypeDeclaration( "Type"); return producedType(td, literalType); } } public ProducedType getParameterTypesAsTupleType(List<Parameter> params, ProducedReference pr) { List<ProducedType> paramTypes = new ArrayList<ProducedType>(params.size()); int max = params.size()-1; int firstDefaulted = -1; boolean sequenced = false; boolean atLeastOne = false; for (int i=0; i<=max; i++) { Parameter p = params.get(i); ProducedType ft; if (p.getModel() == null) { ft = new UnknownType(this).getType(); } else { ft = pr.getTypedParameter(p).getFullType(); if (firstDefaulted<0 && p.isDefaulted()) { firstDefaulted = i; } if (i==max && p.isSequenced()) { sequenced = true; atLeastOne = p.isAtLeastOne(); if (ft!=null) { ft = getIteratedType(ft); } } } paramTypes.add(ft); } return getTupleType(paramTypes, sequenced, atLeastOne, firstDefaulted); } public ProducedType getType(TypeDeclaration td) { return td==null ? new UnknownType(this).getType() : td.getType(); } public ProducedType getPackageDeclarationType() { return getType(getLanguageModuleDeclarationTypeDeclaration("Package")); } public ProducedType getModuleDeclarationType() { return getType(getLanguageModuleDeclarationTypeDeclaration("Module")); } public ProducedType getImportDeclarationType() { return getType(getLanguageModuleDeclarationTypeDeclaration("Import")); } public ProducedType getClassDeclarationType() { return getType(getLanguageModuleDeclarationTypeDeclaration("ClassDeclaration")); } public ProducedType getClassDeclarationType(Class clazz) { return clazz.hasConstructors() ? getType(getLanguageModuleDeclarationTypeDeclaration("ClassWithConstructorsDeclaration")) : getType(getLanguageModuleDeclarationTypeDeclaration("ClassWithInitializerDeclaration")); } public ProducedType getConstructorDeclarationType() { return getType(getLanguageModuleDeclarationTypeDeclaration("ConstructorDeclaration")); } public ProducedType getInterfaceDeclarationType() { return getType(getLanguageModuleDeclarationTypeDeclaration("InterfaceDeclaration")); } public ProducedType getAliasDeclarationType() { return getType(getLanguageModuleDeclarationTypeDeclaration("AliasDeclaration")); } public ProducedType getTypeParameterDeclarationType() { return getType(getLanguageModuleDeclarationTypeDeclaration("TypeParameter")); } public ProducedType getFunctionDeclarationType() { return getType(getLanguageModuleDeclarationTypeDeclaration("FunctionDeclaration")); } public ProducedType getValueDeclarationType() { return getType(getLanguageModuleDeclarationTypeDeclaration("ValueDeclaration")); } public TypeDeclaration getAnnotationDeclaration() { return (TypeDeclaration) getLanguageModuleDeclaration("Annotation"); } public TypeDeclaration getConstrainedAnnotationDeclaration() { return (TypeDeclaration) getLanguageModuleDeclaration("ConstrainedAnnotation"); } public TypeDeclaration getSequencedAnnotationDeclaration() { return (TypeDeclaration) getLanguageModuleDeclaration("SequencedAnnotation"); } public TypeDeclaration getOptionalAnnotationDeclaration() { return (TypeDeclaration) getLanguageModuleDeclaration("OptionalAnnotation"); } public TypeDeclaration getDeclarationDeclaration() { return getLanguageModuleDeclarationTypeDeclaration("Declaration"); } public TypeDeclaration getClassModelDeclaration() { return getLanguageModuleModelTypeDeclaration("ClassModel"); } public TypeDeclaration getInterfaceModelDeclaration() { return getLanguageModuleModelTypeDeclaration("InterfaceModel"); } public TypeDeclaration getFunctionModelDeclaration() { return getLanguageModuleModelTypeDeclaration("FunctionModel"); } public TypeDeclaration getValueModelDeclaration() { return getLanguageModuleModelTypeDeclaration("ValueModel"); } public TypeDeclaration getConstructorModelDeclaration() { return getLanguageModuleModelTypeDeclaration("ConstructorModel"); } public ProducedTypeCache getCache() { Module module = getPackage().getModule(); return module != null ? module.getCache() : null; } }
package com.swabunga.spell.engine; import com.swabunga.util.StringUtility; import java.io.*; import java.util.HashMap; import java.util.Vector; /** * A Generic implementation of a transformator takes an aspell phonetics file and constructs * some sort of transformation table using the inner class Rule. * * @author Robert Gustavsson (robert@lindesign.se) */ public class GenericTransformator implements Transformator { /** * This replace list is used if no phonetic file is supplied or it doesn't * contain the alphabet. */ private static final char[] defaultEnglishAlphabet = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; public static final char ALPHABET_START = '['; public static final char ALPHABET_END = ']'; public static final String KEYWORD_ALPHBET = "alphabet"; public static final String[] IGNORED_KEYWORDS = {"version", "followup", "collapse_result"}; public static final char STARTMULTI = '('; public static final char ENDMULTI = ')'; public static final String DIGITCODE = "0"; public static final String REPLACEVOID = "_"; private Object[] ruleArray = null; private char[] alphabetString = defaultEnglishAlphabet; public GenericTransformator(File phonetic) throws IOException { buildRules(new BufferedReader(new FileReader(phonetic))); alphabetString = washAlphabetIntoReplaceList(getReplaceList()); } public GenericTransformator(Reader phonetic) throws IOException { buildRules(new BufferedReader(phonetic)); alphabetString = washAlphabetIntoReplaceList(getReplaceList()); } /** * Goes through an alphabet and makes sure that only one of those letters * that are coded equally will be in the replace list. * In other words, it removes any letters in the alphabet * that are redundant phonetically. * * This is done to improve speed in the getSuggestion method. * * @param alphabet The complete alphabet to wash. * @return The washed alphabet to be used as replace list. */ private char[] washAlphabetIntoReplaceList(char[] alphabet) { HashMap letters = new HashMap(alphabet.length); for (int i = 0; i < alphabet.length; i++) { String tmp = String.valueOf(alphabet[i]); String code = transform(tmp); if (!letters.containsKey(code)) { letters.put(code, new Character(alphabet[i])); } } Object[] tmpCharacters = letters.values().toArray(); char[] washedArray = new char[tmpCharacters.length]; for (int i = 0; i < tmpCharacters.length; i++) { washedArray[i] = ((Character) tmpCharacters[i]).charValue(); } return washedArray; } /** * Takes out all single character replacements and put them in a char array. * This array can later be used for adding or changing letters in getSuggestion(). * @return char[] An array of chars with replacements characters */ public char[] getCodeReplaceList() { char[] replacements; TransformationRule rule; Vector tmp = new Vector(); if (ruleArray == null) return null; for (int i = 0; i < ruleArray.length; i++) { rule = (TransformationRule) ruleArray[i]; if (rule.getReplaceExp().length() == 1) tmp.addElement(rule.getReplaceExp()); } replacements = new char[tmp.size()]; for (int i = 0; i < tmp.size(); i++) { replacements[i] = ((String) tmp.elementAt(i)).charAt(0); } return replacements; } /** * Builds up an char array with the chars in the alphabet of the language as it was read from the * alphabet tag in the phonetic file. * @return char[] An array of chars representing the alphabet or null if no alphabet was available. */ public char[] getReplaceList() { return alphabetString; } /** * Returns the phonetic code of the word. */ public String transform(String word) { if (ruleArray == null) return null; TransformationRule rule; StringBuffer str = new StringBuffer(word.toUpperCase()); int strLength = str.length(); int startPos = 0, add = 1; while (startPos < strLength) { add = 1; if (Character.isDigit(str.charAt(startPos))) { StringUtility.replace(str, startPos, startPos + DIGITCODE.length(), DIGITCODE); startPos += add; continue; } for (int i = 0; i < ruleArray.length; i++) { //System.out.println("Testing rule rule = (TransformationRule) ruleArray[i]; if (rule.startsWithExp() && startPos > 0) continue; if (startPos + rule.lengthOfMatch() > strLength) { continue; } if (rule.isMatching(str, startPos)) { String replaceExp = rule.getReplaceExp(); add = replaceExp.length(); StringUtility.replace(str, startPos, startPos + rule.getTakeOut(), replaceExp); strLength -= rule.getTakeOut(); strLength += add; //System.out.println("Replacing with rule#:"+i+" add="+add); break; } } startPos += add; } //System.out.println(word); //System.out.println(str.toString()); return str.toString(); } // Used to build up the transformastion table. private void buildRules(BufferedReader in) throws IOException { String read = null; Vector ruleList = new Vector(); while ((read = in.readLine()) != null) { buildRule(realTrimmer(read), ruleList); } ruleArray = new TransformationRule[ruleList.size()]; ruleList.copyInto(ruleArray); } // Here is where the real work of reading the phonetics file is done. private void buildRule(String str, Vector ruleList) { if (str.length() < 1) return; for (int i = 0; i < IGNORED_KEYWORDS.length; i++) { if (str.startsWith(IGNORED_KEYWORDS[i])) return; } // A different alphabet is used for this language, will be read into // the alphabetString variable. if (str.startsWith(KEYWORD_ALPHBET)) { int start = str.indexOf(ALPHABET_START); int end = str.lastIndexOf(ALPHABET_END); if (end != -1 && start != -1) { alphabetString = str.substring(++start, end).toCharArray(); } return; } TransformationRule rule = null; StringBuffer matchExp = new StringBuffer(); StringBuffer replaceExp = new StringBuffer(); boolean start = false, end = false; int takeOutPart = 0, matchLength = 0; boolean match = true, inMulti = false; for (int i = 0; i < str.length(); i++) { if (Character.isWhitespace(str.charAt(i))) { match = false; } else { if (match) { if (!isReservedChar(str.charAt(i))) { matchExp.append(str.charAt(i)); if (!inMulti) { takeOutPart++; matchLength++; } if (str.charAt(i) == STARTMULTI || str.charAt(i) == ENDMULTI) inMulti = !inMulti; } if (str.charAt(i) == '-') takeOutPart if (str.charAt(i) == '^') start = true; if (str.charAt(i) == '$') end = true; } else { replaceExp.append(str.charAt(i)); } } } if (replaceExp.toString().equals(REPLACEVOID)) { replaceExp = new StringBuffer(""); //System.out.println("Changing _ to \"\" for "+matchExp.toString()); } rule = new TransformationRule(matchExp.toString(), replaceExp.toString(), takeOutPart, matchLength, start, end); //System.out.println(rule.toString()); ruleList.addElement(rule); } // Chars with special meaning to aspell. Not everyone is implemented here. private boolean isReservedChar(char ch) { if (ch == '<' || ch == '>' || ch == '^' || ch == '$' || ch == '-' || Character.isDigit(ch)) return true; return false; } // Trims off everything we don't care about. private String realTrimmer(String row) { int pos = row.indexOf(' if (pos != -1) { row = row.substring(0, pos); } return row.trim(); } // Inner Classes /* * Holds the match string and the replace string and all the rule attributes. * Is responsible for indicating matches. */ private class TransformationRule { private String replace; private char[] match; // takeOut=number of chars to replace; // matchLength=length of matching string counting multies as one. private int takeOut, matchLength; private boolean start, end; // Construktor public TransformationRule(String match, String replace, int takeout, int matchLength, boolean start, boolean end) { this.match = match.toCharArray(); this.replace = replace; this.takeOut = takeout; this.matchLength = matchLength; this.start = start; this.end = end; } /* * Returns true if word from pos and forward matches the match string. * Precondition: wordPos+matchLength<word.length() */ public boolean isMatching(StringBuffer word, int wordPos) { boolean matching = true, inMulti = false, multiMatch = false; char matchCh; for (int matchPos = 0; matchPos < match.length; matchPos++) { matchCh = match[matchPos]; if (matchCh == STARTMULTI || matchCh == ENDMULTI) { inMulti = !inMulti; if (!inMulti) matching = matching & multiMatch; else multiMatch = false; } else { if (matchCh != word.charAt(wordPos)) { if (inMulti) multiMatch = multiMatch | false; else matching = false; } else { if (inMulti) multiMatch = multiMatch | true; else matching = true; } if (!inMulti) wordPos++; if (!matching) break; } } if (end && wordPos != word.length()) matching = false; return matching; } public String getReplaceExp() { return replace; } public int getTakeOut() { return takeOut; } public boolean startsWithExp() { return start; } public int lengthOfMatch() { return matchLength; } // Just for debugging purposes. public String toString() { return "Match:" + String.valueOf(match) + " Replace:" + replace + " TakeOut:" + takeOut + " MatchLength:" + matchLength + " Start:" + start + " End:" + end; } } }
package com.tactfactory.harmony.plateforme; import com.tactfactory.harmony.HarmonyContext; import com.tactfactory.harmony.Harmony; import com.tactfactory.harmony.meta.ApplicationMetadata; /** Base Adapter of project structure. */ public abstract class BaseAdapter implements IAdapter { // Structure /** Project path. */ private String project; /** Platform path. */ private String platform; /** Resources path. */ private String resource; /** Assets path. */ private String assets; /** Source path. */ private String source; /** Libs path. */ private String libs; /** Tests path. */ private String test; /** Tests libraries path. */ private String testLibs; /** Harmony path. */ private String harmony; /** Widgets path. */ private String widget; /** Utility classes path. */ private String util; /** Template Utility files path. */ private String utilityPath; /** Bundle template files path. */ private String bundleTemplates = "bundle"; // Bundles /** Bundle template files path. */ private String annotationsBundleTemplates = "annotation"; /** Bundle template files path. */ private String templateBundleTemplates = "template"; /** Bundle template files path. */ private String parserBundleTemplates = "parser"; /** Bundle template files path. */ private String metaBundleTemplates = "meta"; /** Bundle template files path. */ private String commandBundleTemplates = "command"; // MVC /** Models path. */ private String model = "entity"; /** Views path. */ private String view = "layout"; /** Views path. */ private String largeView = "layout-xlarge"; /** Values path. */ private String values = "values"; /** Values path. */ private String valuesXLarge = "values-xlarge"; /** Controllers path. */ private String controller = "view"; /** Data path. */ private String data = "data"; /** Providers path. */ private String provider = "provider"; /** Common path. */ private String common = "common"; /** Services path. */ private String service = "service"; /** Fixtures path. */ private String fixture = "fixture"; /** Criterias path. */ private String criterias = "criterias"; /** Base path. */ private String base = "base"; // File /** Manifest path. */ private String manifest; /** Home path. */ private String home; /** Strings path. */ private String strings; /** Configs path. */ private String configs; /** Menu path. */ private String menu; public BaseAdapter(final BaseAdapter adapter) { this(); adapter.cloneTo(this); } public BaseAdapter() { } @Override public final ApplicationMetadata getApplicationMetadata() { //TODO return a copy of ApplicationMetadata.INSTANCE // to preserve data modifications return ApplicationMetadata.INSTANCE; } // Utils /** * Get the template project path. * @return The template project path */ public final String getTemplateProjectPath() { return String.format("%s%s/%s/", Harmony.getTemplatesPath(), this.getPlatform(), this.getProject()); } /** * Get the libraries path. * @return The libraries path */ public final String getLibsPath() { return String.format("%s%s/%s/", Harmony.getProjectPath(), this.getPlatform(), this.getLibs()); } /** * Get the tests path. * @return The tests path */ public final String getTestPath() { return String.format("%s%s/%s/", Harmony.getProjectPath(), this.getPlatform(), this.getTest()); } /** * Get the test libraries path. * @return The test libraries path */ public final String getTestLibsPath() { return String.format("%s%s/", this.getTestPath(), this.getTestLibs()); } /** * Get the sources path. * @return The sources path */ public String getSourcePath() { return String.format("%s%s/%s/", Harmony.getProjectPath(), this.getPlatform(), this.getSource()); } /** * Get the sources path. * @return The sources path */ public String getSourceControllerPath() { return String.format("%s%s/%s/", this.getSourcePath(), this.getApplicationMetadata().getProjectNameSpace(), this.getController()); } /** * Get the widgets path. * @return The widgets path */ public final String getWidgetPath() { return String.format("%s%s/%s/%s/", this.getSourcePath(), this.getApplicationMetadata().getProjectNameSpace(), this.getHarmony(), this.getWidget()); } /** * Get the utility classes path. * @return The utility classes path */ public String getUtilPath() { return String.format("%s%s/%s/%s/", this.getSourcePath(), this.getApplicationMetadata().getProjectNameSpace(), this.getHarmony(), this.getUtil()); } /** * Get the project's menu path. * @return The menu path */ public final String getMenuPath() { return String.format("%s%s/%s/", this.getSourcePath(), this.getApplicationMetadata().getProjectNameSpace(), this.getMenu()); } /** * Get the project's menu base path. * @return The menu base path */ public final String getMenuBasePath() { return String.format("%s%s/", this.getMenuPath(), this.getBase()); } /** * Get the project's menu path. * @return The menu path */ public final String getTemplateMenuPath() { return String.format("%s%s/", this.getTemplateSourcePath(), this.getMenu()); } /** * Get the project's menu base path. * @return The menu base path */ public final String getTemplateMenuBasePath() { return String.format("%s%s/", this.getTemplateMenuPath(), this.getBase()); } /** * Get the widget's templates path. * @return The widget's templates path */ public final String getTemplateWidgetPath() { return String.format("%s%s/", this.getTemplateSourcePath(), this.getWidget()); } /** * Get the utility classes' templates path. * @return The utility classes' templates path */ public final String getTemplateUtilPath() { return String.format("%s%s/%s/", this.getTemplateSourcePath(), this.getHarmony(), this.getUtil()); } /** * Get the utility classes' templates path. * @return The utility classes' templates path */ public final String getTemplateUtilityPath() { //Path begin with / because it is interpreted by freemarker. return String.format("/%s%s/%s/", Harmony.getTemplatesPath(), this.getPlatform(), this.getUtilityPath()); } /** * Get the sources's templates path. * @return The source's templates path */ public final String getTemplateSourcePath() { return String.format("%s%s/%s/", Harmony.getTemplatesPath(), this.getPlatform(), this.getSource()); } /** * Get the controllers' templates path. * @return The controllers' templates path */ public final String getTemplateSourceControlerPath() { return String.format("%s%s/", this.getTemplateSourcePath(), this.getController()); } /** * Get the services' templates path. * @return The services' templates path */ public final String getTemplateSourceServicePath() { return String.format("%s%s/", this.getTemplateSourcePath(), this.getService()); } /** * Get the entities' templates path. * @return The entities' templates path */ public final String getTemplateSourceEntityBasePath() { return String.format("%s%s/%s/", this.getTemplateSourcePath(), this.getModel(), "base"); } /** * Get the providers' templates path. * @return The providers' templates path */ public final String getTemplateSourceProviderPath() { return String.format("%s%s/%s/%s/", Harmony.getTemplatesPath(), this.getPlatform(), this.getSource(), this.getProvider()); } /** * Get the data' templates path. * @return The data' templates path */ public final String getTemplateSourceDataPath() { return String.format("%s%s/%s/%s/", Harmony.getTemplatesPath(), this.getPlatform(), this.getSource(), this.getData()); } /** * Get the criteria's templates path. * @return The criteria's templates path */ public final String getTemplateSourceCriteriasPath() { return String.format("%s%s/", this.getTemplateSourcePath(), this.getCriterias()); } /** * Get the fixtures' templates path. * @return The fixtures' templates path */ public final String getTemplateSourceFixturePath() { return String.format("%s%s/", this.getTemplateSourcePath(), this.getFixture()); } /** * Get the common's templates path. * @return The common's templates path */ public final String getTemplateSourceCommonPath() { return String.format("%s%s/", this.getTemplateSourcePath(), this.getCommon()); } /** * Get the assets path. * @return The assets path */ public final String getAssetsPath() { return String.format("%s%s/%s/", Harmony.getProjectPath(), this.getPlatform(), this.getAssets()); } /** * Get the manifest's path. * @return The manifest's path */ public final String getManifestPathFile() { return String.format("%s/%s/%s", Harmony.getProjectPath(), this.getPlatform(), this.getManifest()); } /** * Get the manifest's template path. * @return The manifest's template path */ public final String getTemplateManifestPathFile() { return String.format("%s%s/%s/%s", Harmony.getTemplatesPath(), this.getPlatform(), this.getProject(), this.getManifest()); } /** * Get the strings path. * @return The strings path */ public String getStringsPathFile() { return String.format("%s%s/%s/%s/%s", Harmony.getProjectPath(), this.getPlatform(), this.getResource(), this.getValues(), this.getStrings()); } /** * Get the strings template path. * @return The strings template path */ public final String getTemplateStringsPathFile() { return String.format("%s%s/%s/%s/%s", Harmony.getTemplatesPath(), this.getPlatform(), this.getResource(), this.getValues(), this.getStrings()); } /** * Get the configs path. * @return The configs path */ public final String getConfigsPathFile() { return String.format("%s%s/%s/%s/%s", Harmony.getProjectPath(), this.getPlatform(), this.getResource(), this.getValues(), this.getConfigs()); } /** * Get the configs template path. * @return The configs template path */ public final String getTemplateConfigsPathFile() { return String.format("%s%s/%s/%s/%s", Harmony.getTemplatesPath(), this.getPlatform(), this.getResource(), this.getValues(), this.getConfigs()); } /** * Get the tests templates path. * @return The tests templates path */ public final String getTemplateTestsPath() { return String.format("%s%s/%s/", Harmony.getTemplatesPath(), this.getPlatform(), this.getTest()); } /** * Get the test project templates path. * @return The test project templates path */ public final String getTemplateTestProjectPath() { return String.format("%s%s/%s/%s/", Harmony.getTemplatesPath(), this.getPlatform(), this.getTest(), this.getProject()); } /** * Get the strings tests path. * @return The strings tests path */ public final String getStringsTestPathFile() { return String.format("%s%s/%s/%s/%s/%s", Harmony.getProjectPath(), this.getPlatform(), this.getTest(), this.getResource(), this.getValues(), this.getStrings()); } /** * Get the strings tests templates path. * @return The strings tests templates path */ public final String getTemplateStringsTestPathFile() { return String.format("%s%s/%s/%s/%s/%s", Harmony.getTemplatesPath(), this.getPlatform(), this.getTest(), this.getResource(), this.getValues(), this.getStrings()); } /** * Get the resource path. * @return The resource path */ public String getRessourcePath() { return String.format("%s%s/%s/", Harmony.getProjectPath(), this.getPlatform(), this.getResource()); } /** * Get the resource's templates path. * @return The resource's templates path */ public final String getTemplateRessourcePath() { return String.format("%s%s/%s/", Harmony.getTemplatesPath(), this.getPlatform(), this.getResource()); } /** * Get the source data namespace. * @return The source data namespace */ public final String getSourceDataNameSpace() { return String.format("%s.%s.%s.%s", Harmony.getProjectPath(), this.getPlatform(), this.getSource(), this.getData()); } /** * Get the source data namespace. * @return The source data namespace */ public final String getAnnotationBundleTemplatePath() { return String.format("%s%s/%s", Harmony.getTemplatesPath(), this.getBundleTemplates(), this.getAnnotationsBundleTemplates()); } /** * Get the source data namespace. * @param bundleOwnerName The bundle owner name * @param bundleNamespace The bundle namespace * @param bundleName The bundle name * @return The source data namespace */ public final String getAnnotationBundlePath( final String bundleOwnerName, final String bundleNamespace, final String bundleName) { return String.format("%s%s/src/%s/%s", Harmony.getBundlePath(), bundleOwnerName.toLowerCase() + "-" + bundleName.toLowerCase(), bundleNamespace.replaceAll("\\.", HarmonyContext.DELIMITER), this.getAnnotationsBundleTemplates()); } /** * Get the source data namespace. * @return The source data namespace */ public final String getCommandBundleTemplatePath() { return String.format("%s%s/%s", Harmony.getTemplatesPath(), this.getBundleTemplates(), this.getCommandBundleTemplates()); } /** * Get the source data namespace. * @param bundleOwnerName The bundle owner name * @param bundleNamespace The bundle namespace * @param bundleName The bundle name * @return The source data namespace */ public final String getCommandBundlePath( final String bundleOwnerName, final String bundleNamespace, final String bundleName) { return String.format("%s%s/src/%s/%s", Harmony.getBundlePath(), bundleOwnerName.toLowerCase() + "-" + bundleName.toLowerCase(), bundleNamespace.replaceAll("\\.", HarmonyContext.DELIMITER), this.getCommandBundleTemplates()); } /** * Get the source data namespace. * @return The source data namespace */ public final String getMetaBundleTemplatePath() { return String.format("%s%s/%s", Harmony.getTemplatesPath(), this.getBundleTemplates(), this.getMetaBundleTemplates()); } /** * Get the source data namespace. * @param bundleOwnerName The bundle owner name * @param bundleNamespace The bundle namespace * @param bundleName The bundle name * @return The source data namespace */ public final String getMetaBundlePath( final String bundleOwnerName, final String bundleNamespace, final String bundleName) { return String.format("%s%s/src/%s/%s", Harmony.getBundlePath(), bundleOwnerName.toLowerCase() + "-" + bundleName.toLowerCase(), bundleNamespace.replaceAll("\\.", HarmonyContext.DELIMITER), this.getMetaBundleTemplates()); } /** * Get the source data namespace. * @return The source data namespace */ public final String getTemplateBundleTemplatePath() { return String.format("%s%s/%s", Harmony.getTemplatesPath(), this.getBundleTemplates(), this.getTemplateBundleTemplates()); } /** * Get the source data namespace. * @param bundleOwnerName The bundle owner name * @param bundleNamespace The bundle namespace * @param bundleName The bundle name * @return The source data namespace */ public final String getTemplateBundlePath( final String bundleOwnerName, final String bundleNamespace, final String bundleName) { return String.format("%s%s/src/%s/%s", Harmony.getBundlePath(), bundleOwnerName.toLowerCase() + "-" + bundleName.toLowerCase(), bundleNamespace.replaceAll("\\.", HarmonyContext.DELIMITER), this.getTemplateBundleTemplates()); } /** * Get the source data namespace. * @return The source data namespace */ public final String getParserBundleTemplatePath() { return String.format("%s%s/%s", Harmony.getTemplatesPath(), this.getBundleTemplates(), this.getParserBundleTemplates()); } /** * Get the source data namespace. * @param bundleOwnerName The bundle owner name * @param bundleNamespace The bundle namespace * @param bundleName The bundle name * @return The source data namespace */ public final String getParserBundlePath( final String bundleOwnerName, final String bundleNamespace, final String bundleName) { return String.format("%s%s/src/%s/%s", Harmony.getBundlePath(), bundleOwnerName.toLowerCase() + "-" + bundleName.toLowerCase(), bundleNamespace.replaceAll("\\.", HarmonyContext.DELIMITER), this.getParserBundleTemplates()); } /** * Get the source data namespace. * @return The source data namespace */ public final String getBundleTemplatePath() { return String.format("%s%s", Harmony.getTemplatesPath(), this.getBundleTemplates()); } /** * Get the source data namespace. * @param bundleOwnerName The bundle owner name * @param bundleName The bundle name * @return The source data namespace */ public final String getBundlePath( final String bundleOwnerName, final String bundleName) { return String.format("%s%s/", Harmony.getBundlePath(), bundleOwnerName.toLowerCase() + "-" + bundleName.toLowerCase()); } // Getter and Setter /** * @return the project */ public final String getProject() { return this.project; } /** * @param project the project to set */ public final void setProject(final String project) { this.project = project; } /** * @return the resource */ public final String getResource() { return this.resource; } /** * @return the resource */ public final String getAssets() { return this.assets; } /** * @return the source */ public String getSource() { return this.source; } /** * @return the model */ public final String getModel() { return this.model; } /** * @return the view */ public final String getView() { return this.view; } /** * @return the large view */ public final String getLargeView() { return this.largeView; } /** * @return the controller */ public String getController() { return this.controller; } /** * @return the manifest */ public final String getManifest() { return this.manifest; } /** * @return the platform */ public final String getPlatform() { return this.platform; } /** * @param platform the platform to set */ public final void setPlatform(final String platform) { this.platform = platform; } /** * @param ressource the resource to set */ public final void setResource(final String ressource) { this.resource = ressource; } /** * @param assets the assets folder */ public final void setAssets(final String assets) { this.assets = assets; } /** * @param source the source to set */ public final void setSource(final String source) { this.source = source; } /** * @param model the model to set */ public final void setModel(final String model) { this.model = model; } /** * @param view the view to set */ public final void setView(final String view) { this.view = view; } /** * @param controller the controller to set */ public final void setController(final String controller) { this.controller = controller; } /** * @param manifest the manifest to set */ public final void setManifest(final String manifest) { this.manifest = manifest; } /** * @return the data */ public final String getData() { return this.data; } /** * @param data the data to set */ public final void setData(final String data) { this.data = data; } /** * @return the provider */ public final String getProvider() { return this.provider; } /** * @param provider the provider to set */ public final void setProvider(final String provider) { this.provider = provider; } /** * @return the criterias */ public final String getCriterias() { return this.criterias; } /** * @param criterias the criterias to set */ public final void setCriterias(final String criterias) { this.criterias = criterias; } /** * @return the base */ public final String getBase() { return this.base; } /** * @param base the base to set */ public final void setBase(final String base) { this.base = base; } /** * @return the common */ public final String getCommon() { return this.common; } /** * @param common the common to set */ public final void setCommon(final String common) { this.common = common; } /** * @return the service */ public final String getService() { return this.service; } /** * @param service the service to set */ public final void setService(final String service) { this.service = service; } /** * @return the service */ public final String getFixture() { return this.fixture; } /** * @param fixture the fixture folder */ public final void setFixture(final String fixture) { this.fixture = fixture; } /** * @return the values */ public final String getValues() { return this.values; } /** * @return the values-xlarge */ public final String getValuesXLarge() { return this.valuesXLarge; } /** * @param values the values to set */ public final void setValues(final String values) { this.values = values; } /** * @return the libs */ public final String getLibs() { return this.libs; } /** * @param libs the libs to set */ public final void setLibs(final String libs) { this.libs = libs; } /** * @return the HomeActivity filename */ public final String getHome() { return this.home; } /** * @param home the HomeActivity filename to set */ public final void setHome(final String home) { this.home = home; } /** * @return the strings.xml */ public final String getStrings() { return this.strings; } /** * @return the configs.xml */ public final String getConfigs() { return this.configs; } /** * @param config The config. */ public final void setConfigs(final String config) { this.configs = config; } /** * @param strings the strings.xml filename to set */ public final void setStrings(final String strings) { this.strings = strings; } /** * @return the test */ public final String getTest() { return this.test; } /** * @param test the test to set */ public final void setTest(final String test) { this.test = test; } /** * @return the testLibs */ public final String getTestLibs() { return this.testLibs; } /** * @param testLibs the testLibs to set */ public final void setTestLibs(final String testLibs) { this.testLibs = testLibs; } /** * @return the harmony */ public final String getHarmony() { return this.harmony; } /** * @param harmony the harmony to set */ public final void setHarmony(final String harmony) { this.harmony = harmony; } /** * @return the widget */ public final String getWidget() { return this.widget; } /** * @param widget the widget to set */ public final void setWidget(final String widget) { this.widget = widget; } /** * @return the util */ public final String getUtil() { return this.util; } /** * @param util the util to set */ public final void setUtil(final String util) { this.util = util; } /** * @return the menu */ public final String getMenu() { return this.menu; } /** * @param menu the menu to set */ public final void setMenu(final String menu) { this.menu = menu; } /** * @return the utility path */ public final String getUtilityPath() { return this.utilityPath; } /** * @param utilityPath The utility path to set */ public final void setUtilityPath(final String utilityPath) { this.utilityPath = utilityPath; } /** * @return the bundleTemplates */ public final String getBundleTemplates() { return bundleTemplates; } /** * @param bundleTemplates the bundleTemplates to set */ public final void setBundleTemplates( final String bundleTemplates) { this.bundleTemplates = bundleTemplates; } /** * @return the annotationsBundleTemplates */ public final String getAnnotationsBundleTemplates() { return annotationsBundleTemplates; } /** * @param annotationsBundleTemplates the annotationsBundleTemplates to set */ public final void setAnnotationsBundleTemplates( final String annotationsBundleTemplates) { this.annotationsBundleTemplates = annotationsBundleTemplates; } /** * @return the templateBundleTemplates */ public final String getTemplateBundleTemplates() { return templateBundleTemplates; } /** * @param templateBundleTemplates the templateBundleTemplates to set */ public final void setTemplateBundleTemplates( final String templateBundleTemplates) { this.templateBundleTemplates = templateBundleTemplates; } /** * @return the parserBundleTemplates */ public final String getParserBundleTemplates() { return parserBundleTemplates; } /** * @param parserBundleTemplates the parserBundleTemplates to set */ public final void setParserBundleTemplates( final String parserBundleTemplates) { this.parserBundleTemplates = parserBundleTemplates; } /** * @return the metaBundleTemplates */ public final String getMetaBundleTemplates() { return metaBundleTemplates; } /** * @param metaBundleTemplates the metaBundleTemplates to set */ public final void setMetaBundleTemplates( final String metaBundleTemplates) { this.metaBundleTemplates = metaBundleTemplates; } /** * @return the commandBundleTemplates */ public final String getCommandBundleTemplates() { return commandBundleTemplates; } /** * @param commandBundleTemplates the commandBundleTemplates to set */ public final void setCommandBundleTemplates( final String commandBundleTemplates) { this.commandBundleTemplates = commandBundleTemplates; } public void cloneTo(BaseAdapter adapter) { //TODO use reflection for that ! adapter.setAnnotationsBundleTemplates(this.getAnnotationsBundleTemplates()); adapter.setAssets(this.getAssets()); adapter.setBase(this.getBase()); adapter.setBundleTemplates(this.getBundleTemplates()); adapter.setCommandBundleTemplates(this.getCommandBundleTemplates()); adapter.setCommon(this.getCommon()); adapter.setConfigs(this.getConfigs()); adapter.setController(this.getController()); adapter.setCriterias(this.getCriterias()); adapter.setData(this.getData()); adapter.setFixture(this.getFixture()); adapter.setHarmony(this.getHarmony()); adapter.setHome(this.getHome()); adapter.setLibs(this.getLibs()); adapter.setManifest(this.getManifest()); adapter.setMenu(this.getMenu()); adapter.setMetaBundleTemplates(this.getMetaBundleTemplates()); adapter.setModel(this.getModel()); adapter.setParserBundleTemplates(this.getParserBundleTemplates()); adapter.setPlatform(this.getPlatform()); adapter.setProject(this.getProject()); adapter.setProvider(this.getProvider()); adapter.setResource(this.getResource()); adapter.setService(this.getService()); adapter.setSource(this.getSource()); adapter.setStrings(this.getStrings()); adapter.setTemplateBundleTemplates(this.getTemplateBundleTemplates()); adapter.setTest(this.getTest()); adapter.setTestLibs(this.getTestLibs()); adapter.setUtil(this.getUtil()); adapter.setUtilityPath(this.getUtilityPath()); adapter.setValues(this.getValues()); adapter.setView(this.getView()); adapter.setWidget(this.getWidget()); } }
package com.thaiopensource.relaxng.impl; import com.thaiopensource.xml.util.Name; import java.util.Vector; import java.util.Hashtable; import org.relaxng.datatype.ValidationContext; public class PatternMatcher implements Cloneable { static private class Shared { private final Pattern start; private final ValidatorPatternBuilder builder; private Hashtable recoverPatternTable; Shared(Pattern start, ValidatorPatternBuilder builder) { this.start = start; this.builder = builder; } Pattern findElement(Name name) { if (recoverPatternTable == null) recoverPatternTable = new Hashtable(); Pattern p = (Pattern)recoverPatternTable.get(name); if (p == null) { p = FindElementFunction.findElement(builder, name, start); recoverPatternTable.put(name, p); } return p; } PatternMemo fixAfter(PatternMemo p) { return builder.getPatternMemo(p.getPattern().applyForPattern(new ApplyAfterFunction(builder) { Pattern apply(Pattern p) { return builder.makeEmpty(); } })); } } private PatternMemo memo; private boolean textMaybeTyped; private boolean hadError; private boolean ignoreNextEndTag; private String errorMessage; private final Shared shared; PatternMatcher(Pattern start, ValidatorPatternBuilder builder) { shared = new Shared(start, builder); memo = builder.getPatternMemo(start); } public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new Error("unexpected CloneNotSupportedException"); } } public PatternMatcher copy() { return (PatternMatcher)clone(); } public boolean matchStartDocument() { if (memo.isNotAllowed()) return error("schema_allows_nothing"); return true; } public boolean matchStartTagOpen(Name name) { if (setMemo(memo.startTagOpenDeriv(name))) return true; PatternMemo next = memo.startTagOpenRecoverDeriv(name); if (!next.isNotAllowed()) { memo = next; return error("required_elements_missing"); } ValidatorPatternBuilder builder = shared.builder; next = builder.getPatternMemo(builder.makeAfter(shared.findElement(name), memo.getPattern())); memo = next; return error(next.isNotAllowed() ? "unknown_element" : "out_of_context_element", name); } public boolean matchAttributeName(Name name) { if (setMemo(memo.startAttributeDeriv(name))) return true; ignoreNextEndTag = true; return error("impossible_attribute_ignored", name); } public boolean matchAttributeValue(String value, ValidationContext vc) { if (ignoreNextEndTag) { ignoreNextEndTag = false; return true; } if (setMemo(memo.dataDeriv(value, vc))) return true; memo = memo.recoverAfter(); return error("bad_attribute_value_no_name"); // XXX add to catalog } public boolean matchStartTagClose() { boolean ret; if (setMemo(memo.endAttributes())) ret = true; else { memo = memo.ignoreMissingAttributes(); // XXX should specify which attributes ret = error("required_attributes_missing"); } textMaybeTyped = memo.getPattern().getContentType() == Pattern.DATA_CONTENT_TYPE; return ret; } public boolean matchText(String string, ValidationContext vc, boolean nextTagIsEndTag) { if (textMaybeTyped && nextTagIsEndTag) { ignoreNextEndTag = true; return setDataDeriv(string, vc); } else { if (DataDerivFunction.isBlank(string)) return true; return matchUntypedText(); } } public boolean matchUntypedText() { if (setMemo(memo.mixedTextDeriv())) return true; return error("text_not_allowed"); } public boolean isTextMaybeTyped() { return textMaybeTyped; } private boolean setDataDeriv(String string, ValidationContext vc) { textMaybeTyped = false; if (!setMemo(memo.textOnly())) { memo = memo.recoverAfter(); return error("only_text_not_allowed"); } if (setMemo(memo.dataDeriv(string, vc))) { ignoreNextEndTag = true; return true; } PatternMemo next = memo.recoverAfter(); boolean ret = true; if (!memo.isNotAllowed()) { if (!next.isNotAllowed() || shared.fixAfter(memo).dataDeriv(string, vc).isNotAllowed()) ret = error("string_not_allowed"); } memo = next; return ret; } public boolean matchEndTag(ValidationContext vc) { // The tricky thing here is that the derivative that we compute may be notAllowed simply because the parent // is notAllowed; we don't want to give an error in this case. if (ignoreNextEndTag) return true; if (textMaybeTyped) return setDataDeriv("", vc); textMaybeTyped = false; if (setMemo(memo.endTagDeriv())) return true; PatternMemo next = memo.recoverAfter(); if (memo.isNotAllowed()) { if (!next.isNotAllowed() || shared.fixAfter(memo).endTagDeriv().isNotAllowed()) { memo = next; return error("unfinished_element"); } } memo = next; return true; } public String getErrorMessage() { return errorMessage; } public boolean isValidSoFar() { return !hadError; } // members are of type Name public Vector possibleStartTags() { // XXX return null; } public Vector possibleAttributes() { // XXX return null; } private boolean setMemo(PatternMemo m) { if (m.isNotAllowed()) return false; else { memo = m; return true; } } private boolean error(String key) { if (hadError && memo.isNotAllowed()) return true; hadError = true; errorMessage = SchemaBuilderImpl.localizer.message(key); return false; } private boolean error(String key, Name arg) { return error(key, NameFormatter.format(arg)); } private boolean error(String key, String arg) { if (hadError && memo.isNotAllowed()) return true; hadError = true; errorMessage = SchemaBuilderImpl.localizer.message(key, arg); return false; } }
package com.timepath.tf2.hudedit.loaders; import com.timepath.tf2.hudedit.gui.EditorFrame; import com.timepath.tf2.hudedit.util.DataUtils; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.CRC32; /** * * @author TimePath */ public class CaptionLoader { private static final Logger logger = Logger.getLogger(CaptionLoader.class.getName()); public static String takeCRC32(String in) { CRC32 crc = new CRC32(); crc.update(in.toLowerCase().getBytes()); return Integer.toHexString((int)crc.getValue()).toUpperCase(); } private static String captionId = "VCCD"; private static int captionVer = 1; /** * Used for writing captions * @param curr * @param round * @return */ private static long alignValue(long curr, int round) { return (long) (Math.ceil(curr/round) * round); } /** * Entries are stored alphabetically by original value of hash */ private class Entry { Entry() { } Entry(int hash, int block, int offset, int length) { this.hash = hash; this.block = block; this.offset = offset; this.length = length; } int hash; int block; int offset; int length; @Override public String toString() { return new StringBuilder().append("H: ").append(hash).append(", b: ").append(block).append(", o: ").append(offset).append(", l: ").append(length).toString(); } } public CaptionLoader() { generateHash(); } private HashMap<Integer, String> hashmap = new HashMap<Integer, String>(); private void generateHash() { logger.info("Generating hash codes ..."); try { GcfFile gcf = GcfFile.load(new File(EditorFrame.locateSteamAppsDirectory() + "team fortress 2 content.gcf")); CRC32 crc = new CRC32(); String all = new String(gcf.ls); String[] ls = all.split("\0"); for(int i = 0; i < ls.length; i++) { int end = ls[i].length(); int ext = ls[i].lastIndexOf("."); if(ext != -1) { end = ext; } String sp = ls[i].substring(0, end); if(ls[i].toLowerCase().endsWith(".wav") || ls[i].toLowerCase().endsWith(".mp3") // ls[i].toLowerCase().endsWith(".vcd") || ls[i].toLowerCase().endsWith(".bsp") || // ls[i].toLowerCase().endsWith(".mp3") || ls[i].toLowerCase().endsWith(".bat") || // ls[i].toLowerCase().endsWith(".doc") || ls[i].toLowerCase().endsWith(".raw") || // ls[i].toLowerCase().endsWith(".pcf") || ls[i].toLowerCase().endsWith(".cfg") || // ls[i].toLowerCase().endsWith(".vbsp") || ls[i].toLowerCase().endsWith(".inf") || // ls[i].toLowerCase().endsWith(".rad") || ls[i].toLowerCase().endsWith(".vdf") || // ls[i].toLowerCase().endsWith(".ctx") || ls[i].toLowerCase().endsWith(".vdf") || // ls[i].toLowerCase().endsWith(".lst") || ls[i].toLowerCase().endsWith(".res") || // ls[i].toLowerCase().endsWith(".pop") || ls[i].toLowerCase().endsWith(".dll") || // ls[i].toLowerCase().endsWith(".dylib") || ls[i].toLowerCase().endsWith(".so") || // ls[i].toLowerCase().endsWith(".scr") || ls[i].toLowerCase().endsWith(".rc") || // ls[i].toLowerCase().endsWith(".vfe") || ls[i].toLowerCase().endsWith(".pre") || // ls[i].toLowerCase().endsWith(".cache") || ls[i].toLowerCase().endsWith(".nav") || // ls[i].toLowerCase().endsWith(".lmp") || ls[i].toLowerCase().endsWith(".bik") || // ls[i].toLowerCase().endsWith(".mov") || ls[i].toLowerCase().endsWith(".snd") || // ls[i].toLowerCase().endsWith(".midi") || ls[i].toLowerCase().endsWith(".png") || // ls[i].toLowerCase().endsWith(".ttf") || ls[i].toLowerCase().endsWith(".ico") || // ls[i].toLowerCase().endsWith(".dat") || ls[i].toLowerCase().endsWith(".pl") || // ls[i].toLowerCase().endsWith(".ain") || ls[i].toLowerCase().endsWith(".db") || // ls[i].toLowerCase().endsWith(".py") || ls[i].toLowerCase().endsWith(".xsc") || // ls[i].toLowerCase().endsWith(".bmp") || ls[i].toLowerCase().endsWith(".icns") || // ls[i].toLowerCase().endsWith(".txt") || ls[i].toLowerCase().endsWith(".manifest") ) { String str = sp.replaceAll("_", ".").replaceAll(" ", ""); crc.update(str.toLowerCase().getBytes()); hashmap.put((int)crc.getValue(), str); // HASH > // logger.log(Level.INFO, "{0} > {1}", new Object[]{crc.getValue(), str}); crc.reset(); } else { // logger.info(ls[i]); } } } catch (IOException ex) { Logger.getLogger(CaptionLoader.class.getName()).log(Level.WARNING, "Error generating hash codes", ex); } } private String attemptDecode(int hash) { if(hashmap.containsKey(hash)) { return hashmap.get(hash); } else { // logger.log(Level.INFO, "hashmap does not contain {0}", hash); return Integer.toHexString(hash).toUpperCase(); } } public ArrayList<String> load(String file) { if(file == null) { return null; } ArrayList<String> s = new ArrayList<String>(); try { RandomAccessFile rf = new RandomAccessFile(file, "r"); String magic = new String(new byte[] {DataUtils.readChar(rf), DataUtils.readChar(rf), DataUtils.readChar(rf),DataUtils.readChar(rf)}); int ver = DataUtils.readLEInt(rf); int blocks = DataUtils.readLEInt(rf); int blockSize = DataUtils.readLEInt(rf); int directorySize = DataUtils.readLEInt(rf); int dataOffset = DataUtils.readLEInt(rf); Entry[] entries = new Entry[directorySize]; for(int i = 0; i < directorySize; i++) { entries[i] = new Entry(DataUtils.readULong(rf), DataUtils.readLEInt(rf), DataUtils.readUShort(rf), DataUtils.readUShort(rf)); } rf.seek(dataOffset); // trustable, otherwise do: rf.seek(rf.getFilePointer() + (alignValue(rf.getFilePointer(), 512) - rf.getFilePointer())); for(int i = 0; i < directorySize; i++) { rf.seek(dataOffset + (entries[i].block * blockSize) + entries[i].offset); StringBuilder sb = new StringBuilder(entries[i].length / 2); for(int x = 0; x + 1 < (entries[i].length / 2); x++) { sb.append(DataUtils.readUTFChar(rf)); } rf.skipBytes(2); // \0\0 padding logger.log(Level.INFO, "{0} = {1}", new Object[]{entries[i], sb.toString()}); s.add(attemptDecode(entries[i].hash)); s.add(sb.toString()); } rf.close(); // The rest of the file is garbage } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); } return s; } }
package me.nallar.tickthreading.patcher; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.common.base.Splitter; import javassist.CannotCompileException; import javassist.ClassMap; import javassist.CtBehavior; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtField; import javassist.CtMethod; import javassist.CtNewMethod; import javassist.Modifier; import javassist.NotFoundException; import javassist.bytecode.BadBytecode; import javassist.expr.Cast; import javassist.expr.ConstructorCall; import javassist.expr.ExprEditor; import javassist.expr.FieldAccess; import javassist.expr.Handler; import javassist.expr.Instanceof; import javassist.expr.MethodCall; import javassist.expr.NewArray; import javassist.expr.NewExpr; import me.nallar.tickthreading.Log; import me.nallar.tickthreading.mappings.MethodDescription; @SuppressWarnings ("MethodMayBeStatic") public class Patches { private final ClassRegistry classRegistry; public Patches(ClassRegistry classRegistry) { this.classRegistry = classRegistry; } @Patch public void markDirty(CtClass ctClass) { // A NOOP patch to make sure META-INF is removed } @Patch ( name = "volatile" ) public void volatile_(CtClass ctClass, Map<String, String> attributes) throws NotFoundException { String field = attributes.get("field"); if (field == null) { for (CtField ctField : ctClass.getDeclaredFields()) { if (ctField.getType().isPrimitive()) { ctField.setModifiers(ctField.getModifiers() | Modifier.VOLATILE); } } } else { CtField ctField = ctClass.getDeclaredField(field); ctField.setModifiers(ctField.getModifiers() | Modifier.VOLATILE); } } @Patch ( requiredAttributes = "class" ) public CtClass replace(CtClass clazz, Map<String, String> attributes) throws NotFoundException, CannotCompileException { Log.info("Replacing " + clazz.getName() + " with " + attributes.get("class")); String oldName = clazz.getName(); clazz.setName(oldName + "_old"); CtClass newClass = classRegistry.getClass(attributes.get("class")); newClass.getClassFile2().setSuperclass(null); newClass.setName(oldName); newClass.setModifiers(newClass.getModifiers() & ~Modifier.ABSTRACT); return newClass; } @Patch public void replaceMethod(CtMethod method, Map<String, String> attributes) throws NotFoundException, CannotCompileException, BadBytecode { String fromClass = attributes.get("fromClass"); String code = attributes.get("code"); if (fromClass != null) { String fromMethod = attributes.get("fromMethod"); CtMethod replacingMethod = fromMethod == null ? classRegistry.getClass(fromClass).getDeclaredMethod(method.getName(), method.getParameterTypes()) : MethodDescription.fromString(fromClass, fromMethod).inClass(classRegistry.getClass(fromClass)); replaceMethod(method, replacingMethod); } else if (code != null) { Log.info("Replacing " + new MethodDescription(method).getMCPName() + " with " + code); method.setBody(code); } else { Log.severe("Missing required attributes for replaceMethod"); } } private void replaceMethod(CtMethod oldMethod, CtMethod newMethod) throws CannotCompileException, BadBytecode { Log.info("Replacing " + new MethodDescription(oldMethod).getMCPName() + " with " + new MethodDescription(newMethod).getMCPName()); ClassMap classMap = new ClassMap(); classMap.put(newMethod.getDeclaringClass().getName(), oldMethod.getDeclaringClass().getName()); oldMethod.setBody(newMethod, classMap); oldMethod.getMethodInfo().rebuildStackMap(classRegistry.classes); oldMethod.getMethodInfo().rebuildStackMapForME(classRegistry.classes); } @Patch ( requiredAttributes = "field" ) public void replaceFieldUsage(CtBehavior ctBehavior, Map<String, String> attributes) throws CannotCompileException { final String field = attributes.get("field"); final String readCode = attributes.get("readCode"); final String writeCode = attributes.get("writeCode"); if (readCode == null && writeCode == null) { throw new IllegalArgumentException("readCode or writeCode must be set"); } ctBehavior.instrument(new ExprEditor() { @Override public void edit(FieldAccess fieldAccess) throws CannotCompileException { if (fieldAccess.getFieldName().equals(field)) { if (fieldAccess.isWriter() && writeCode != null) { fieldAccess.replace(writeCode); } else if (fieldAccess.isReader() && readCode != null) { fieldAccess.replace(readCode); } } } }); } @Patch ( requiredAttributes = "code" ) public void replaceMethodCall(final CtBehavior ctBehavior, Map<String, String> attributes) throws CannotCompileException { String method_ = attributes.get("method"); if (method_ == null) { method_ = ""; } String className_ = null; int dotIndex = method_.indexOf('.'); if (dotIndex != -1) { className_ = method_.substring(0, dotIndex); method_ = method_.substring(dotIndex + 1); } String index_ = attributes.get("index"); if (index_ == null) { index_ = "-1"; } final String method = method_; final String className = className_; final String code = attributes.get("code"); final int index = Integer.valueOf(index_); ctBehavior.instrument(new ExprEditor() { private int currentIndex = 0; @Override public void edit(MethodCall methodCall) throws CannotCompileException { if ((className == null || methodCall.getClassName().equals(className)) && (method.isEmpty() || methodCall.getMethodName().equals(method)) && (index == -1 || currentIndex++ == index)) { Log.info("Replaced " + methodCall + " from " + ctBehavior); methodCall.replace(code); } } }); } @Patch ( requiredAttributes = "code,return,name" ) public void addMethod(CtClass ctClass, Map<String, String> attributes) throws NotFoundException, CannotCompileException { String name = attributes.get("name"); String return_ = attributes.get("return"); String code = attributes.get("code"); String parameterNamesList = attributes.get("parameters"); parameterNamesList = parameterNamesList == null ? "" : parameterNamesList; List<CtClass> parameterList = new ArrayList<CtClass>(); for (String parameterName : Splitter.on(',').trimResults().omitEmptyStrings().split(parameterNamesList)) { parameterList.add(classRegistry.getClass(parameterName)); } CtMethod newMethod = new CtMethod(classRegistry.getClass(return_), name, parameterList.toArray(new CtClass[parameterList.size()]), ctClass); newMethod.setBody('{' + code + '}'); ctClass.addMethod(newMethod); } @Patch ( requiredAttributes = "fromClass" ) public void addAll(CtClass ctClass, Map<String, String> attributes) throws NotFoundException, CannotCompileException, BadBytecode { String fromClass = attributes.get("fromClass"); CtClass from = classRegistry.getClass(fromClass); ClassMap classMap = new ClassMap(); classMap.put(fromClass, ctClass.getName()); for (CtField ctField : from.getDeclaredFields()) { if (!ctField.getName().isEmpty() && ctField.getName().charAt(ctField.getName().length() - 1) == '_') { ctField.setName(ctField.getName().substring(0, ctField.getName().length() - 1)); } try { ctClass.getDeclaredField(ctField.getName()); } catch (NotFoundException ignored) { Log.info("Added " + ctField); ctClass.addField(new CtField(ctField, ctClass)); } } for (CtMethod newMethod : from.getDeclaredMethods()) { if ((newMethod.getName().startsWith("construct") || newMethod.getName().startsWith("staticConstruct"))) { try { ctClass.getDeclaredMethod(newMethod.getName()); boolean found = true; int i = 0; String name = newMethod.getName(); while (found) { i++; try { ctClass.getDeclaredMethod(name + i); } catch (NotFoundException e2) { found = false; } } newMethod.setName(name + i); } catch (NotFoundException ignored) { // Not found - no need to change the name } } } for (CtMethod newMethod : from.getDeclaredMethods()) { try { CtMethod oldMethod = ctClass.getDeclaredMethod(newMethod.getName(), newMethod.getParameterTypes()); replaceMethod(oldMethod, newMethod); Log.info("Replaced " + newMethod); } catch (NotFoundException ignored) { CtMethod added = CtNewMethod.copy(newMethod, ctClass, classMap); Log.info("Adding " + added); ctClass.addMethod(added); if (added.getName().startsWith("construct")) { ctClass.addField(new CtField(classRegistry.getClass("boolean"), "isConstructed", ctClass), CtField.Initializer.constant(false)); for (CtBehavior ctBehavior : ctClass.getDeclaredConstructors()) { ctBehavior.insertAfter("{ if(!this.isConstructed) { this.isConstructed = true; this. " + added.getName() + "(); } }"); } } if (added.getName().startsWith("staticConstruct")) { ctClass.makeClassInitializer().insertAfter("{ " + added.getName() + "(); }"); } } } for (CtClass CtInterface : from.getInterfaces()) { ctClass.addInterface(CtInterface); } } @Patch ( requiredAttributes = "field,threadLocalField,type" ) public void threadLocal(CtClass ctClass, Map<String, String> attributes) throws CannotCompileException { final String field = attributes.get("field"); final String threadLocalField = attributes.get("threadLocalField"); final String type = attributes.get("type"); String setExpression_ = attributes.get("setExpression"); final String setExpression = setExpression_ == null ? '(' + type + ") $1" : setExpression_; Log.info(field + " -> " + threadLocalField); ctClass.instrument(new ExprEditor() { @Override public void edit(FieldAccess e) throws CannotCompileException { if (e.getFieldName().equals(field)) { if (e.isReader()) { e.replace("{ $_ = (" + type + ") " + threadLocalField + ".get(); }"); } else if (e.isWriter()) { e.replace("{ " + threadLocalField + ".set(" + setExpression + "); }"); } } } }); } @Patch ( name = "public", emptyConstructor = false ) public void makePublic(Object o, Map<String, String> attributes) throws NotFoundException { String field = attributes.get("field"); if (field == null) { CtBehavior ctBehavior = (CtBehavior) o; ctBehavior.setModifiers(Modifier.setPublic(ctBehavior.getModifiers())); } else { CtClass ctClass = (CtClass) o; CtField ctField = ctClass.getDeclaredField(field); ctField.setModifiers(Modifier.setPublic(ctField.getModifiers())); } } @Patch ( requiredAttributes = "field" ) public void newInitializer(CtClass ctClass, Map<String, String> attributes) throws NotFoundException, CannotCompileException, IOException { String field = attributes.get("field"); String clazz = attributes.get("class"); String initialise = attributes.get("code"); String arraySize = attributes.get("arraySize"); initialise = "{ " + field + " = " + (initialise == null ? ("new " + clazz + (arraySize == null ? "()" : '[' + arraySize + ']')) : initialise) + "; }"; // Return value ignored - just used to cause a NotFoundException if the field doesn't exist. ctClass.getDeclaredField(field); for (CtConstructor ctConstructor : ctClass.getConstructors()) { ctConstructor.insertAfter(initialise); } if (clazz != null) { classRegistry.add(ctClass, clazz); } } @Patch ( requiredAttributes = "field" ) public void replaceField(CtClass ctClass, Map<String, String> attributes) throws NotFoundException, CannotCompileException, IOException { String field = attributes.get("field"); String clazz = attributes.get("class"); String type = attributes.get("type"); if (type == null) { type = clazz; } String initialise = attributes.get("code"); String arraySize = attributes.get("arraySize"); initialise = "{ " + field + " = " + (initialise == null ? ("new " + clazz + (arraySize == null ? "()" : '[' + arraySize + ']')) : initialise) + "; }"; CtField oldField = ctClass.getDeclaredField(field); oldField.setName(oldField.getName() + "_old"); CtField newField = new CtField(classRegistry.getClass(type), field, ctClass); newField.setModifiers(oldField.getModifiers()); ctClass.addField(newField); for (CtConstructor ctConstructor : ctClass.getConstructors()) { ctConstructor.insertAfter(initialise); } if (clazz != null) { classRegistry.add(ctClass, clazz); } } @Patch ( requiredAttributes = "field,class" ) public void newField(CtClass ctClass, Map<String, String> attributes) throws NotFoundException, CannotCompileException, IOException { String field = attributes.get("field"); String clazz = attributes.get("class"); String initialise = attributes.get("code"); if (initialise == null) { initialise = "new " + clazz + "();"; } CtClass newType = classRegistry.getClass(clazz); CtField ctField = new CtField(newType, field, ctClass); if (attributes.get("static") != null) { ctField.setModifiers(ctField.getModifiers() | Modifier.STATIC | Modifier.PUBLIC); } CtField.Initializer initializer = CtField.Initializer.byExpr(initialise); ctClass.addField(ctField, initializer); classRegistry.add(ctClass, clazz); } @Patch ( requiredAttributes = "code" ) public void insertBefore(CtBehavior ctBehavior, Map<String, String> attributes) throws NotFoundException, CannotCompileException, IOException { String field = attributes.get("field"); String code = attributes.get("code"); if (field != null) { code = code.replace("$field", field); } ctBehavior.insertBefore(code); } @Patch ( requiredAttributes = "code" ) public void insertAfter(CtBehavior ctBehavior, Map<String, String> attributes) throws NotFoundException, CannotCompileException, IOException { String field = attributes.get("field"); String code = attributes.get("code"); if (field != null) { code = code.replace("$field", field); } ctBehavior.insertAfter(code); } @Patch public void insertSuper(CtBehavior ctBehavior) throws CannotCompileException { ctBehavior.insertBefore("super." + ctBehavior.getName() + "($$);"); } @Patch ( requiredAttributes = "field" ) public void lock(CtMethod ctMethod, Map<String, String> attributes) throws NotFoundException, CannotCompileException, IOException { String field = attributes.get("field"); CtClass ctClass = ctMethod.getDeclaringClass(); CtMethod replacement = CtNewMethod.copy(ctMethod, ctClass, null); ctMethod.setName(ctMethod.getName() + "_nolock"); replacement.setBody("{ this." + field + ".lock(); try { return " + (attributes.get("methodcall") == null ? "$proceed" : ctMethod.getName()) + "($$); } finally { this." + field + ".unlock(); } }", "this", ctMethod.getName()); ctClass.addMethod(replacement); } @Patch ( requiredAttributes = "field" ) public void lockMethodCall(final CtBehavior ctBehavior, Map<String, String> attributes) throws CannotCompileException { String method_ = attributes.get("method"); if (method_ == null) { method_ = ""; } String className_ = null; int dotIndex = method_.indexOf('.'); if (dotIndex != -1) { className_ = method_.substring(0, dotIndex); method_ = method_.substring(dotIndex + 1); } String index_ = attributes.get("index"); if (index_ == null) { index_ = "-1"; } final String method = method_; final String className = className_; final String field = attributes.get("field"); final int index = Integer.valueOf(index_); ctBehavior.instrument(new ExprEditor() { private int currentIndex = 0; @Override public void edit(MethodCall methodCall) throws CannotCompileException { if ((className == null || methodCall.getClassName().equals(className)) && (method.isEmpty() || methodCall.getMethodName().equals(method)) && (index == -1 || currentIndex++ == index)) { Log.info("Replaced " + methodCall + " from " + ctBehavior); methodCall.replace("{ " + field + ".lock(); try { $_ = $proceed($$); } finally { " + field + ".unlock(); } }"); } } }); } @Patch ( requiredAttributes = "field" ) public void synchronizeMethodCall(final CtBehavior ctBehavior, Map<String, String> attributes) throws CannotCompileException { String method_ = attributes.get("method"); if (method_ == null) { method_ = ""; } String className_ = null; int dotIndex = method_.indexOf('.'); if (dotIndex != -1) { className_ = method_.substring(0, dotIndex); method_ = method_.substring(dotIndex + 1); } String index_ = attributes.get("index"); if (index_ == null) { index_ = "-1"; } final String method = method_; final String className = className_; final String field = attributes.get("field"); final int index = Integer.valueOf(index_); ctBehavior.instrument(new ExprEditor() { private int currentIndex = 0; @Override public void edit(MethodCall methodCall) throws CannotCompileException { if ((className == null || methodCall.getClassName().equals(className)) && (method.isEmpty() || methodCall.getMethodName().equals(method)) && (index == -1 || currentIndex++ == index)) { Log.info("Replaced " + methodCall + " from " + ctBehavior); methodCall.replace("synchronized(" + field + ") { $_ = $0.$proceed($$); }"); } } }); } @Patch ( emptyConstructor = false ) public void synchronize(Object o, Map<String, String> attributes) throws CannotCompileException { if (o instanceof CtMethod) { synchronize((CtMethod) o, attributes.get("field")); } else { boolean static_ = attributes.containsKey("static"); for (CtMethod ctMethod : ((CtClass) o).getDeclaredMethods()) { boolean isStatic = (ctMethod.getModifiers() & Modifier.STATIC) == Modifier.STATIC; if (isStatic == static_) { synchronize(ctMethod, attributes.get("field")); } } } } private void synchronize(CtMethod ctMethod, String field) throws CannotCompileException { if (field == null) { int currentModifiers = ctMethod.getModifiers(); if (Modifier.isSynchronized(currentModifiers)) { Log.warning("Method: " + ctMethod.getLongName() + " is already synchronized"); } else { ctMethod.setModifiers(currentModifiers | Modifier.SYNCHRONIZED); } } else { CtClass ctClass = ctMethod.getDeclaringClass(); CtMethod replacement = CtNewMethod.copy(ctMethod, ctClass, null); ctMethod.setName(ctMethod.getName() + "_nosynchronize"); replacement.setBody("synchronized(" + field + ") { return this." + ctMethod.getName() + "($$); }"); ctClass.addMethod(replacement); } } @Patch public void ignoreExceptions(CtMethod ctMethod, Map<String, String> attributes) throws CannotCompileException, NotFoundException { String returnCode = attributes.get("code"); if (returnCode == null) { returnCode = "return;"; } String exceptionType = attributes.get("type"); if (exceptionType == null) { exceptionType = "java.lang.Exception"; } Log.info("Ignoring " + exceptionType + " in " + ctMethod + ", returning with " + returnCode); ctMethod.addCatch("{ " + returnCode + '}', classRegistry.getClass(exceptionType)); } @Patch ( requiredAttributes = "class" ) public void addClass(CtClass ctClass, Map<String, String> attributes) throws IOException, CannotCompileException, NotFoundException { classRegistry.add(ctClass, attributes.get("class")); } @Patch public void replaceInstantiations(CtBehavior object, Map<String, String> attributes) { // TODO: Implement this, change some newInitializer patches to use this } public void replaceInstantiationsImplementation(CtBehavior ctBehavior, final Map<String, List<String>> replacementClasses) throws CannotCompileException { // TODO: Learn to use ASM, javassist isn't nice for some things. :( final Map<Integer, String> newExprType = new HashMap<Integer, String>(); ctBehavior.instrument(new ExprEditor() { NewExpr lastNewExpr; int newPos = 0; @Override public void edit(NewExpr e) { lastNewExpr = null; newPos++; if (replacementClasses.containsKey(e.getClassName())) { lastNewExpr = e; } } @Override public void edit(FieldAccess e) { NewExpr myLastNewExpr = lastNewExpr; lastNewExpr = null; if (myLastNewExpr != null) { Log.fine('(' + myLastNewExpr.getSignature() + ") " + myLastNewExpr.getClassName() + " at " + myLastNewExpr.getFileName() + ':' + myLastNewExpr.getLineNumber() + ':' + newPos); newExprType.put(newPos, classSignatureToName(e.getSignature())); } } @Override public void edit(MethodCall e) { lastNewExpr = null; } @Override public void edit(NewArray e) { lastNewExpr = null; } @Override public void edit(Cast e) { lastNewExpr = null; } @Override public void edit(Instanceof e) { lastNewExpr = null; } @Override public void edit(Handler e) { lastNewExpr = null; } @Override public void edit(ConstructorCall e) { lastNewExpr = null; } }); ctBehavior.instrument(new ExprEditor() { int newPos = 0; @Override public void edit(NewExpr e) throws CannotCompileException { newPos++; try { Log.fine(e.getFileName() + ':' + e.getLineNumber() + ", pos: " + newPos); if (newExprType.containsKey(newPos)) { String replacementType = null, assignedType = newExprType.get(newPos); Log.fine(assignedType + " at " + e.getFileName() + ':' + e.getLineNumber()); Class<?> assignTo = Class.forName(assignedType); for (String replacementClass : replacementClasses.get(e.getClassName())) { if (assignTo.isAssignableFrom(Class.forName(replacementClass))) { replacementType = replacementClass; break; } } if (replacementType == null) { return; } String block = "{$_=new " + replacementType + "($$);}"; Log.fine("Replaced with " + block + ", " + replacementType.length() + ':' + assignedType.length()); e.replace(block); } } catch (ClassNotFoundException el) { Log.severe("Could not replace instantiation, class not found.", el); } } }); } private static String classSignatureToName(String signature) { //noinspection HardcodedFileSeparator return signature.substring(1, signature.length() - 1).replace("/", "."); } }
import com.sun.star.awt.FontDescriptor; import com.sun.star.awt.XListBox; import com.sun.star.wizards.common.*; import java.util.*; /** * * @author bc93774 */ public class FieldSelection { public UnoDialog CurUnoDialog; public XListBox xFieldsListBox; public XListBox xSelFieldsListBox; public XFieldSelectionListener xFieldSelection; public int maxfieldcount = 10000000; public String sIncSuffix; protected Integer IStep; protected int FirstHelpIndex; protected short curtabindex; String[] AllFieldNames; public Integer ListBoxWidth; public Integer SelListBoxPosX; boolean bisModified = false; boolean AppendMode = false; final int SOCMDMOVESEL = 1; final int SOCMDMOVEALL = 2; final int SOCMDREMOVESEL = 3; final int SOCMDREMOVEALL = 4; final int SOCMDMOVEUP = 5; final int SOCMDMOVEDOWN = 6; final int SOFLDSLST = 7; final int SOSELFLDSLST = 8; final int cmdButtonWidth = 16; final int cmdButtonHoriDist = 4; final int cmdButtonHeight = 14; final int cmdButtonVertiDist = 2; final int lblHeight = 8; final int lblVertiDist = 2; int CompPosX; int CompPosY; int CompHeight; int CompWidth; class ItemListenerImpl implements com.sun.star.awt.XItemListener { public void itemStateChanged(com.sun.star.awt.ItemEvent EventObject) { int iPos; com.sun.star.wizards.common.Helper.setUnoPropertyValue(CurUnoDialog.xDialogModel, "Enabled", Boolean.FALSE); int iKey = CurUnoDialog.getControlKey(EventObject.Source, CurUnoDialog.ControlList); switch (iKey) { case SOFLDSLST : toggleListboxButtons((short) - 1, (short) - 1); break; case SOSELFLDSLST : toggleListboxButtons((short) - 1, (short) - 1); break; default : break; } com.sun.star.wizards.common.Helper.setUnoPropertyValue(CurUnoDialog.xDialogModel, "Enabled", Boolean.TRUE); } public void disposing(com.sun.star.lang.EventObject eventObject) { } } class ActionListenerImpl implements com.sun.star.awt.XActionListener { public void disposing(com.sun.star.lang.EventObject eventObject) { } public void actionPerformed(com.sun.star.awt.ActionEvent actionEvent) { try { int iKey = CurUnoDialog.getControlKey(actionEvent.Source, CurUnoDialog.ControlList); switch (iKey) { case SOFLDSLST : selectFields(false); break; case SOSELFLDSLST : deselectFields(false); break; case SOCMDMOVESEL : selectFields(false); break; case SOCMDMOVEALL : selectFields(true); break; case SOCMDREMOVESEL : deselectFields(false); break; case SOCMDREMOVEALL : deselectFields(true); break; case SOCMDMOVEUP : changeSelectionOrder(-1); break; case SOCMDMOVEDOWN : changeSelectionOrder(1); break; default : // System.err.println( exception); break; } } catch (Exception exception) { exception.printStackTrace(System.out); } } } public void addFieldSelectionListener(XFieldSelectionListener xFieldSelection) { this.xFieldSelection = xFieldSelection; this.xFieldSelection.setID(sIncSuffix); } public void setAppendMode(boolean _AppendMode) { AppendMode = _AppendMode; } public boolean getAppendMode() { return AppendMode; } public FieldSelection(UnoDialog CurUnoDialog, int iStep, int CompPosX, int CompPosY, int CompWidth, int CompHeight, String slblFields, String slblSelFields, int _FirstHelpIndex, boolean bshowFourButtons) { try { String AccessTextMoveSelected = CurUnoDialog.oResource.getResText(UIConsts.RID_DB_COMMON + 39); String AccessTextRemoveSelected = CurUnoDialog.oResource.getResText(UIConsts.RID_DB_COMMON + 40); String AccessTextMoveAll = CurUnoDialog.oResource.getResText(UIConsts.RID_DB_COMMON + 41); String AccessTextRemoveAll = CurUnoDialog.oResource.getResText(UIConsts.RID_DB_COMMON + 42); String AccessMoveFieldUp = CurUnoDialog.oResource.getResText(UIConsts.RID_DB_COMMON + 43); String AccessMoveFieldDown = CurUnoDialog.oResource.getResText(UIConsts.RID_DB_COMMON + 44); FirstHelpIndex = _FirstHelpIndex; curtabindex = UnoDialog.setInitialTabindex(iStep); int ShiftButtonCount = 2; int a = 0; this.CurUnoDialog = CurUnoDialog; this.CompPosX = CompPosX; this.CompPosY = CompPosY; this.CompHeight = CompHeight; this.CompWidth = CompWidth; Object btnmoveall = null; Object btnremoveall = null; ListBoxWidth = new Integer((int) ((CompWidth - 3 * cmdButtonHoriDist - 2 * cmdButtonWidth) / 2)); Integer cmdShiftButtonPosX = new Integer((int) (CompPosX + ListBoxWidth.intValue() + cmdButtonHoriDist)); Integer ListBoxPosY = new Integer(CompPosY + lblVertiDist + lblHeight); Integer ListBoxHeight = new Integer(CompHeight - 8 - 2); SelListBoxPosX = new Integer(cmdShiftButtonPosX.intValue() + cmdButtonWidth + cmdButtonHoriDist); IStep = new Integer(iStep); if (bshowFourButtons == true) { ShiftButtonCount = 4; } Integer[] ShiftButtonPosY = getYButtonPositions(ShiftButtonCount); Integer[] MoveButtonPosY = getYButtonPositions(2); Integer cmdMoveButtonPosX = new Integer(SelListBoxPosX.intValue() + ListBoxWidth.intValue() + cmdButtonHoriDist); Integer CmdButtonWidth = new Integer(cmdButtonWidth); sIncSuffix = "_" + com.sun.star.wizards.common.Desktop.getIncrementSuffix(CurUnoDialog.xDlgNameAccess, "lblFields_"); CurUnoDialog.insertControlModel("com.sun.star.awt.UnoControlFixedTextModel", "lblFields" + sIncSuffix, new String[] { "Height", "Label", "PositionX", "PositionY", "Step", "TabIndex", "Width" }, new Object[] { new Integer(8), slblFields, new Integer(CompPosX), new Integer(CompPosY), IStep, new Short(curtabindex), new Integer(109)}); xFieldsListBox = CurUnoDialog.insertListBox("lstFields" + sIncSuffix, SOFLDSLST, new ActionListenerImpl(), new ItemListenerImpl(), new String[] { "Height", "HelpURL", "MultiSelection", "PositionX", "PositionY", "Step", "TabIndex", "Width" }, new Object[] { ListBoxHeight, "HID:" + Integer.toString(_FirstHelpIndex++), Boolean.TRUE, new Integer(CompPosX), ListBoxPosY, IStep, new Short((curtabindex++)), ListBoxWidth }); Object btnmoveselected = CurUnoDialog.insertButton("cmdMoveSelected" + sIncSuffix, SOCMDMOVESEL, new ActionListenerImpl(), new String[] { "Enabled", "Height", "HelpURL", "Label", "PositionX", "PositionY", "Step", "TabIndex", "Width" }, new Object[] { Boolean.FALSE, new Integer(14), "HID:" + Integer.toString(_FirstHelpIndex++), ">", cmdShiftButtonPosX, ShiftButtonPosY[a++], IStep, new Short(curtabindex++), CmdButtonWidth }); if (bshowFourButtons == true) btnmoveall = CurUnoDialog.insertButton("cmdMoveAll" + sIncSuffix, SOCMDMOVEALL, new ActionListenerImpl(), new String[] { "Height", "HelpURL", "Label", "PositionX", "PositionY", "Step", "TabIndex", "Width" }, new Object[] { new Integer(14), "HID:" + Integer.toString(_FirstHelpIndex++), ">>", cmdShiftButtonPosX, ShiftButtonPosY[a++], IStep, new Short(curtabindex++), CmdButtonWidth }); Object btnremoveselected = CurUnoDialog.insertButton("cmdRemoveSelected" + sIncSuffix, SOCMDREMOVESEL, new ActionListenerImpl(), new String[] { "Enabled", "Height", "HelpURL", "Label", "PositionX", "PositionY", "Step", "TabIndex", "Width" }, new Object[] { Boolean.FALSE, new Integer(14), "HID:" + Integer.toString(_FirstHelpIndex++), "<", cmdShiftButtonPosX, ShiftButtonPosY[a++], IStep, new Short(curtabindex++), CmdButtonWidth }); if (bshowFourButtons == true) btnremoveall = CurUnoDialog.insertButton("cmdRemoveAll" + sIncSuffix, SOCMDREMOVEALL, new ActionListenerImpl(), new String[] { "Height", "HelpURL", "Label", "PositionX", "PositionY", "Step", "TabIndex", "Width" }, new Object[] { new Integer(14), "HID:" + Integer.toString(_FirstHelpIndex++), "<<", cmdShiftButtonPosX, ShiftButtonPosY[a++], IStep, new Short(curtabindex++), CmdButtonWidth }); FontDescriptor oFontDesc = new FontDescriptor(); oFontDesc.Name = "StarSymbol"; CurUnoDialog.insertControlModel("com.sun.star.awt.UnoControlFixedTextModel", "lblSelFields" + sIncSuffix, new String[] { "Height", "Label", "PositionX", "PositionY", "Step", "TabIndex", "Width" }, new Object[] { new Integer(8), slblSelFields, SelListBoxPosX, new Integer(CompPosY), IStep, new Short(curtabindex++), ListBoxWidth }); xSelFieldsListBox = CurUnoDialog.insertListBox("lstSelFields" + sIncSuffix, SOSELFLDSLST, new ActionListenerImpl(), new ItemListenerImpl(), new String[] { "Height", "HelpURL", "MultiSelection", "PositionX", "PositionY", "Step", "TabIndex", "Width" }, new Object[] { ListBoxHeight, "HID:" + Integer.toString(_FirstHelpIndex++), Boolean.TRUE, SelListBoxPosX, ListBoxPosY, IStep, new Short(curtabindex++), ListBoxWidth }); Object btnmoveup = CurUnoDialog.insertButton("cmdMoveUp" + sIncSuffix, SOCMDMOVEUP, new ActionListenerImpl(), new String[] { "Enabled", "FontDescriptor", "Height", "HelpURL", "Label", "PositionX", "PositionY", "Step", "TabIndex", "Width" }, new Object[] { Boolean.FALSE, oFontDesc, new Integer(14), "HID:" + Integer.toString(_FirstHelpIndex++), String.valueOf((char) 8743), cmdMoveButtonPosX, MoveButtonPosY[0], IStep, new Short(curtabindex++), CmdButtonWidth }); Object btnmovedown = CurUnoDialog.insertButton("cmdMoveDown" + sIncSuffix, SOCMDMOVEDOWN, new ActionListenerImpl(), new String[] { "Enabled", "FontDescriptor", "Height", "HelpURL", "Label", "PositionX", "PositionY", "Step", "TabIndex", "Width" }, new Object[] { Boolean.FALSE, oFontDesc, new Integer(14), "HID:" + Integer.toString(_FirstHelpIndex++), String.valueOf((char) 8744), cmdMoveButtonPosX, MoveButtonPosY[1], IStep, new Short(curtabindex++), CmdButtonWidth }); CurUnoDialog.getPeerConfiguration().setAccessiblityName(btnmoveselected, AccessTextMoveSelected); CurUnoDialog.getPeerConfiguration().setAccessiblityName(btnremoveselected, AccessTextMoveSelected); CurUnoDialog.getPeerConfiguration().setAccessiblityName(xFieldsListBox, JavaTools.replaceSubString(slblFields, "", "~")); CurUnoDialog.getPeerConfiguration().setAccessiblityName(xSelFieldsListBox, JavaTools.replaceSubString(slblSelFields, "", "~")); if (btnmoveall != null) CurUnoDialog.getPeerConfiguration().setAccessiblityName(btnmoveall, AccessTextMoveAll); if (btnremoveall != null) CurUnoDialog.getPeerConfiguration().setAccessiblityName(btnremoveall, AccessTextRemoveAll); if (btnmoveup != null) CurUnoDialog.getPeerConfiguration().setAccessiblityName(btnmoveup, AccessMoveFieldUp); if (btnmovedown != null) CurUnoDialog.getPeerConfiguration().setAccessiblityName(btnmovedown, AccessMoveFieldDown ); } catch (Exception exception) { exception.printStackTrace(System.out); } } // Todo: If Value is getting smaller than zero -> throw exception private Integer[] getYButtonPositions(int ButtonCount) { Integer[] YPosArray; if (ButtonCount > 0) { YPosArray = new Integer[ButtonCount]; YPosArray[0] = new Integer((int) (CompPosY + 10 + (((CompHeight - 10) - (ButtonCount * cmdButtonHeight) - ((ButtonCount - 1) * cmdButtonVertiDist)) / 2))); if (ButtonCount > 1) { for (int i = 1; i < ButtonCount; i++) { YPosArray[i] = new Integer(YPosArray[i - 1].intValue() + cmdButtonHeight + cmdButtonVertiDist); } } return YPosArray; } return null; } public Integer getListboxWidth() { return this.ListBoxWidth; } private void changeSelectionOrder(int iNeighbor) { short[] iSelIndices = xSelFieldsListBox.getSelectedItemsPos(); // Todo: we are assuming that the array starts with the lowest index. Verfy this assumption!!!!! if (iSelIndices.length == 1) { short iSelIndex = iSelIndices[0]; String[] NewItemList = xSelFieldsListBox.getItems(); String CurItem = NewItemList[iSelIndex]; String NeighborItem = NewItemList[iSelIndex + iNeighbor]; NewItemList[iSelIndex + iNeighbor] = CurItem; NewItemList[iSelIndex] = NeighborItem; CurUnoDialog.setControlProperty("lstSelFields" + sIncSuffix, "StringItemList", NewItemList); xSelFieldsListBox.selectItem(CurItem, true); if (xFieldSelection != null){ if (iNeighbor < 0) xFieldSelection.moveItemUp(CurItem); else xFieldSelection.moveItemDown(CurItem); } } } public void toggleListboxControls(Boolean BDoEnable) { try { CurUnoDialog.setControlProperty("lblFields" + sIncSuffix, "Enabled", BDoEnable); CurUnoDialog.setControlProperty("lblSelFields" + sIncSuffix, "Enabled", BDoEnable); CurUnoDialog.setControlProperty("lstFields" + sIncSuffix, "Enabled", BDoEnable); CurUnoDialog.setControlProperty("lstSelFields" + sIncSuffix, "Enabled", BDoEnable); if (BDoEnable.booleanValue() == true) toggleListboxButtons((short) - 1, (short) - 1); else { CurUnoDialog.setControlProperty("cmdRemoveAll" + sIncSuffix, "Enabled", BDoEnable); CurUnoDialog.setControlProperty("cmdRemoveSelected" + sIncSuffix, "Enabled", BDoEnable); toggleMoveButtons(BDoEnable.booleanValue(), BDoEnable.booleanValue()); } } catch (Exception exception) { exception.printStackTrace(System.out); } } // Enable or disable the buttons used for moving the available // fields between the two list boxes. private void toggleListboxButtons(short iFieldsSelIndex, short iSelFieldsSelIndex) { try { boolean bmoveUpenabled = false; boolean bmoveDownenabled = false; CurUnoDialog.selectListBoxItem(xFieldsListBox, iFieldsSelIndex); CurUnoDialog.selectListBoxItem(xSelFieldsListBox, iSelFieldsSelIndex); int SelListBoxSelLength = xSelFieldsListBox.getSelectedItems().length; int ListBoxSelLength = xFieldsListBox.getSelectedItems().length; boolean bIsFieldSelected = (ListBoxSelLength > 0); int FieldCount = xFieldsListBox.getItemCount(); boolean bSelectSelected = (SelListBoxSelLength > 0); int SelectCount = xSelFieldsListBox.getItemCount(); if (bSelectSelected) { short[] iSelIndices = xSelFieldsListBox.getSelectedItemsPos(); bmoveUpenabled = ((iSelIndices[0] > 0) && (iSelIndices.length == 1)); bmoveDownenabled = (((iSelIndices[SelListBoxSelLength - 1]) < (short) (SelectCount - 1)) && (iSelIndices.length == 1)); } CurUnoDialog.setControlProperty("cmdRemoveAll" + sIncSuffix, "Enabled", new Boolean(SelectCount >= 1)); CurUnoDialog.setControlProperty("cmdRemoveSelected" + sIncSuffix, "Enabled", new Boolean(bSelectSelected)); toggleMoveButtons((FieldCount >= 1), bIsFieldSelected); CurUnoDialog.setControlProperty("cmdMoveUp" + sIncSuffix, "Enabled", new Boolean(bmoveUpenabled)); CurUnoDialog.setControlProperty("cmdMoveDown" + sIncSuffix, "Enabled", new Boolean(bmoveDownenabled)); } catch (Exception exception) { exception.printStackTrace(System.out); } } private void toggleMoveButtons(boolean _btoggleMoveAll, boolean _btoggleMoveSelected) { boolean btoggleMoveAll = (((xFieldsListBox.getItemCount() + xSelFieldsListBox.getItemCount()) < maxfieldcount) && (_btoggleMoveAll)); boolean btoggleMoveSelected = (((xFieldsListBox.getSelectedItems().length + xSelFieldsListBox.getItemCount()) < maxfieldcount) && (_btoggleMoveSelected)); CurUnoDialog.setControlProperty("cmdMoveAll" + sIncSuffix, "Enabled", new Boolean(btoggleMoveAll)); CurUnoDialog.setControlProperty("cmdMoveSelected" + sIncSuffix, "Enabled", new Boolean(btoggleMoveSelected)); } public void setMultipleMode(boolean _bisMultiple) { xFieldsListBox.setMultipleMode(_bisMultiple); xSelFieldsListBox.setMultipleMode(_bisMultiple); } public void emptyFieldsListBoxes() { try { toggleListboxControls(Boolean.FALSE); CurUnoDialog.setControlProperty("lstSelFields" + sIncSuffix, "StringItemList", new String[]{}); CurUnoDialog.setControlProperty("lstFields" + sIncSuffix, "StringItemList", new String[]{}); } catch (Exception exception) { exception.printStackTrace(System.out); } } public void mergeList(String[] AllFieldNames, String[] SecondList) { int MaxIndex = SecondList.length; xFieldsListBox.addItems(AllFieldNames, (short) 0); toggleListboxButtons((short) - 1, (short) - 1); } public void intializeSelectedFields(String[] _SelectedFieldNames) { xSelFieldsListBox.addItems(_SelectedFieldNames, xSelFieldsListBox.getItemCount()); } // Note Boolean Parameter public void initialize(String[] _AllFieldNames, boolean _AppendMode) { AppendMode = _AppendMode; xFieldsListBox.removeItems((short) 0, xFieldsListBox.getItemCount()); xFieldsListBox.addItems(_AllFieldNames, (short) 0); this.AllFieldNames = xFieldsListBox.getItems(); if ((xSelFieldsListBox.getItemCount() > 0) && (!AppendMode)) xSelFieldsListBox.removeItems((short) 0, xSelFieldsListBox.getItemCount()); toggleListboxControls(Boolean.TRUE); } public void initialize(String[][] _AllFieldNamesTable, boolean _AppendMode, int _maxfieldcount) { String[] AllFieldNames = new String[_AllFieldNamesTable.length]; for (int i = 0; i < _AllFieldNamesTable.length; i++) AllFieldNames[i] = _AllFieldNamesTable[i][0]; initialize(AllFieldNames, _AppendMode, _maxfieldcount); } public void initialize(String[] _AllFieldNames, boolean _AppendMode, int _maxfieldcount) { maxfieldcount = _maxfieldcount; initialize(_AllFieldNames, _AppendMode); } public void initialize(String[] _AllFieldNames, String[] _SelFieldNames, boolean _AppendMode){ xSelFieldsListBox.removeItems((short) 0, xSelFieldsListBox.getItemCount()); xSelFieldsListBox.addItems(_SelFieldNames, (short) 0); initialize( _AllFieldNames,_AppendMode); } public void selectFields(boolean bMoveAll) { int CurIndex; short iFieldSelected = (short) - 1; short iSelFieldSelected = (short) - 1; int MaxCurTarget = xSelFieldsListBox.getItemCount(); String[] SelFieldItems; if (bMoveAll) { SelFieldItems = xFieldsListBox.getItems(); xFieldsListBox.removeItems((short) 0, xFieldsListBox.getItemCount()); if (!AppendMode){ xSelFieldsListBox.removeItems((short) 0, xSelFieldsListBox.getItemCount()); xSelFieldsListBox.addItems(AllFieldNames, (short) 0); } else xSelFieldsListBox.addItems(SelFieldItems, xSelFieldsListBox.getItemCount()); } else { SelFieldItems = xFieldsListBox.getSelectedItems(); int MaxSourceSelected = SelFieldItems.length; if (MaxSourceSelected > 0) { iFieldSelected = xFieldsListBox.getSelectedItemPos(); iSelFieldSelected = xSelFieldsListBox.getSelectedItemPos(); short[] SourceSelList = new short[xFieldsListBox.getSelectedItemsPos().length]; SourceSelList = xFieldsListBox.getSelectedItemsPos(); xSelFieldsListBox.addItems(SelFieldItems, xSelFieldsListBox.getItemCount()); CurUnoDialog.removeSelectedItems(xFieldsListBox); xSelFieldsListBox.selectItemPos((short) 0, xSelFieldsListBox.getSelectedItems().length > 0); } } toggleListboxButtons(iFieldSelected, iSelFieldSelected); if (xFieldSelection != null) xFieldSelection.shiftFromLeftToRight(SelFieldItems, xSelFieldsListBox.getItems()); } public void deselectFields(boolean bMoveAll) { int m = 0; String SearchString; short iOldFieldSelected = xFieldsListBox.getSelectedItemPos(); short iOldSelFieldSelected = xSelFieldsListBox.getSelectedItemPos(); String[] OldSelFieldItems = xSelFieldsListBox.getSelectedItems(); if (bMoveAll) { OldSelFieldItems = xSelFieldsListBox.getItems(); xFieldsListBox.removeItems((short) 0, xFieldsListBox.getItemCount()); xFieldsListBox.addItems(AllFieldNames, (short) 0); xSelFieldsListBox.removeItems((short) 0, xSelFieldsListBox.getItemCount()); } else { int MaxOriginalCount = AllFieldNames.length; int MaxSelected = OldSelFieldItems.length; String[] SelList = xFieldsListBox.getItems(); Vector NewSourceVector = new Vector(); for (int i = 0; i < MaxOriginalCount; i++) { SearchString = AllFieldNames[i]; if (JavaTools.FieldInList(SelList, SearchString) != -1) NewSourceVector.addElement(SearchString); else if (JavaTools.FieldInList(OldSelFieldItems, SearchString) != -1) NewSourceVector.addElement(SearchString); } xFieldsListBox.removeItems((short) 0, xFieldsListBox.getItemCount()); if (NewSourceVector.size() > 0) { String[] NewSourceList = new String[NewSourceVector.size()]; NewSourceVector.toArray(NewSourceList); xFieldsListBox.addItems(NewSourceList, (short) 0); } CurUnoDialog.removeSelectedItems(xSelFieldsListBox); } toggleListboxButtons(iOldFieldSelected, iOldSelFieldSelected); String[] NewSelFieldItems = xSelFieldsListBox.getItems(); if (xFieldSelection != null) xFieldSelection.shiftFromRightToLeft(OldSelFieldItems, NewSelFieldItems); } public String[] getSelectedFieldNames() { return (String[]) CurUnoDialog.getControlProperty("lstSelFields" + sIncSuffix, "StringItemList"); } public void setSelectedFieldNames(String[] _sfieldnames){ CurUnoDialog.setControlProperty("lstSelFields" + sIncSuffix, "StringItemList", _sfieldnames); String[] sleftboxfieldnames = JavaTools.removefromList(xFieldsListBox.getItems(), _sfieldnames); CurUnoDialog.setControlProperty("lstFields" + sIncSuffix, "StringItemList", sleftboxfieldnames); } public void setModified(boolean _bModified){ bisModified = _bModified; } public boolean isModified(){ return bisModified; } }
package com.hotmail.kalebmarc.textfighter.main; import com.hotmail.kalebmarc.textfighter.player.Achievements; import com.hotmail.kalebmarc.textfighter.player.Coins; import com.hotmail.kalebmarc.textfighter.player.Stats; import com.hotmail.kalebmarc.textfighter.player.Xp; import javax.swing.*; import java.util.ArrayList; public class Weapon { //Weapon List public static final ArrayList<Weapon> arrayWeapon = new ArrayList<>(); //Properties public static int BULLET_DAMAGE; //Variables public static Weapon starting; private static Weapon current = null; public int price; public int level; public boolean melee; public boolean owns; private int damageMin; private int damageMax; private int damageDealt; private double chanceOfMissing; private String name; private boolean buyable; //Ammo private int ammo; private int ammoUsed; private int ammoPrice;//Per 1 private int ammoIncludedWithPurchase; public Weapon(String name, int ammoUsed, int ammoIncludedWithPurchase, boolean buyable, int price, //For guns int ammoPrice, int level, double chanceOfMissing, boolean firstInit, boolean changeDif) { this.name = name; this.ammoUsed = ammoUsed; this.ammoIncludedWithPurchase = ammoIncludedWithPurchase; this.buyable = buyable; this.price = price; this.ammoPrice = ammoPrice; this.level = level; this.chanceOfMissing = chanceOfMissing; this.melee = false; if (!changeDif) { arrayWeapon.add(this); } if (firstInit) { this.owns = false; } } public Weapon(String name, boolean startingWeapon, boolean buyable, int price, int level,//For Melee int damageMin, int damageMax, boolean firstInit, boolean changeDif) { this.name = name; this.buyable = buyable; this.price = price; this.level = level; this.damageMin = damageMin; this.damageMax = damageMax; this.melee = true; if (!changeDif) { arrayWeapon.add(this); } if (firstInit) { if (startingWeapon) {//If first init, see if player starts with this or not. this.owns = true; current = this; starting = this; } else { this.owns = false; } } } public static Weapon get() { return current; } static int getIndex(Weapon i) { return arrayWeapon.indexOf(i); } public static void set(Weapon x) { current = x; } public static void set(int i) { current = arrayWeapon.get(i); } public static void choose() { while (true) { Ui.cls(); Ui.println(" Ui.println("Equip new weapon"); Ui.println(); Ui.println("Ammo: " + current.getAmmo()); Ui.println("Equipped weapon: " + current.getName()); Ui.println(" int j = 0; int[] offset = new int[arrayWeapon.size()]; for (int i = 0; i < arrayWeapon.size(); i++) { if (arrayWeapon.get(i).owns()) { Ui.println((j + 1) + ") " + arrayWeapon.get(i).getName()); offset[j] = i - j; j++; } } Ui.println((j + 1) + ") Back"); while (true) { int menuItem = Ui.getValidInt(); try { //choices other than options in the array go here: if (menuItem == (j + 1) || menuItem > j) return; //reverts back to Weapon indexing menuItem menuItem = menuItem + offset[menuItem]; //Testing to make sure the option is valid goes here: if (!arrayWeapon.get(menuItem).owns) { Ui.msg("You do not own this weapon!"); return; } current = arrayWeapon.get(menuItem); Ui.msg("You have equipped a " + arrayWeapon.get(menuItem).getName()); return; } catch (Exception e) { Ui.println(); Ui.println(menuItem + " is not an option."); } } } } private static void noAmmo() { Ui.popup("You've run out of ammo!", "Warning", JOptionPane.WARNING_MESSAGE); Weapon.current = Weapon.starting; } public static void displayAmmo() { if (!(Weapon.get().melee)) { Ui.println(" Ammo: " + Weapon.get().getAmmo()); } } public String getName() { return name; } public boolean owns() { return owns; } public void setAmmo(int amount, boolean add) { if (this.melee) return; if (add) { this.ammo += amount; } else { this.ammo = amount; } } public int getAmmo() { return this.ammo; } public void dealDam() { if (this.melee) { /* * Melee Attack */ damageDealt = Random.RInt(this.damageMin, this.damageMax); } else { /* * Gun Attack */ if (getAmmo() >= this.ammoUsed) { for (int i = 1; i <= this.ammoUsed; i++) { if (Random.RInt(100) > this.chanceOfMissing) { damageDealt += BULLET_DAMAGE; Stats.bulletsThatHit++; } //Results setAmmo(-1, true); Stats.bulletsFired += 1; } criticalHit(); } else { noAmmo(); damageDealt = 0; } } //Make damageDealt available in Enemy.java Enemy.get().returnDamage(damageDealt); //Display stuff com.hotmail.kalebmarc.textfighter.player.Stats.totalDamageDealt += damageDealt; com.hotmail.kalebmarc.textfighter.player.Xp.setBattleXp(damageDealt, true); if(!Enemy.get().takeDamage(damageDealt)) { // !dead Ui.cls(); Ui.println(" Ui.println("You have attacked a " + Enemy.get().getName() + "!"); Ui.println("You dealt " + damageDealt + " damage with a " + this.name); Ui.println(" Ui.println("Your health: " + com.hotmail.kalebmarc.textfighter.player.Health.getStr()); Ui.println("Enemy health: " + Enemy.get().getHeathStr()); Ui.println(" Ui.pause(); if (Enemy.get().getHealth() <= Enemy.get().getHealthMax() / 3){ Enemy.get().useFirstAidKit(); } } damageDealt = 0; } public void criticalHit() { if (Random.RInt(100) == 1) { int critMultiplier = Random.RInt(5, 10); damageDealt *= critMultiplier; Ui.cls(); Ui.println(" Ui.println("Critical Hit!"); Ui.println("You dealt " + critMultiplier + "x normal damage."); Ui.println(" Ui.pause(); } } public void viewAbout() { final int BORDER_LENGTH = 39; //Start of weapon Info Ui.cls(); for (int i = 0; i < BORDER_LENGTH; i++) Ui.print("-");//Make line Ui.println(); for (int i = 0; i < ((BORDER_LENGTH / 2) - (this.getName().length() / 2)); i++) Ui.print(" ");//Set correct spacing to get name in middle of box Ui.println(this.getName()); Ui.println("Price: " + this.price + " coins"); Ui.println("Chance of missing: " + this.chanceOfMissing + "%"); Ui.println("Ammo Used: " + this.ammoUsed); Ui.println("Damage: " + this.getDamage()); for (int i = 0; i < BORDER_LENGTH; i++) Ui.print("-");//Make line Ui.pause(); Ui.cls(); //End of weapon Info } private String getDamage() { if (this.melee) { return (this.damageMin + " - " + this.damageMax); } else { if (this.chanceOfMissing == 0) { return String.valueOf((BULLET_DAMAGE * this.ammoUsed)); } else { return ("0 - " + String.valueOf((BULLET_DAMAGE * this.ammoUsed))); } } } public boolean isBuyable() { return this.buyable; } public void buy() { if (!isBuyable()) { Ui.msg("Sorry, this item is no longer in stock."); return; } if (this.owns()) { Ui.msg("You already own this weapon."); return; } if (level > Xp.getLevel()) { Ui.msg("You are not a high enough level to buy this item."); return; } if (price > Coins.get()) { Ui.msg("You do not have enough coins to buy this item."); return; } //Buy Achievements.boughtItem = true; Coins.set(-price, true); Stats.coinsSpentOnWeapons += price; this.owns = true; current = this; Ui.println("You have bought a " + this.getName() + " for " + this.price + " coins."); Ui.println("Coins: " + Coins.get()); Ui.pause(); //Give ammo ammo += this.ammoIncludedWithPurchase; } public void buyAmmo() { Ui.cls(); //Make sure player is a high enough level if (Xp.getLevel() < this.level) { Ui.println("You are not a high enough level. You need to be at least level " + this.level + "."); Ui.pause(); return; } //Get amount of ammo user wants Ui.println("How much ammo would you like to buy?"); Ui.println("1 ammo cost " + this.ammoPrice + " coins."); Ui.println("You have " + Coins.get() + " coins."); int ammoToBuy = Ui.getValidInt(); int cost = ammoToBuy * ammoPrice; //Make sure player has enough coins if (Coins.get() < (cost)) { Ui.println("You don't have enough coins. You need " + (cost - Coins.get()) + " more coins."); Ui.pause(); return; } this.ammo += ammoToBuy; Coins.set(-cost, true); Stats.coinsSpentOnWeapons += cost; Ui.println("You have bought " + ammoToBuy + " ammo."); Ui.pause(); } public int getAmmoPrice() { return this.ammoPrice; } }
package org.intermine.dataloader; import org.intermine.dataconversion.DataConverterStoreHook; /** * Loads information from a data source into the InterMine database. * This class defines a member variable referencing an IntegrationWriter, which all DataLoaders * require. * * @author Matthew Wakeling * @author Richard Smith */ public abstract class DataLoader { private IntegrationWriter iw; private DataConverterStoreHook storeHook; /** * No-arg constructor for testing purposes */ private DataLoader() { // empty } /** * Set a hook for this converter that will be called just before each Item is stored. * The processItem() method in DataConverterStoreHook will be passed the Item, which * it can modify. * @param dataConverterStoreHook the hook */ public void setStoreHook(DataConverterStoreHook dataConverterStoreHook) { this.storeHook = dataConverterStoreHook; } /** * Construct a DataLoader * * @param iw an IntegrationWriter to write to */ public DataLoader(IntegrationWriter iw) { this.iw = iw; } /** * Return the IntegrationWriter that was passed to the constructor. * @return the IntegrationWriter */ public IntegrationWriter getIntegrationWriter() { return iw; } }
package com.iskrembilen.quasseldroid.gui; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ExpandableListActivity; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Build; import android.os.Bundle; import android.os.IBinder; import android.os.ResultReceiver; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.PagerTabStrip; import android.support.v4.view.ViewPager; import android.util.Log; import android.util.TypedValue; import android.view.ActionMode; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ArrayAdapter; import android.widget.BaseExpandableListAdapter; import android.widget.EditText; import android.widget.ExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.ExpandableListView.ExpandableListContextMenuInfo; import android.widget.ExpandableListView.OnChildClickListener; import android.widget.ExpandableListView.OnGroupCollapseListener; import android.widget.ExpandableListView.OnGroupExpandListener; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.iskrembilen.quasseldroid.Buffer; import com.iskrembilen.quasseldroid.BufferInfo; import com.iskrembilen.quasseldroid.BufferUtils; import com.iskrembilen.quasseldroid.Network; import com.iskrembilen.quasseldroid.NetworkCollection; import com.iskrembilen.quasseldroid.Quasseldroid; import com.iskrembilen.quasseldroid.R; import com.iskrembilen.quasseldroid.events.BufferOpenedEvent; import com.iskrembilen.quasseldroid.events.ConnectionChangedEvent; import com.iskrembilen.quasseldroid.events.ConnectionChangedEvent.Status; import com.iskrembilen.quasseldroid.events.CompleteNickEvent; import com.iskrembilen.quasseldroid.events.DisconnectCoreEvent; import com.iskrembilen.quasseldroid.events.InitProgressEvent; import com.iskrembilen.quasseldroid.events.LatencyChangedEvent; import com.iskrembilen.quasseldroid.events.UpdateReadBufferEvent; import com.iskrembilen.quasseldroid.gui.MainActivity.FragmentAdapter; import com.iskrembilen.quasseldroid.gui.fragments.BufferFragment; import com.iskrembilen.quasseldroid.gui.fragments.ChatFragment; import com.iskrembilen.quasseldroid.gui.fragments.ConnectingFragment; import com.iskrembilen.quasseldroid.gui.fragments.NickListFragment; import com.iskrembilen.quasseldroid.service.CoreConnService; import com.iskrembilen.quasseldroid.util.BusProvider; import com.iskrembilen.quasseldroid.util.Helper; import com.iskrembilen.quasseldroid.util.ThemeUtil; import com.squareup.otto.Bus; import com.squareup.otto.Produce; import com.squareup.otto.Subscribe; import java.util.GregorianCalendar; import java.util.Observable; import java.util.Observer; public class MainActivity extends SherlockFragmentActivity { private static final String TAG = MainActivity.class.getSimpleName(); public static final String BUFFER_ID_EXTRA = "bufferid"; public static final String BUFFER_NAME_EXTRA = "buffername"; private static final long BACK_THRESHOLD = 4000; SharedPreferences preferences; OnSharedPreferenceChangeListener sharedPreferenceChangeListener; private int currentTheme; private Boolean showLag = false; private ViewPager pager; private int openedBuffer = -1; private long lastBackPressed = 0; private FragmentAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { setTheme(ThemeUtil.theme); super.onCreate(savedInstanceState); currentTheme = ThemeUtil.theme; setContentView(R.layout.main_layout); adapter = new FragmentAdapter(getSupportFragmentManager()); pager = (ViewPager) findViewById(R.id.pager); pager.setOffscreenPageLimit(2); PagerTabStrip pagerIndicator = (PagerTabStrip) findViewById(R.id.pagerIndicator); pagerIndicator.setDrawFullUnderline(false); pagerIndicator.setTextColor(getResources().getColor(R.color.pager_indicator_text_color)); pagerIndicator.setTabIndicatorColor(getResources().getColor(R.color.pager_indicator_color)); pager.setOnPageChangeListener(adapter); pager.setAdapter(adapter); preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); showLag = preferences.getBoolean(getString(R.string.preference_show_lag), false); sharedPreferenceChangeListener =new OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if(key.equals(getResources().getString(R.string.preference_show_lag))){ showLag = preferences.getBoolean(getString(R.string.preference_show_lag), false); if(!showLag) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { setActionBarSubtitle(""); } else { setTitle(getResources().getString(R.string.app_name)); } } } } }; preferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); //To avoid GC issues if (savedInstanceState != null) { setBuffer(savedInstanceState.getInt("bufferid", -1)); } } private void setActionBarSubtitle(String subtitle) { getSupportActionBar().setSubtitle(subtitle); } @Override protected void onStart() { super.onStart(); if(ThemeUtil.theme != currentTheme) { Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } } @Override protected void onResume() { super.onResume(); BusProvider.getInstance().register(this); if(!Quasseldroid.connected) { returnToLogin(); } } @Override protected void onPause() { super.onPause(); BusProvider.getInstance().unregister(this); } @Override protected void onDestroy() { preferences.unregisterOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); super.onDestroy(); } @Override public void onBackPressed() { long currentTime = System.currentTimeMillis(); if(currentTime - lastBackPressed < BACK_THRESHOLD) super.onBackPressed(); else { Toast.makeText(this, getString(R.string.pressed_back_toast), Toast.LENGTH_SHORT).show(); lastBackPressed = currentTime; } } @Override public boolean onSearchRequested() { if(pager.getCurrentItem() == 1) { BusProvider.getInstance().post(new CompleteNickEvent()); return false; //Activity ate the request } return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { getSupportMenuInflater().inflate(R.menu.base_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_preferences: Intent i = new Intent(MainActivity.this, PreferenceView.class); startActivity(i); return true; case R.id.menu_disconnect: BusProvider.getInstance().post(new DisconnectCoreEvent()); startActivity(new Intent(this, LoginActivity.class)); finish(); return true; } return super.onOptionsItemSelected(item); } public class FragmentAdapter extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener { public static final int BUFFERS_POS = 0; public static final int CHAT_POS = 1; public static final int NICKS_POS = 2; public static final int PAGE_COUNT = 3; public boolean chatShown = false; public FragmentAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { switch (position) { case BUFFERS_POS: return BufferFragment.newInstance(); case CHAT_POS: return ChatFragment.newInstance(); case NICKS_POS: return NickListFragment.newInstance(); default: return null; } } @Override public int getCount() { if (chatShown) return PAGE_COUNT; else return 1; } @Override public CharSequence getPageTitle(int position) { switch (position) { case BUFFERS_POS: return "Channels"; case CHAT_POS: return "Chat"; case NICKS_POS: return "Nicks"; default: return super.getPageTitle(position); } } @Override public void onPageScrollStateChanged(int state) { // TODO Auto-generated method stub } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // TODO Auto-generated method stub } @Override public void onPageSelected(int position) { if(position == BUFFERS_POS) { BusProvider.getInstance().post(new UpdateReadBufferEvent()); } InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(pager.getWindowToken(), 0); } } @Subscribe public void onInitProgressed(InitProgressEvent event) { FragmentManager manager = getSupportFragmentManager(); if(event.done) { if(manager.findFragmentById(R.id.connecting_fragment_container) != null) { FragmentTransaction trans = manager.beginTransaction(); trans.remove(manager.findFragmentById(R.id.connecting_fragment_container)); trans.commit(); pager.setVisibility(View.VISIBLE); findViewById(R.id.connecting_fragment_container).setVisibility(View.GONE); //Doing this seems to fix a bug where menu items doesn't show up in the actionbar pager.setCurrentItem(FragmentAdapter.BUFFERS_POS); } } else { if(manager.findFragmentById(R.id.connecting_fragment_container) == null) { findViewById(R.id.connecting_fragment_container).setVisibility(View.VISIBLE); pager.setVisibility(View.GONE); FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); ConnectingFragment fragment = ConnectingFragment.newInstance(); fragmentTransaction.add(R.id.connecting_fragment_container, fragment, "connect"); fragmentTransaction.commit(); } } } @Subscribe public void onLatencyChanged(LatencyChangedEvent event) { if(showLag) { if (event.latency > 0) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { setActionBarSubtitle(Helper.formatLatency(event.latency, getResources())); } else { setTitle(getResources().getString(R.string.app_name) + " - " + Helper.formatLatency(event.latency, getResources())); } } } } @Subscribe public void onConnectionChanged(ConnectionChangedEvent event) { if(event.status == Status.Disconnected) { if(event.reason != "") { removeDialog(R.id.DIALOG_CONNECTING); Toast.makeText(MainActivity.this.getApplicationContext(), event.reason, Toast.LENGTH_LONG).show(); } returnToLogin(); } } private void returnToLogin() { finish(); Intent intent = new Intent(MainActivity.this, LoginActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } @Subscribe public void onBufferOpened(BufferOpenedEvent event) { setBuffer(event.bufferId); } private void setBuffer(int id) { if(id != -1) { adapter.chatShown = true; openedBuffer = id; setTitle(NetworkCollection.getInstance().getBufferById(id).getInfo().name); pager.setCurrentItem(FragmentAdapter.CHAT_POS, false); //using false here solved a problem with lables not showing up } } @Produce public BufferOpenedEvent produceBufferOpenedEvent() { return new BufferOpenedEvent(openedBuffer); } @Override protected void onSaveInstanceState (Bundle outState) { outState.putInt("bufferid", openedBuffer); } }
package org.intermine.web.struts; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import org.intermine.objectstore.query.BagConstraint; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.objectstore.query.ConstraintSet; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QueryClass; import org.intermine.objectstore.query.QueryExpression; import org.intermine.objectstore.query.QueryField; import org.intermine.objectstore.query.QueryFunction; import org.intermine.objectstore.query.QueryValue; import org.intermine.objectstore.query.Results; import org.intermine.objectstore.query.ResultsRow; import org.intermine.objectstore.query.SimpleConstraint; import org.intermine.metadata.AttributeDescriptor; import org.intermine.metadata.ClassDescriptor; import org.intermine.metadata.FieldDescriptor; import org.intermine.metadata.Model; import org.intermine.objectstore.ObjectStore; import org.intermine.web.logic.ClassKeyHelper; import org.intermine.web.logic.Constants; import org.intermine.web.logic.WebUtil; import org.intermine.web.logic.bag.InterMineBag; import org.intermine.web.logic.profile.Profile; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; /** * Action to search a list for an identifier and then highlight it on the list details page. * @author Kim Rutherford */ public class FindInListAction extends InterMineAction { /** * Method called when user has submitted the search form. * * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @return an ActionForward object defining where control goes next * @exception Exception if the application business logic throws * an exception */ @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, @SuppressWarnings("unused") HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); ServletContext context = session.getServletContext(); FindInListForm qsf = (FindInListForm) form; String textToFind = qsf.getTextToFind().trim(); String bagName = qsf.getBagName(); Profile profile = ((Profile) session.getAttribute(Constants.PROFILE)); Map<String, InterMineBag> allBags = WebUtil.getAllBags(profile.getSavedBags(), context); InterMineBag bag = allBags.get(bagName); ForwardParameters forwardParameters = new ForwardParameters(mapping.findForward("bagDetails")); forwardParameters.addParameter("name", bagName); if (bag != null) { Map<String, List<FieldDescriptor>> classKeys = (Map<String, List<FieldDescriptor>>) context.getAttribute(Constants.CLASS_KEYS); ObjectStore os = (ObjectStore) context.getAttribute(Constants.OBJECTSTORE); String bagQualifiedType = bag.getQualifiedType(); Collection<String> keyFields = ClassKeyHelper.getKeyFieldNames(classKeys, bagQualifiedType); int foundId = -1; if (keyFields.size() > 0) { Query q = makeQuery(textToFind, bag, keyFields); foundId = findFirst(os, q); } if (foundId == -1) { // no class key fields match so try all keys List<String> allStringFields = getStringFields(os, bagQualifiedType); Query q = makeQuery(textToFind, bag, allStringFields); foundId = findFirst(os, q); } if (foundId != -1) { forwardParameters.addParameter("highlightId", foundId + ""); forwardParameters.addParameter("gotoHighlighted", "true"); } } return forwardParameters.forward(); } private List<String> getStringFields(ObjectStore os, String bagQualifiedType) { List<String> retList = new ArrayList<String>(); Model model = os.getModel(); ClassDescriptor cd = model.getClassDescriptorByName(bagQualifiedType); for (AttributeDescriptor ad: cd.getAllAttributeDescriptors()) { if (ad.getType().equals(String.class.getName())) { retList.add(ad.getName()); } } return retList; } private Query makeQuery(String searchTerm, InterMineBag bag, Collection<String> identifierFieldNames) { Object lowerSearchTerm = searchTerm.toLowerCase(); Query q = new Query(); QueryClass qc; try { qc = new QueryClass(Class.forName(bag.getQualifiedType())); } catch (ClassNotFoundException e) { throw new RuntimeException("class not found", e); } QueryField idQF = new QueryField(qc, "id"); ConstraintSet cs = new ConstraintSet(ConstraintOp.AND); q.addFrom(qc); q.addToSelect(idQF); BagConstraint bagConstraint = new BagConstraint(idQF, ConstraintOp.IN, bag.getOsb()); cs.addConstraint(bagConstraint); ConstraintSet fieldCS = new ConstraintSet(ConstraintOp.OR); for (String fieldName: identifierFieldNames) { QueryField qf = new QueryField(qc, fieldName); QueryExpression lowerQF = new QueryExpression(QueryExpression.LOWER, qf); SimpleConstraint sc = new SimpleConstraint(lowerQF, ConstraintOp.EQUALS, new QueryValue(lowerSearchTerm)); fieldCS.addConstraint(sc); } cs.addConstraint(fieldCS); q.setConstraint(cs); return q; } /** * Return the id of the first object in the output, or -1 if there aren't any rows. */ private int findFirst(ObjectStore os, Query q) { Results res = os.execute(q); try { return (Integer) ((ResultsRow) res.get(0)).get(0); } catch (IndexOutOfBoundsException e) { return -1; } } }
package com.jcw.andriod.fileListView; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.widget.ImageView; import com.jcw.android.fileListView.R; import java.io.File; class PictureGenerator { File file; FileExtension extension; public static final int ICON_SIZE = 64; public PictureGenerator(File file) { this.file = file; extension = FileExtension.createExtension(getExtension()); } /* * you should avoid calling this * on the main thread -- it will * get very expensive very fast * because it loads the whole * picture into memory then trims * it. */ public Bitmap getIcon(Context context) { return extension.getIcon(context, this.file); } /* * This MUST be called within a thread */ protected void addIconAsync(final ImageView view) { Thread thread = new Thread(new Runnable() { @Override public void run() { final Bitmap icon = getIcon(view.getContext()); Runnable setImageRunnable = new Runnable() { @Override public void run() { if (icon == null) { //the icon was not loaded here view.setImageResource(R.drawable.file_icon); } else { view.setImageBitmap(icon); } } }; try { view.getHandler().post(setImageRunnable); } catch (Exception e) { //this is really trying to catch a dead object //exception, which means that the view is already destroyed view.post(setImageRunnable); } } }); thread.start(); } /* * This adds images to a series of views in * async fashion. */ public static void addIconsAsync(final FileListItemView[] items) { Thread runnable = new Thread(new Runnable() { @Override public void run() { for (FileListItemView view : items) { PictureGenerator generator = new PictureGenerator(view.getFullFile()); generator.addIconAsync(view.icon); } } }); } private String getExtension() { String[] delimited = file.getName().split("\\."); if (delimited.length == 0) { return ""; } else { return delimited[delimited.length - 1].toLowerCase(); } } private enum FileExtension { //IMPORTANT NOTE //if you add something here, you also have to add it to the //getIcon and createExtension methods JPG(".jpg"), PNG(".png"), MP3(".MP3"), MP4(".MP4"), AVI(".AVI"), FLV(".FLV"), MOV(".MOV"), Other(""); protected String extension; FileExtension(String extension) { this.extension = extension; } /* * returns a bitmap in 64x64 format * of the passed picture */ public Bitmap getIcon(Context context, File file) { switch (this) { case PNG: case JPG: return getPictureIcon(file); case MP3: return getPictureFromResource(context, R.drawable.mp3_icon); case Other: return null; } return null; } private Bitmap getPictureFromResource(Context context, int resId) { return BitmapFactory.decodeResource(context.getResources(), resId); } /* This method is synchronized as many calls can be generated to it * from a single view. (All in parallel) If that is done, then * we don't want to run out of memory loading a gazillion of these * bitmaps into memory. */ private synchronized Bitmap getPictureIcon(File file) { try { BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; Bitmap fullSized = BitmapFactory.decodeFile(file.toString(), options); Bitmap resized = Bitmap.createScaledBitmap(fullSized, 64, 64, true); fullSized.recycle(); return resized; } catch (Exception e) { //This can happen if there is an improperly formatted png/jpg file //i.e. if someone changed the extension of a file name by accident return null; } } public static FileExtension createExtension(String extension) { String s = extension.toLowerCase(); if (s.equals("jpg")) { return JPG; } else if (s.equals("png")) { return PNG; } else if (s.equals("mp3")) { return MP3; } else { return Other; } } } }
package org.intermine.web.struts; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.Map.Entry; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.intermine.api.InterMineAPI; import org.intermine.api.profile.TagManager; import org.intermine.api.tag.AspectTagUtil; import org.intermine.api.tag.TagNames; import org.intermine.metadata.ClassDescriptor; import org.intermine.metadata.FieldDescriptor; import org.intermine.model.InterMineObject; import org.intermine.model.userprofile.Tag; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreException; import org.intermine.api.template.TemplateManager; import org.intermine.web.displayer.ReportDisplayer; import org.intermine.web.logic.PortalHelper; import org.intermine.web.logic.config.InlineList; import org.intermine.web.logic.results.DisplayCollection; import org.intermine.web.logic.results.DisplayField; import org.intermine.web.logic.results.DisplayReference; import org.intermine.web.logic.results.ReportObject; import org.intermine.web.logic.results.ReportObjectFactory; import org.intermine.web.logic.session.SessionMethods; import org.jfree.util.Log; /** * New objectDetails. * * @author Radek Stepan */ public class ReportController extends InterMineAction { private static final Logger LOG = Logger.getLogger(ReportController.class); /** * {@inheritDoc} */ @Override public ActionForward execute(@SuppressWarnings("unused") ActionMapping mapping, @SuppressWarnings("unused") ActionForm form, HttpServletRequest request, @SuppressWarnings("unused") HttpServletResponse response) throws Exception { long startTime = System.currentTimeMillis(); HttpSession session = request.getSession(); InterMineAPI im = SessionMethods.getInterMineAPI(session); if (im.getBagManager().isAnyBagToUpgrade(SessionMethods.getProfile(session))) { recordError(new ActionMessage("login.upgradeListManually"), request); } // fetch & set requested object InterMineObject requestedObject = getRequestedObject(im, request); if (requestedObject != null) { ReportObjectFactory reportObjectFactory = SessionMethods.getReportObjects(session); ReportObject reportObject = reportObjectFactory.get(requestedObject); request.setAttribute("object", reportObject); request.setAttribute("reportObject", reportObject); request.setAttribute("requestedObject", requestedObject); // hell starts here TagManager tagManager = im.getTagManager(); ServletContext servletContext = session.getServletContext(); ObjectStore os = im.getObjectStore(); String superuser = im.getProfileManager().getSuperuser(); // place InlineLists based on TagManager, reportObject is cached while Controller is not Map<String, List<InlineList>> placedInlineLists = new TreeMap<String, List<InlineList>>(); // traverse all unplaced (non-header) InlineLists for (InlineList list : reportObject.getNormalInlineLists()) { FieldDescriptor fd = list.getDescriptor(); String taggedType = getTaggedType(fd); // assign lists to any aspects they are tagged to or put in unplaced lists String fieldPath = fd.getClassDescriptor().getUnqualifiedName() + "." + fd.getName(); List<Tag> tags = tagManager.getTags(null, fieldPath, taggedType, superuser); for (Tag tag : tags) { String tagName = tag.getTagName(); if (AspectTagUtil.isAspectTag(tagName)) { List<InlineList> listsForAspect = placedInlineLists.get(tagName); if (listsForAspect == null) { listsForAspect = new ArrayList<InlineList>(); placedInlineLists.put(tagName, listsForAspect); } listsForAspect.add(list); } else if (tagName.equals(TagNames.IM_SUMMARY)) { List<InlineList> summaryLists = placedInlineLists.get(tagName); if (summaryLists == null) { summaryLists = new ArrayList<InlineList>(); placedInlineLists.put(tagName, summaryLists); } summaryLists.add(list); } } } // any lists that aren't tagged will be 'unplaced' List<InlineList> unplacedInlineLists = new ArrayList<InlineList>(reportObject.getNormalInlineLists()); unplacedInlineLists.removeAll(placedInlineLists.values()); long now = System.currentTimeMillis(); LOG.info("TIME placed inline lists: " + (now - startTime) + "ms"); long stepTime = now; request.setAttribute("mapOfInlineLists", placedInlineLists); request.setAttribute("listOfUnplacedInlineLists", unplacedInlineLists); Map<String, Map<String, DisplayField>> placementRefsAndCollections = new TreeMap<String, Map<String, DisplayField>>(); Set<String> aspects = new LinkedHashSet<String>(SessionMethods.getCategories(servletContext)); Set<ClassDescriptor> cds = os.getModel().getClassDescriptorsForClass(requestedObject.getClass()); for (String aspect : aspects) { placementRefsAndCollections.put(TagNames.IM_ASPECT_PREFIX + aspect, new TreeMap<String, DisplayField>(String.CASE_INSENSITIVE_ORDER)); } Map<String, DisplayField> miscRefs = new TreeMap<String, DisplayField>( reportObject.getRefsAndCollections()); placementRefsAndCollections.put(TagNames.IM_ASPECT_MISC, miscRefs); // summary refs and colls Map<String, DisplayField> summaryRefsCols = new TreeMap<String, DisplayField>(); placementRefsAndCollections.put(TagNames.IM_SUMMARY, summaryRefsCols); for (Iterator<Entry<String, DisplayField>> iter = reportObject.getRefsAndCollections().entrySet().iterator(); iter.hasNext();) { Map.Entry<String, DisplayField> entry = iter.next(); DisplayField df = entry.getValue(); if (df instanceof DisplayReference) { categoriseBasedOnTags(((DisplayReference) df).getDescriptor(), "reference", df, miscRefs, tagManager, superuser, placementRefsAndCollections, SessionMethods.isSuperUser(session)); } else if (df instanceof DisplayCollection) { categoriseBasedOnTags(((DisplayCollection) df).getDescriptor(), "collection", df, miscRefs, tagManager, superuser, placementRefsAndCollections, SessionMethods.isSuperUser(session)); } } // remove any fields overridden by displayers removeFieldsReplacedByReportDisplayers(reportObject, placementRefsAndCollections); request.setAttribute("placementRefsAndCollections", placementRefsAndCollections); String type = reportObject.getType(); request.setAttribute("objectType", type); String stableLink = PortalHelper.generatePortalLink(reportObject.getObject(), im, request); if (stableLink != null) { request.setAttribute("stableLink", stableLink); } stepTime = System.currentTimeMillis(); startTime = stepTime; // attach only non empty categories Set<String> allClasses = new HashSet<String>(); for (ClassDescriptor cld : cds) { allClasses.add(cld.getUnqualifiedName()); } TemplateManager templateManager = im.getTemplateManager(); Map<String, List<ReportDisplayer>> displayerMap = reportObject.getReportDisplayers(); stepTime = System.currentTimeMillis(); startTime = stepTime; List<String> categories = new LinkedList<String>(); for (String aspect : aspects) { // 1) Displayers // 2) Inline Lists if ( (displayerMap != null && displayerMap.containsKey(aspect)) || placedInlineLists.containsKey(aspect)) { categories.add(aspect); } else { // 3) Templates if (!templateManager.getReportPageTemplatesForAspect(aspect, allClasses) .isEmpty()) { categories.add(aspect); } else { // 4) References & Collections if (placementRefsAndCollections.containsKey("im:aspect:" + aspect) && placementRefsAndCollections.get("im:aspect:" + aspect) != null) { for (DisplayField df : placementRefsAndCollections.get( "im:aspect:" + aspect).values()) { categories.add(aspect); break; } } } } } if (!categories.isEmpty()) { request.setAttribute("categories", categories); } now = System.currentTimeMillis(); LOG.info("TIME made list of categories: " + (now - stepTime) + "ms"); } return null; } private InterMineObject getRequestedObject(InterMineAPI im, HttpServletRequest request) { String idString = request.getParameter("id"); Integer id = new Integer(Integer.parseInt(idString)); ObjectStore os = im.getObjectStore(); InterMineObject requestedObject = null; try { requestedObject = os.getObjectById(id); } catch (ObjectStoreException e) { Log.warn("Accessed report page with id: " + id + " but failed to find object.", e); } return requestedObject; } private String getTaggedType(FieldDescriptor fd) { if (fd.isCollection()) { return "collection"; } else if (fd.isReference()) { return "reference"; } return "attribute"; } /** * For a given FieldDescriptor, look up its 'aspect:' tags and place it in * the correct map within placementRefsAndCollections. If categorised, * remove it from the supplied miscRefs map. * * @param fd the FieldDecriptor (a references or collection) * @param taggedType 'reference' or 'collection' * @param dispRef the corresponding DisplayReference or DisplayCollection * @param miscRefs map that contains dispRef (may be removed by this method) * @param tagManager the tag manager * @param sup the superuser account name * @param placementRefsAndCollections take from the ReportObject * @param isSuperUser if current user is superuser */ public static void categoriseBasedOnTags(FieldDescriptor fd, String taggedType, DisplayField dispRef, Map<String, DisplayField> miscRefs, TagManager tagManager, String sup, Map<String, Map<String, DisplayField>> placementRefsAndCollections, boolean isSuperUser) { List<Tag> tags = tagManager.getTags(null, fd.getClassDescriptor() .getUnqualifiedName() + "." + fd.getName(), taggedType, sup); for (Tag tag : tags) { String tagName = tag.getTagName(); if (!isSuperUser && tagName.equals(TagNames.IM_HIDDEN)) { //miscRefs.remove(fd.getName()); // Maybe it was added already to some placement and // that's why it must be removed removeField(fd.getName(), placementRefsAndCollections); return; } if (AspectTagUtil.isAspectTag(tagName)) { Map<String, DisplayField> refs = placementRefsAndCollections.get(tagName); if (refs != null) { refs.put(fd.getName(), dispRef); miscRefs.remove(fd.getName()); } } else if (tagName.equals(TagNames.IM_SUMMARY)) { Map<String, DisplayField> summary = placementRefsAndCollections.get(TagNames.IM_SUMMARY); if (summary != null) { summary.put(fd.getName(), dispRef); miscRefs.remove(fd.getName()); } miscRefs.remove(fd.getName()); } } } private void removeFieldsReplacedByReportDisplayers(ReportObject reportObject, Map<String, Map<String, DisplayField>> placementRefsAndCollections) { for (String fieldName : reportObject.getReplacedFieldExprs()) { removeField(fieldName, placementRefsAndCollections); } } /** * Removes field from placements. * * @param name * @param placementRefsAndCollections */ private static void removeField(String name, Map<String, Map<String, DisplayField>> placementRefsAndCollections) { Iterator<Entry<String, Map<String, DisplayField>>> it = placementRefsAndCollections .entrySet().iterator(); while (it.hasNext()) { Entry<String, Map<String, DisplayField>> entry = it.next(); entry.getValue().remove(name); } } }
package io.flutter.pub; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.LangDataKeys; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.List; import java.util.regex.Pattern; /** * A snapshot of the root directory of a pub package. * <p> * That is, a directory containing (at a minimum) a pubspec.yaml file. */ public class PubRoot { @NotNull private final VirtualFile root; @NotNull private final VirtualFile pubspec; @Nullable private final VirtualFile packages; @Nullable private final VirtualFile lib; private PubRoot(@NotNull VirtualFile root, @NotNull VirtualFile pubspec, @Nullable VirtualFile packages, @Nullable VirtualFile lib) { assert (!root.getPath().endsWith("/")); this.root = root; this.pubspec = pubspec; this.packages = packages; this.lib = lib; } /** * Returns the unique pub root for a project. * <p> * If there is more than one, returns null. */ @Nullable public static PubRoot forProject(@NotNull Project project) { final List<PubRoot> roots = PubRoots.forProject(project); if (roots.size() != 1) { return null; } return roots.get(0); } /** * Returns the unique pub root for a project. * <p> * If there is more than one, returns null. * <p> * Refreshes the returned pubroot's directory. (Not any others.) */ @Nullable public static PubRoot forProjectWithRefresh(@NotNull Project project) { final PubRoot root = forProject(project); return root == null ? null : root.refresh(); } /** * Returns the unique pub root for a module. * <p> * If there is more than one, returns null. * <p> * Refreshes the returned pubroot's directory. (Not any others.) */ @Nullable public static PubRoot forModuleWithRefresh(@NotNull Module module) { final List<PubRoot> roots = PubRoots.forModule(module); if (roots.size() != 1) { return null; } return roots.get(0).refresh(); } /** * Returns the appropriate pub root for an event. * <p> * Refreshes the returned pubroot's directory. (Not any others.) */ @Nullable public static PubRoot forEventWithRefresh(@NotNull final AnActionEvent event) { final PsiFile psiFile = CommonDataKeys.PSI_FILE.getData(event.getDataContext()); if (psiFile != null) { final PubRoot root = forPsiFile(psiFile); return root == null ? null : root.refresh(); } final Module module = LangDataKeys.MODULE.getData(event.getDataContext()); if (module != null) { return forModuleWithRefresh(module); } final Project project = event.getData(CommonDataKeys.PROJECT); if (project != null) { return forProjectWithRefresh(project); } return null; } /** * Returns the pub root for a PsiFile, if any. * <p> * The file must be within a content root that has a pubspec.yaml file. * <p> * Based on the filesystem cache; doesn't refresh anything. */ @Nullable public static PubRoot forPsiFile(@NotNull PsiFile psiFile) { final VirtualFile file = psiFile.getVirtualFile(); if (file == null) { return null; } if (isPubspec(file)) { return forDirectory(file.getParent()); } else { return forDescendant(file, psiFile.getProject()); } } /** * Returns the pub root for the content root containing a file or directory. * <p> * Based on the filesystem cache; doesn't refresh anything. */ @Nullable public static PubRoot forDescendant(VirtualFile fileOrDir, Project project) { final ProjectFileIndex index = ProjectRootManager.getInstance(project).getFileIndex(); final VirtualFile root = index.getContentRootForFile(fileOrDir); return forDirectory(root); } /** * Returns the PubRoot for a directory, provided it contains a pubspec.yaml file. * <p> * Otherwise returns null. * <p> * (The existence check is based on the filesystem cache; doesn't refresh anything.) */ @Nullable public static PubRoot forDirectory(@Nullable VirtualFile dir) { if (dir == null || !dir.isDirectory()) { return null; } final VirtualFile pubspec = dir.findChild("pubspec.yaml"); if (pubspec == null || !pubspec.exists() || pubspec.isDirectory()) { return null; } VirtualFile packages = dir.findChild(".packages"); if (packages == null || !packages.exists() || packages.isDirectory()) { packages = null; } VirtualFile lib = dir.findChild("lib"); if (lib == null || !lib.exists() || !lib.isDirectory()) { lib = null; } return new PubRoot(dir, pubspec, packages, lib); } /** * Returns the PubRoot for a directory, provided it contains a pubspec.yaml file. * <p> * Refreshes the directory and the lib directory (if present). Returns null if not found. */ @Nullable public static PubRoot forDirectoryWithRefresh(@NotNull VirtualFile dir) { // Ensure file existence and timestamps are up to date. dir.refresh(false, false); final PubRoot root = forDirectory(dir); if (root == null) return null; final VirtualFile lib = root.getLib(); if (lib != null) lib.refresh(false, false); return root; } /** * Returns the relative path to a file or directory within this PubRoot. * <p> * Returns null for the pub root directory, or it not within the pub root. */ @Nullable public String getRelativePath(@NotNull VirtualFile file) { final String root = this.root.getPath(); final String path = file.getPath(); if (!path.startsWith(root) || path.length() < root.length() + 2) { return null; } return path.substring(root.length() + 1); } /** * Returns true if the given file is a directory that contains tests. */ public boolean hasTests(@NotNull VirtualFile dir) { if (!dir.isDirectory()) return false; // We can run tests in the pub root. (It will look in the test dir.) if (getRoot().equals(dir)) return true; // Any directory in the test dir or below is also okay. final VirtualFile wanted = getTestDir(); if (wanted == null) return false; while (dir != null) { if (wanted.equals(dir)) return true; dir = dir.getParent(); } return false; } /** * Refreshes the pubroot and lib directories and returns an up-to-date snapshot. * <p> * Returns null if the directory or pubspec file is no longer there. */ @Nullable public PubRoot refresh() { return forDirectoryWithRefresh(root); } @NotNull public VirtualFile getRoot() { return root; } @NotNull public String getPath() { return root.getPath(); } @NotNull public VirtualFile getPubspec() { return pubspec; } /** * Returns true if the pubspec declares a flutter dependency. */ public boolean declaresFlutter() { try { final String contents = new String(pubspec.contentsToByteArray(true /* cache contents */)); return FLUTTER_SDK_DEP.matcher(contents).find(); } catch (IOException e) { return false; } } @Nullable public VirtualFile getPackages() { return packages; } /** * Returns true if the packages file is up to date. */ @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean hasUpToDatePackages() { return packages != null && pubspec.getTimeStamp() < packages.getTimeStamp(); } @Nullable public VirtualFile getLib() { return lib; } /** * Returns a file in lib if it exists. */ @Nullable public VirtualFile getFileToOpen() { final VirtualFile main = getLibMain(); if (main != null) { return main; } if (lib != null) { final VirtualFile[] files = lib.getChildren(); if (files.length != 0) { return files[0]; } } return null; } /** * Returns lib/main.dart if it exists. */ @Nullable public VirtualFile getLibMain() { return lib == null ? null : lib.findChild("main.dart"); } /** * Returns example/lib/main.dart if it exists. */ public VirtualFile getExampleLibMain() { if (lib == null) { return null; } final VirtualFile exampleDir = lib.findChild("example"); if (exampleDir != null) { final VirtualFile libDir = exampleDir.findChild("lib"); if (libDir != null) { return libDir.findChild("main.dart"); } } return null; } @Nullable public VirtualFile getTestDir() { return root.findChild("test"); } @Nullable public VirtualFile getExampleDir() { return root.findChild("example"); } /** * Returns the android subdirectory if it exists. */ @Nullable public VirtualFile getAndroidDir() { return root.findChild("android"); } /** * Returns the ios subdirectory if it exists. */ @Nullable public VirtualFile getiOsDir() { return root.findChild("ios"); } /** * Returns true if the project has a module for the "android" directory. */ public boolean hasAndroidModule(Project project) { final VirtualFile androidDir = getAndroidDir(); if (androidDir == null) { return false; } for (Module module : ModuleManager.getInstance(project).getModules()) { for (VirtualFile contentRoot : ModuleRootManager.getInstance(module).getContentRoots()) { if (contentRoot.equals(androidDir)) { return true; } } } return false; } /** * Returns the module containing this pub root, if any. */ @Nullable public Module getModule(@NotNull Project project) { if (project.isDisposed()) return null; return ProjectRootManager.getInstance(project).getFileIndex().getModuleForFile(pubspec); } /** * Returns true if the PubRoot is an ancestor of the given file. */ public boolean contains(@NotNull VirtualFile file) { VirtualFile dir = file.getParent(); while (dir != null) { if (dir.equals(root)) { return true; } dir = dir.getParent(); } return false; } @Override public String toString() { return "PubRoot(" + root.getName() + ")"; } public static boolean isPubspec(@NotNull VirtualFile file) { return !file.isDirectory() && file.getName().equals("pubspec.yaml"); } private static final Pattern FLUTTER_SDK_DEP = Pattern.compile(".*sdk:\\s*flutter"); //NON-NLS }
package com.jcwhatever.bukkit.generic.utils; import javax.annotation.Nullable; /** * Enum helper utilities. */ public class EnumUtils { private EnumUtils() {} /** * Get an enum by its constant name. The constant name is case sensitive. * * @param constantName The name of the enum constant. * @param enumClass The enum class. * * @param <T> The enum type. * * @return Null if the enum does not have a constant with the specified name. */ @Nullable public static <T extends Enum<T>> T getEnum(String constantName, Class<T> enumClass) { PreCon.notNull(constantName); PreCon.notNull(enumClass); return getEnum(constantName, enumClass, null); } /** * Get an enum by its constant name. The constant name is case sensitive. * * @param constantName The name of the enum constant. * @param enumClass The enum class. * @param def The default value to return if the constant is not found. * * @param <T> The enum type. * * @return Default value if the enum does not have a constant with the specified name. */ @Nullable public static <T extends Enum<T>> T getEnum(String constantName, Class<T> enumClass, @Nullable T def) { PreCon.notNull(constantName); PreCon.notNull(enumClass); if (!constantName.isEmpty()) { T value; try { value = Enum.valueOf(enumClass, constantName); } catch (Exception e) { return def; } return value; } return def; } /** * Get an enum by its constant name. The constant name is case insensitive. * * @param constantName The name of the enum constant. * @param enumClass The enum class. * * @param <T> The enum type. * * @return Null if the enum does not have a constant with the specified name. */ @Nullable public static <T extends Enum<T>> T searchEnum(String constantName, Class<T> enumClass) { PreCon.notNull(constantName); PreCon.notNull(enumClass); return searchEnum(constantName, enumClass, null); } /** * Get an enum by its constant name. The constant name is case insensitive. * * @param constantName The name of the enum constant. * @param enumClass The enum class. * @param def The default value to return if the constant is not found. * * @param <T> The enum type. * * @return Default value if the enum does not have a constant with the specified name. */ @Nullable public static <T extends Enum<T>> T searchEnum(String constantName, Class<T> enumClass, @Nullable T def) { PreCon.notNull(constantName); PreCon.notNull(enumClass); if (!constantName.isEmpty()) { T[] constants = enumClass.getEnumConstants(); for (T constant : constants) { if (constant.name().equalsIgnoreCase(constantName)) return constant; } } return def; } /** * Get an enum of an unknown type. Constant name is case sensitive. * * @param constantName The name of the enum constant. * @param enumClass The enum class. * @param def The default value to return if the constant is not found. * * @return The default value if the enum constant is not found. */ @Nullable public static Enum<?> getGenericEnum( String constantName, Class<? extends Enum<?>> enumClass, @Nullable Enum<?> def) { PreCon.notNull(constantName); PreCon.notNull(enumClass); if (!constantName.isEmpty()) { Enum<?>[] constants = enumClass.getEnumConstants(); for (Enum<?> constant : constants) { if (constant.name().equals(constantName)) return constant; } } return def; } /** * Get an enum of an unknown type. Constant name is case insensitive. * * @param constantName The name of the enum constant. * @param enumClass The enum class. * @param def The default value to return if the constant is not found. * * @return The default value if the enum constant is not found. */ @Nullable public static Enum<?> searchGenericEnum( String constantName, Class<? extends Enum<?>> enumClass, @Nullable Enum<?> def) { PreCon.notNull(constantName); PreCon.notNull(enumClass); if (!constantName.isEmpty()) { Enum<?>[] constants = enumClass.getEnumConstants(); for (Enum<?> constant : constants) { if (constant.name().equalsIgnoreCase(constantName)) return constant; } } return def; } /** * Get a raw enum from the enum constant name. Constant name is case sensitive. * * @param constantName The name of the enum constant. * @param enumClass The enum class. * @param def The default value to return if the constant is not found. * * @return The default value if the constant name is not found. */ @Nullable @SuppressWarnings("rawtypes") public static Enum getRawEnum(String constantName, Class enumClass, @Nullable Enum def) { PreCon.notNull(constantName); PreCon.notNull(enumClass); PreCon.isValid(enumClass.isEnum(), "enumClass must be an enum class."); if (!constantName.isEmpty()) { for (Object constant : enumClass.getEnumConstants()) { if (constant instanceof Enum) { if (((Enum) constant).name().equals(constantName)) { return (Enum)constant; } } } } return def; } /** * Get a raw enum from the enum constant name. Constant name is case insensitive. * * @param constantName The name of the enum constant. * @param enumClass The enum class. * @param def The default value to return if the constant is not found. * * @return The default value if the constant name is not found. */ @Nullable @SuppressWarnings("rawtypes") public static Enum searchRawEnum(String constantName, Class enumClass, @Nullable Enum def) { PreCon.notNull(constantName); PreCon.notNull(enumClass); PreCon.isValid(enumClass.isEnum(), "enumClass must be an enum class."); if (!constantName.isEmpty()) { for (Object constant : enumClass.getEnumConstants()) { if (constant instanceof Enum) { if (((Enum) constant).name().equalsIgnoreCase(constantName)) { return (Enum)constant; } } } } return def; } }
package org.intermine.web.struts; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.Map.Entry; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.intermine.api.InterMineAPI; import org.intermine.api.profile.TagManager; import org.intermine.api.tag.AspectTagUtil; import org.intermine.api.tag.TagNames; import org.intermine.api.template.TemplateManager; import org.intermine.metadata.ClassDescriptor; import org.intermine.metadata.FieldDescriptor; import org.intermine.model.InterMineObject; import org.intermine.model.userprofile.Tag; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreException; import org.intermine.web.displayer.CustomDisplayer; import org.intermine.web.logic.PortalHelper; import org.intermine.web.logic.config.InlineList; import org.intermine.web.logic.results.DisplayCollection; import org.intermine.web.logic.results.DisplayField; import org.intermine.web.logic.results.DisplayReference; import org.intermine.web.logic.results.ReportObject; import org.intermine.web.logic.results.ReportObjectFactory; import org.intermine.web.logic.session.SessionMethods; import org.jfree.util.Log; /** * New objectDetails. * * @author Radek Stepan */ public class ReportController extends InterMineAction { /** * {@inheritDoc} */ @Override public ActionForward execute(@SuppressWarnings("unused") ActionMapping mapping, @SuppressWarnings("unused") ActionForm form, HttpServletRequest request, @SuppressWarnings("unused") HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); InterMineAPI im = SessionMethods.getInterMineAPI(session); // fetch & set requested object InterMineObject requestedObject = getRequestedObject(im, request); if (requestedObject != null) { ReportObjectFactory reportObjectFactory = SessionMethods.getReportObjects(session); ReportObject reportObject = reportObjectFactory.get(requestedObject); //request.setAttribute("reportObject", reportObject); request.setAttribute("object", reportObject); request.setAttribute("reportObject", reportObject); request.setAttribute("requestedObject", requestedObject); // hell starts here TagManager tagManager = im.getTagManager(); ServletContext servletContext = session.getServletContext(); ObjectStore os = im.getObjectStore(); String superuser = im.getProfileManager().getSuperuser(); // place InlineLists based on TagManager, reportObject is cached while Controller is not Map<String, List<InlineList>> placedInlineLists = new TreeMap<String, List<InlineList>>(); // traverse all unplaced (non-header) InlineLists for (InlineList list : reportObject.getNormalInlineLists()) { FieldDescriptor fd = list.getDescriptor(); String taggedType = getTaggedType(fd); // assign lists to any aspects they are tagged to or put in unplaced lists List<Tag> tags = tagManager.getTags(null, fd.getClassDescriptor().getUnqualifiedName() + "." + fd.getName(), taggedType, superuser); for (Tag tag : tags) { String tagName = tag.getTagName(); if (AspectTagUtil.isAspectTag(tagName)) { List<InlineList> listsForAspect = placedInlineLists.get(tagName); if (listsForAspect == null) { listsForAspect = new ArrayList<InlineList>(); placedInlineLists.put(tagName, listsForAspect); } listsForAspect.add(list); } } } // any lists that aren't tagged will be 'unplaced' List<InlineList> unplacedInlineLists = new ArrayList<InlineList>(reportObject.getNormalInlineLists()); unplacedInlineLists.removeAll(placedInlineLists.values()); request.setAttribute("mapOfInlineLists", placedInlineLists); request.setAttribute("listOfUnplacedInlineLists", unplacedInlineLists); Map<String, Map<String, DisplayField>> placementRefsAndCollections = new TreeMap<String, Map<String, DisplayField>>(); Set<String> aspects = new LinkedHashSet<String>(SessionMethods.getCategories(servletContext)); Set<ClassDescriptor> cds = os.getModel().getClassDescriptorsForClass(requestedObject.getClass()); for (String aspect : aspects) { placementRefsAndCollections.put(TagNames.IM_ASPECT_PREFIX + aspect, new TreeMap<String, DisplayField>(String.CASE_INSENSITIVE_ORDER)); } Map<String, DisplayField> miscRefs = new TreeMap<String, DisplayField>( reportObject.getRefsAndCollections()); placementRefsAndCollections.put(TagNames.IM_ASPECT_MISC, miscRefs); for (Iterator<Entry<String, DisplayField>> iter = reportObject.getRefsAndCollections().entrySet().iterator(); iter.hasNext();) { Map.Entry<String, DisplayField> entry = iter.next(); DisplayField df = entry.getValue(); if (df instanceof DisplayReference) { categoriseBasedOnTags(((DisplayReference) df).getDescriptor(), "reference", df, miscRefs, tagManager, superuser, placementRefsAndCollections, SessionMethods.isSuperUser(session)); } else if (df instanceof DisplayCollection) { categoriseBasedOnTags(((DisplayCollection) df).getDescriptor(), "collection", df, miscRefs, tagManager, superuser, placementRefsAndCollections, SessionMethods.isSuperUser(session)); } } // remove any fields overridden by displayers removeFieldsReplacedByCustomDisplayers(reportObject, placementRefsAndCollections); request.setAttribute("placementRefsAndCollections", placementRefsAndCollections); String type = reportObject.getType(); request.setAttribute("objectType", type); String stableLink = PortalHelper.generatePortalLink(reportObject.getObject(), im, request); if (stableLink != null) { request.setAttribute("stableLink", stableLink); } // attach only non empty categories Set<String> allClasses = new HashSet<String>(); for (ClassDescriptor cld : cds) { allClasses.add(cld.getUnqualifiedName()); } TemplateManager templateManager = im.getTemplateManager(); Map<String, List<CustomDisplayer>> displayerMap = reportObject.getReportDisplayers(); List<String> categories = new LinkedList<String>(); for (String aspect : aspects) { // 1) Displayers // 2) Inline Lists if ( (displayerMap != null && displayerMap.containsKey(aspect)) || placedInlineLists.containsKey(aspect)) { categories.add(aspect); } else { // 3) Templates if (!templateManager.getReportPageTemplatesForAspect(aspect, allClasses) .isEmpty()) { categories.add(aspect); } else { // 4) References & Collections if (placementRefsAndCollections.containsKey("im:aspect:" + aspect) && placementRefsAndCollections.get("im:aspect:" + aspect) != null) { for (DisplayField df : placementRefsAndCollections.get( "im:aspect:" + aspect).values()) { if (df.getSize() > 0) { categories.add(aspect); break; } } } } } } if (!categories.isEmpty()) { request.setAttribute("categories", categories); } } return null; } private InterMineObject getRequestedObject(InterMineAPI im, HttpServletRequest request) { String idString = request.getParameter("id"); Integer id = new Integer(Integer.parseInt(idString)); ObjectStore os = im.getObjectStore(); InterMineObject requestedObject = null; try { requestedObject = os.getObjectById(id); } catch (ObjectStoreException e) { Log.warn("Accessed report page with id: " + id + " but failed to find object.", e); } return requestedObject; } private String getTaggedType(FieldDescriptor fd) { if (fd.isCollection()) { return "collection"; } else if (fd.isReference()) { return "reference"; } return "attribute"; } /** * For a given FieldDescriptor, look up its 'aspect:' tags and place it in * the correct map within placementRefsAndCollections. If categorised, * remove it from the supplied miscRefs map. * * @param fd the FieldDecriptor (a references or collection) * @param taggedType 'reference' or 'collection' * @param dispRef the corresponding DisplayReference or DisplayCollection * @param miscRefs map that contains dispRef (may be removed by this method) * @param tagManager the tag manager * @param sup the superuser account name * @param placementRefsAndCollections take from the ReportObject * @param isSuperUser if current user is superuser */ public static void categoriseBasedOnTags(FieldDescriptor fd, String taggedType, DisplayField dispRef, Map<String, DisplayField> miscRefs, TagManager tagManager, String sup, Map<String, Map<String, DisplayField>> placementRefsAndCollections, boolean isSuperUser) { List<Tag> tags = tagManager.getTags(null, fd.getClassDescriptor() .getUnqualifiedName() + "." + fd.getName(), taggedType, sup); for (Tag tag : tags) { String tagName = tag.getTagName(); if (!isSuperUser && tagName.equals(TagNames.IM_HIDDEN)) { //miscRefs.remove(fd.getName()); // Maybe it was added already to some placement and // that's why it must be removed removeField(fd.getName(), placementRefsAndCollections); return; } if (AspectTagUtil.isAspectTag(tagName)) { Map<String, DisplayField> refs = placementRefsAndCollections.get(tagName); if (refs != null) { refs.put(fd.getName(), dispRef); miscRefs.remove(fd.getName()); } } else if (tagName.equals(TagNames.IM_SUMMARY)) { //miscRefs.remove(fd.getName()); } } } private void removeFieldsReplacedByCustomDisplayers(ReportObject reportObject, Map<String, Map<String, DisplayField>> placementRefsAndCollections) { for (String fieldName : reportObject.getReplacedFieldExprs()) { removeField(fieldName, placementRefsAndCollections); } } /** * Removes field from placements. * * @param name * @param placementRefsAndCollections */ private static void removeField(String name, Map<String, Map<String, DisplayField>> placementRefsAndCollections) { Iterator<Entry<String, Map<String, DisplayField>>> it = placementRefsAndCollections .entrySet().iterator(); while (it.hasNext()) { Entry<String, Map<String, DisplayField>> entry = it.next(); entry.getValue().remove(name); } } }
package algorithms.imageProcessing; import algorithms.CountingSort; import algorithms.MultiArrayMergeSort; import algorithms.QuickSort; import algorithms.util.PairIntArray; import algorithms.util.PairInt; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * Edge extractor operates on an image that has already been reduced to * single pixel width lines and extracts edges from it, attempting to make * the longest edges it can - this specific edge extractor stores and uses * junction information, so is not as fast as EdgeExtractor.java. * Edge extraction Local Methods: (1) DFS walk through adjacent non-zero pixels to form a sequence of pixels called an edge. (2) find join points (3) join edges using join points (4) find junction points (5) using the junction points, splice together the edges to improve the edges. Currently, improve means to make the edges longer (which is good for an image expected to have one contour for example, and doesn't harm corner finding for non-contour goals). (7) remove edges shorter than a minimum length (this may of may not be currently enabled) @see AbstractEdgeExtractor * * @author nichole */ public class EdgeExtractorWithJunctions extends AbstractEdgeExtractor { private boolean debug = false; /** * map with key = center of junction pixel coordinates; * value = set of adjacent pixels when there are more than the preceding * and next. */ private Map<Integer, Set<Integer>> junctionMap = new HashMap<Integer, Set<Integer>>(); /** * map with key = pixel coordinates of all pixels involved in junctions; * value = PairInt holding index of edge that pixel is located in and * holding the index within that edge of the pixel. * for example, a pixel located in edges(0) at offset=100 * would have PairInt(0, 100) as a value. */ private Map<Integer, PairInt> junctionLocationMap = new HashMap<Integer, PairInt>(); /** * NOTE: input should have a black (empty) background and edges should * have values > 125 counts. Edges should also have width of 1 and no larger. * * @param input */ public EdgeExtractorWithJunctions(GreyscaleImage input) { super(input); } /** * NOTE: input should have a black (empty) background and edges should * have values > 125 counts. Edges should also have width of 1 and no larger. * The guide image is used to alter the extracted edges back towards the * highest intensity pixels of the guide image. The guide image is expected * to be the combined X and Y gradient image from earlier processing * stages. * * @param input * @param anEdgeGuideImage */ public EdgeExtractorWithJunctions(GreyscaleImage input, final GreyscaleImage anEdgeGuideImage) { super(input, anEdgeGuideImage); } /** * get a hashmap of the junctions within the edges, that is the regions * where there are more than 2 adjacent pixels to a pixel. * @return hashmap with key = image pixel indexes, values = set of adjacent * pixels as pixel indexes. */ public Map<Integer, Set<Integer> > getJunctionMap() { return junctionMap; } /** * contains information needed to find any of the pixels that are part of * a junction. * @return hashmap with key = image pixel indexes, values = a PairInt with * x holding the edge index and y holding the offset index of the point * within the edge. */ public Map<Integer, PairInt> getLocatorForJunctionAssociatedPoints() { return junctionLocationMap; } /** * find the edges and return as a list of points. The method uses a * DFS search through all points in the image with values > 0 to link * adjacent sequential points into edges. * As a side effect, the method also populates * member variables edgeJunctionMap and outputIndexLocatorForJunctionPoints. * * @return */ @Override public List<PairIntArray> findEdgesIntermediateSteps(List<PairIntArray> edges) { List<PairIntArray> output = edges; Map<PairInt, PairInt> joinPoints = findJoinPoints(output); //printJoinPoints(joinPoints, output); output = joinOnJoinPoints(joinPoints, output); findJunctions(output); //printJunctions(output); spliceEdgesAtJunctionsIfImproves(output); return output; } /** * Find the join points of edges which are adjacent to one another and to * no other edges. This method is intended to follow the first creation * of edges from the line thinned edge image to find the unambiguously * connectable edges. (Note that the method findJunctions(...) is later * used to find where there are more than 2 adjacent pixels to any pixel.) * * runtime complexity is O(N). * * @param edges * @return hashmap with key = edge index and index within edge of pixel; * value = the adjacent pixel's edge index and index within its edge */ protected Map<PairInt, PairInt> findJoinPoints(List<PairIntArray> edges) { /* TODO: the logic here has changed again to only use the endpoints or points near the endpoints, so this could be rewritten to iterate only over endpoints instead of every point in every edge. */ // join points for adjacent edge endPoints that are not junctions // key = edge index and index within edge of pixel // value = the adjacent pixel's edge index and index within its edge Map<PairInt, PairInt> theJoinPoints = new HashMap<PairInt, PairInt>(); int n = edges.size(); // key = image pixel index, // value = pairint of edge index, and index within edge Map<Integer, PairInt> pointLocator = new HashMap<Integer, PairInt>(); for (int edgeIdx = 0; edgeIdx < n; edgeIdx++) { PairIntArray edge = edges.get(edgeIdx); for (int iEdgeIdx = 0; iEdgeIdx < edge.getN(); iEdgeIdx++) { int pixIdx = img.getIndex(edge.getX(iEdgeIdx), edge.getY(iEdgeIdx)); pointLocator.put(Integer.valueOf(pixIdx), new PairInt(edgeIdx, iEdgeIdx)); } } int w = img.getWidth(); int h = img.getHeight(); int[] dxs = new int[]{-1, -1, 0, 1, 1, 1, 0, -1}; int[] dys = new int[]{ 0, -1, -1, -1, 0, 1, 1, 1}; /* map edgePairPoints: key = pairint of edge1, edge2 to be joined, ordered by increasing value value = edge point location points for found join points for the key */ Map<PairInt, Set<PairInt>> edgePairPoints = new HashMap<PairInt, Set<PairInt>>(); Set<PairInt> adjacent = new HashSet<PairInt>(); // 8 * O(N) for (int edgeIdx = 0; edgeIdx < n; edgeIdx++) { PairIntArray edge = edges.get(edgeIdx); for (int indexWithinEdge = 0; indexWithinEdge < edge.getN(); indexWithinEdge++) { int col = edge.getX(indexWithinEdge); int row = edge.getY(indexWithinEdge); int uIdx = img.getIndex(col, row); adjacent.clear(); for (int nIdx = 0; nIdx < dxs.length; nIdx++) { int x = col + dxs[nIdx]; int y = row + dys[nIdx]; if ((x < 0) || (x > (w - 1)) || (y < 0) || (y > (h - 1))) { continue; } int vIdx = img.getIndex(x, y); PairInt vLoc = pointLocator.get(Integer.valueOf(vIdx)); if (vLoc != null) { if (vLoc.getX() != edgeIdx) { int diffX = x - col; int diffY = y - row; if ((Math.abs(diffX) < 2) && (Math.abs(diffY) < 2)) { adjacent.add(vLoc); } } } } // 2 neighbors means a join point instead of a junction, // so add it or replace an existing shorter join point if (adjacent.size() == 1) { PairInt vLoc = adjacent.iterator().next(); int edgeIdx0 = edgeIdx; int edgeIdx1 = vLoc.getX(); if (edgeIdx1 < edgeIdx0) { int swap = edgeIdx0; edgeIdx0 = edgeIdx1; edgeIdx1 = swap; } PairInt edgePair = new PairInt(edgeIdx0, edgeIdx1); Set<PairInt> set = edgePairPoints.get(edgePair); if (set == null) { set = new HashSet<PairInt>(); } set.add(vLoc); set.add(new PairInt(edgeIdx, indexWithinEdge)); edgePairPoints.put(edgePair, set); } else if (adjacent.size() > 1) { // if u is an endpoint, store each v that is an endpoint too //TODO: consider allowing if next to the endpoint too if ((indexWithinEdge == 0) || (indexWithinEdge == (edge.getN() - 1))) { for (PairInt vLoc : adjacent) { PairIntArray vEdge = edges.get(vLoc.getX()); int vEdgeN = vEdge.getN(); if ((vLoc.getY() == 0) || (vLoc.getY() == (vEdgeN - 1))) { int edgeIdx0 = edgeIdx; int edgeIdx1 = vLoc.getX(); if (edgeIdx1 < edgeIdx0) { int swap = edgeIdx0; edgeIdx0 = edgeIdx1; edgeIdx1 = swap; } PairInt edgePair = new PairInt(edgeIdx0, edgeIdx1); Set<PairInt> set = edgePairPoints.get(edgePair); if (set == null) { set = new HashSet<PairInt>(); } set.add(vLoc); set.add(new PairInt(edgeIdx, indexWithinEdge)); edgePairPoints.put(edgePair, set); } } } } } } // make sure same point is only present once in joinPoints Map<PairInt, PairInt> invJoinPoints = new HashMap<PairInt, PairInt>(); for (Entry<PairInt, Set<PairInt>> entry : edgePairPoints.entrySet()) { int edgeIdx0 = entry.getKey().getX(); int edgeIdx1 = entry.getKey().getY(); int edge0N = edges.get(edgeIdx0).getN(); int edge1N = edges.get(edgeIdx1).getN(); Set<PairInt> set0 = new HashSet<PairInt>(); Set<PairInt> set1 = new HashSet<PairInt>(); for (PairInt p : entry.getValue()) { if (p.getX() == edgeIdx0) { set0.add(p); } else { set1.add(p); } } boolean point0IsAnEndPoint = false; boolean point1IsAnEndPoint = false; PairInt edge0Endpoint = null; PairInt edge1Endpoint = null; int minDistSq = Integer.MAX_VALUE; for (PairInt p0 : set0) { PairIntArray edge0 = edges.get(p0.getX()); int x0 = edge0.getX(p0.getY()); int y0 = edge0.getY(p0.getY()); boolean t0 = (p0.getY() < 2) || (p0.getY() > (edge0.getN() - 3)); if (!t0) { continue; } for (PairInt p1 : set1) { PairIntArray edge1 = edges.get(p1.getX()); int x1 = edge1.getX(p1.getY()); int y1 = edge1.getY(p1.getY()); int diffX = x1 - x0; int diffY = y1 - y0; int distSq = (diffX * diffX) + (diffY * diffY); boolean t1 = (p1.getY() < 2) || (p1.getY() > (edge1.getN() - 3)); if (!t1) { continue; } if (distSq < minDistSq) { edge0Endpoint = p0; edge1Endpoint = p1; point0IsAnEndPoint = (p0.getY() == 0) || (p0.getY() == (edge0.getN() - 1)); point1IsAnEndPoint = (p1.getY() == 0) || (p1.getY() == (edge1.getN() - 1)); minDistSq = distSq; } else if (distSq == minDistSq) { // prefer this if existing aren't endpoints // and these are if ((!point0IsAnEndPoint || !point1IsAnEndPoint) && (t0 && t1)) { edge0Endpoint = p0; edge1Endpoint = p1; point0IsAnEndPoint = (p0.getY() == 0) || (p0.getY() == (edge0.getN() - 1)); point1IsAnEndPoint = (p1.getY() == 0) || (p1.getY() == (edge1.getN() - 1)); } else if ((!point0IsAnEndPoint && !point1IsAnEndPoint) && (t0 || t1)) { edge0Endpoint = p0; edge1Endpoint = p1; point0IsAnEndPoint = (p0.getY() == 0) || (p0.getY() == (edge0.getN() - 1)); point1IsAnEndPoint = (p1.getY() == 0) || (p1.getY() == (edge1.getN() - 1)); } } } } if (edge0Endpoint == null || edge1Endpoint == null) { continue; } edge0Endpoint = new PairInt(edge0Endpoint.getX(), edge0Endpoint.getY()); edge1Endpoint = new PairInt(edge1Endpoint.getX(), edge1Endpoint.getY()); // since we know both points are endpoints or can be reordered, // can use the reorder method as it has no effect if they are int r0 = reorderIfNearEnd(edge0Endpoint, edges.get(edge0Endpoint.getX()), edge1Endpoint, edges.get(edge1Endpoint.getX())); if (r0 < 0) { continue; } int r1 = reorderIfNearEnd(edge1Endpoint, edges.get(edge1Endpoint.getX()), edge0Endpoint, edges.get(edge0Endpoint.getX())); if (r1 < 0) { continue; } if (theJoinPoints.containsKey(edge0Endpoint) || theJoinPoints.containsKey(edge1Endpoint) || invJoinPoints.containsKey(edge0Endpoint) || invJoinPoints.containsKey(edge1Endpoint) ) { // compare to existing and keep the longest and remove the other PairInt otherEP0 = null; PairInt otherEP1 = null; if (theJoinPoints.containsKey(edge0Endpoint)) { otherEP0 = edge0Endpoint; otherEP1 = theJoinPoints.get(edge0Endpoint); } else if (theJoinPoints.containsKey(edge1Endpoint)) { otherEP0 = edge1Endpoint; otherEP1 = theJoinPoints.get(edge1Endpoint); } else if (invJoinPoints.containsKey(edge0Endpoint)) { otherEP0 = edge0Endpoint; otherEP1 = invJoinPoints.get(edge0Endpoint); } else { otherEP0 = edge1Endpoint; otherEP1 = invJoinPoints.get(edge1Endpoint); } int currentTotalN = edge0N + edge1N; int otherTotalN = edges.get(otherEP0.getX()).getN() + edges.get(otherEP1.getX()).getN(); if (otherTotalN < currentTotalN) { theJoinPoints.remove(otherEP0); theJoinPoints.remove(otherEP1); invJoinPoints.remove(otherEP0); invJoinPoints.remove(otherEP1); theJoinPoints.put(edge0Endpoint, edge1Endpoint); invJoinPoints.put(edge1Endpoint, edge0Endpoint); } } else { theJoinPoints.put(edge0Endpoint, edge1Endpoint); invJoinPoints.put(edge1Endpoint, edge0Endpoint); } } // TODO: // there's an error above that sometimes results in the same join point // specified for two different edges, so fixing that here until // the algorithm gets revised. Set<PairInt> remove = new HashSet<PairInt>(); for (Entry<PairInt, PairInt> entry : theJoinPoints.entrySet()) { PairInt ep0 = entry.getKey(); PairInt ep1 = entry.getValue(); // an endpoint should not be present as a key in both maps. // if it is, one of the entries has to be removed. prefer the // longest edge total. if (theJoinPoints.containsKey(ep0) && invJoinPoints.containsKey(ep0)) { PairInt other = ep1; PairInt invOther = invJoinPoints.get(ep0); int currentN = edges.get(other.getX()).getN(); int otherN = edges.get(invOther.getX()).getN(); if (currentN > otherN) { invJoinPoints.remove(ep0); } else { remove.add(ep0); } } } for (PairInt p : remove) { theJoinPoints.remove(p); } return theJoinPoints; } /** * Iterate over each point looking for its neighbors and noting when * there are more than 2, and store the found junctions as member variables. * * runtime complexity is O(N) * * @param edges */ protected void findJunctions(List<PairIntArray> edges) { // key = center of junction pixel coordinates // value = set of adjacent pixels when there are more than the preceding // and next. Map<Integer, Set<Integer> > theJunctionMap = new HashMap<Integer, Set<Integer>>(); // key = pixel coordinates of all pixels involved in junctions // value = PairInt holding index of edge that pixel is located in and // holding the index within that edge of the pixel. // for example, a pixel located in edges(0) at offset=100 // would have PairInt(0, 100) as a value. Map<Integer, PairInt> theJunctionLocationMap = new HashMap<Integer, PairInt>(); int n = edges.size(); // key = image pixel index, // value = pairint of edge index, and index within edge Map<Integer, PairInt> pointLocator = new HashMap<Integer, PairInt>(); for (int edgeIdx = 0; edgeIdx < n; edgeIdx++) { PairIntArray edge = edges.get(edgeIdx); for (int uIdx = 0; uIdx < edge.getN(); uIdx++) { int pixIdx = img.getIndex(edge.getX(uIdx), edge.getY(uIdx)); pointLocator.put(Integer.valueOf(pixIdx), new PairInt(edgeIdx, uIdx)); } } int w = img.getWidth(); int h = img.getHeight(); int[] dxs = new int[]{-1, -1, 0, 1, 1, 1, 0, -1}; int[] dys = new int[]{ 0, -1, -1, -1, 0, 1, 1, 1}; // 8 * O(N) for (int edgeIdx = 0; edgeIdx < n; edgeIdx++) { PairIntArray edge = edges.get(edgeIdx); for (int iEdgeIdx = 0; iEdgeIdx < edge.getN(); iEdgeIdx++) { int col = edge.getX(iEdgeIdx); int row = edge.getY(iEdgeIdx); int uIdx = img.getIndex(col, row); Set<PairInt> neighbors = new HashSet<PairInt>(); for (int nIdx = 0; nIdx < dxs.length; nIdx++) { int x = col + dxs[nIdx]; int y = row + dys[nIdx]; if ((x < 0) || (x > (w - 1)) || (y < 0) || (y > (h - 1))) { continue; } int vIdx = img.getIndex(x, y); PairInt vLoc = pointLocator.get(Integer.valueOf(vIdx)); if (vLoc != null) { neighbors.add(vLoc); } } if (neighbors.size() > 2) { Set<Integer> indexes = new HashSet<Integer>(); for (PairInt p : neighbors) { int edge2Idx = p.getX(); int iEdge2Idx = p.getY(); PairIntArray vEdge = edges.get(edge2Idx); int vIdx = img.getIndex(vEdge.getX(iEdge2Idx), vEdge.getY(iEdge2Idx)); theJunctionLocationMap.put(Integer.valueOf(vIdx), p); indexes.add(Integer.valueOf(vIdx)); } theJunctionMap.put(Integer.valueOf(uIdx), indexes); theJunctionLocationMap.put(Integer.valueOf(uIdx), new PairInt(edgeIdx, iEdgeIdx)); } // if (neighbors.size() == 2) is handled in findJoinPoints } } // visit each junction and make sure the real center is the only one // stored Set<Integer> remove = new HashSet<Integer>(); Set<Integer> doNotRemove = new HashSet<Integer>(); for (Entry<Integer, Set<Integer>> entry : theJunctionMap.entrySet()) { Integer pixelIndex = entry.getKey(); int col = img.getCol(pixelIndex.intValue()); int row = img.getRow(pixelIndex.intValue()); Set<Integer> neighborIndexes = entry.getValue(); int nN = neighborIndexes.size(); int maxN = Integer.MIN_VALUE; for (Integer pixelIndex2 : neighborIndexes) { if (remove.contains(pixelIndex2)) { continue; } Set<Integer> neighborIndexes2 = theJunctionMap.get(pixelIndex2); if (neighborIndexes2 == null) { continue; } if (neighborIndexes2.size() > nN) { if (neighborIndexes2.size() > maxN) { maxN = neighborIndexes2.size(); } } } if (maxN > Integer.MIN_VALUE) { // remove this pixel remove.add(pixelIndex); assert(!doNotRemove.contains(pixelIndex)); } else { doNotRemove.add(pixelIndex); // remove the neighbors from the junction map for (Integer pixelIndex2 : neighborIndexes) { if (!doNotRemove.contains(pixelIndex2)) { remove.add(pixelIndex2); } } } } for (Integer pixelIndex : remove) { theJunctionMap.remove(pixelIndex); } junctionMap = theJunctionMap; junctionLocationMap = theJunctionLocationMap; } private void printJoinPoints(Map<PairInt, PairInt> joinPoints, List<PairIntArray> edges) { StringBuilder sb = new StringBuilder("join points:\n"); for (Entry<PairInt, PairInt> entry : joinPoints.entrySet()) { PairInt loc0 = entry.getKey(); PairInt loc1 = entry.getValue(); PairIntArray edge0 = edges.get(loc0.getX()); int x0 = edge0.getX(loc0.getY()); int y0 = edge0.getY(loc0.getY()); PairIntArray edge1 = edges.get(loc1.getX()); int x1 = edge1.getX(loc1.getY()); int y1 = edge1.getY(loc1.getY()); sb.append(String.format(" (%d,%d) to (%d,%d) in edges %d and %d at positions=%d out of %d and %d out of %d\n", x0, y0, x1, y1, loc0.getX(), loc1.getX(), loc0.getY(), edges.get(loc0.getX()).getN(), loc1.getY(), edges.get(loc1.getX()).getN() )); } log.info(sb.toString()); } private void printJoinPoints(PairInt[][] edgeJoins, int idxLo, int idxHi, Map<Integer, PairIntArray> edges) { // print array indexes int[] aIndexes = new int[edges.size()]; int count = 0; for (Entry<Integer, PairIntArray> entry : edges.entrySet()) { Integer edgeIndex = entry.getKey(); aIndexes[count] = edgeIndex.intValue(); count++; } CountingSort.sort(aIndexes, 2*edges.size()); StringBuilder sb = new StringBuilder("output indexes of size "); sb.append(Integer.toString(edges.size())).append("\n"); for (int i = 0; i < aIndexes.length; i++) { sb.append(Integer.toString(aIndexes[i])).append(" "); } log.info(sb.toString()); sb = new StringBuilder("join points:\n"); for (int i = idxLo; i <= idxHi; i++) { PairInt loc0 = edgeJoins[i][0]; PairInt loc1 = edgeJoins[i][1]; PairIntArray edge0 = edges.get(Integer.valueOf(loc0.getX())); int x0 = edge0.getX(loc0.getY()); int y0 = edge0.getY(loc0.getY()); PairIntArray edge1 = edges.get(Integer.valueOf(loc1.getX())); int x1 = edge1.getX(loc1.getY()); int y1 = edge1.getY(loc1.getY()); sb.append(String.format(" (%d,%d) to (%d,%d) in edges %d and %d at positions=%d out of %d and %d out of %d\n", x0, y0, x1, y1, loc0.getX(), loc1.getX(), loc0.getY(), edge0.getN(), loc1.getY(), edge1.getN() )); } log.info(sb.toString()); } private Map<Integer, PairIntArray> createIndexedMap(List<PairIntArray> edges) { Map<Integer, PairIntArray> output = new HashMap<Integer, PairIntArray>(); for (int i = 0; i < edges.size(); i++) { output.put(Integer.valueOf(i), edges.get(i)); } return output; } /** * join edges using information in the member variable joinPoints * and update the junction and joinPoint information after the * changes. * @param joinPoints * @param edges * @return */ protected List<PairIntArray> joinOnJoinPoints(Map<PairInt, PairInt> joinPoints, List<PairIntArray> edges) { //order the join points int[] indexes = new int[joinPoints.size()]; PairInt[][] edgeJoins = new PairInt[joinPoints.size()][2]; int count = 0; for (Entry<PairInt, PairInt> entry : joinPoints.entrySet()) { PairInt loc0 = entry.getKey(); PairInt loc1 = entry.getValue(); indexes[count] = loc0.getX(); edgeJoins[count] = new PairInt[]{loc0, loc1}; count++; } QuickSort.sortBy1stArg(indexes, edgeJoins); long nPointsBefore = countPixelsInEdges(edges); // put the edges in a map to remove and search updates faster Map<Integer, PairIntArray> edgesMap = createIndexedMap(edges); int n = edgeJoins.length; for (int i = (n - 1); i > -1; --i) { //printJoinPoints(edgeJoins, 0, i, edgesMap); PairInt[] entry = edgeJoins[i]; PairInt loc0 = entry[0]; PairInt loc1 = entry[1]; // if they've already been merged if (loc0.getX() == loc1.getX()) { continue; } // the smaller edge index should be loc1 and the larger loc0, if (loc1.getX() > loc0.getX()) { PairInt tmp = loc0; loc0 = loc1; loc1 = tmp; } // edge to move PairIntArray edge0 = edgesMap.remove(Integer.valueOf(loc0.getX())); int removedEdgeIdx = loc0.getX(); int n0 = edge0.getN(); if ((loc0.getY() != 0) && (loc0.getY() != (n0 - 1))){ /* this can happen if there is an error in the join point algorithm resulting in the same join point to 2 different edges. an update in the location will eventually be an error in one of them. After more testing, will change this to discard the join point and warn of error. */ throw new IllegalStateException("ERROR in the updates? " + " loc0=" + loc0.getX() + "," + loc0.getY() + " n=" + n0 + " i=" + i + " (nedges=" + n + ") to append edge " + loc0.getX() + " to edge " + loc1.getX()); } // join point should be at the beginning, so reverse if not if (loc0.getY() == (n0 - 1)) { edge0.reverse(); loc0.setY(0); // everything with smaller index than i in edgeJoins with // edgeIndex==loc0.getX() needs to be updated for this reversal. // idx becomes n-idx-1 for (int j = (i - 1); j > -1; --j) { PairInt[] vEntry = edgeJoins[j]; for (int k = 0; k < 2; k++) { PairInt vLoc = vEntry[k]; if (vLoc.getX() == loc0.getX()) { int idxRev = n0 - vLoc.getY() - 1; vLoc.setY(idxRev); } } } } // edge to receive new edge PairIntArray edge1 = edgesMap.get(Integer.valueOf(loc1.getX())); int n1 = edge1.getN(); // endpoint should be at the end, so reverse if not if (loc1.getY() == 0) { edge1.reverse(); loc1.setY(n1 - 1); // everything with smaller index than i in edgeJoins that has // edgeIndex==loc1.getX() needs to be updated for this reversal. // idx becomes n-idx-1 for (int j = (i - 1); j > -1; --j) { PairInt[] vEntry = edgeJoins[j]; for (int k = 0; k < 2; k++) { PairInt vLoc = vEntry[k]; if (vLoc.getX() == loc1.getX()) { int idxRev = n1 - vLoc.getY() - 1; vLoc.setY(idxRev); } } } } edge1.addAll(edge0); // for earlier items in array edgeJoins // need to update all edge indexes and indexes within edge. // loc0 got appended to loc1 --> [edge1][edge0] // points in edge0 need n1 added to them // first, will only update the indexes within the edge for // edgeIndex == loc0.getX() // the new offset index = n0 + index for (int j = (i - 1); j > -1; --j) { PairInt[] vEntry = edgeJoins[j]; for (int k = 0; k < 2; k++) { PairInt vLoc = vEntry[k]; if (vLoc.getX() == loc0.getX()) { int idxEdit = vLoc.getY() + n1; vLoc.setY(idxEdit); } } } // any edge index > loc0 gets reduced by one, but if == it gets replaced by loc1.getX() for (int j = (i - 1); j > -1; --j) { PairInt[] vEntry = edgeJoins[j]; for (int k = 0; k < 2; k++) { PairInt vLoc = vEntry[k]; if (vLoc.getX() > loc0.getX()) { int editX = vLoc.getX() - 1; vLoc.setX(editX); } else if (vLoc.getX() == loc0.getX()) { int editX = loc1.getX(); vLoc.setX(editX); } } } // the output map keeps 0 to loc1.getx(), // but loc0.getX() + 1 gets moved to loc0.getX() // and on until have reached size() - 1 for (int j = (removedEdgeIdx + 1); j <= edgesMap.size(); ++j) { PairIntArray v = edgesMap.remove(Integer.valueOf(j)); assert(v != null); edgesMap.put(Integer.valueOf(j - 1), v); } } List<PairIntArray> output = new ArrayList<PairIntArray>(); for (int i = 0; i < edgesMap.size(); i++) { Integer key = Integer.valueOf(i); PairIntArray v = edgesMap.get(key); assert(v != null); output.add(v); } return output; } private void printJunctions(List<PairIntArray> edges) { printJunctions(this.junctionMap, edges); } private void printJunctions(Map<Integer, Set<Integer>> jMap, List<PairIntArray> edges) { try { Image img2 = img.copyImageToGreen(); ImageIOHelper.addAlternatingColorCurvesToImage(edges, img2); int nExtraForDot = 1; int rClr = 255; int gClr = 0; int bClr = 100; for (Entry<Integer, Set<Integer>> entry : jMap.entrySet()) { int pixIdx = entry.getKey().intValue(); int col = img2.getCol(pixIdx); int row = img2.getRow(pixIdx); ImageIOHelper.addPointToImage(col, row, img2, nExtraForDot, rClr, gClr, bClr); } String dirPath = algorithms.util.ResourceFinder.findDirectory("bin"); String sep = System.getProperty("file.separator"); ImageIOHelper.writeOutputImage(dirPath + sep + "junctions.png", img2); } catch (IOException e) { } } private String printJunctionsToString(Map<Integer, Set<Integer>> jMap, List<PairIntArray> edges) { StringBuilder sb = new StringBuilder("junctions:\n"); for (Entry<Integer, Set<Integer>> entry : jMap.entrySet()) { int pixIdx = entry.getKey().intValue(); int col = img.getCol(pixIdx); int row = img.getRow(pixIdx); sb.append(String.format("%d (%d,%d)\n", pixIdx, col, row)); } return sb.toString(); } private String printJunctionsToString( Map<Integer, PairInt> jLocationMap, Map<Integer, Set<Integer>> jMap, List<PairIntArray> edges) { StringBuilder sb = new StringBuilder("junctions:\n"); for (Entry<Integer, Set<Integer>> entry : jMap.entrySet()) { int pixIdx = entry.getKey().intValue(); int col = img.getCol(pixIdx); int row = img.getRow(pixIdx); sb.append(String.format("%d (%d,%d)\n", pixIdx, col, row)); } sb.append("junction locations:\n"); for (Entry<Integer, PairInt> entry : jLocationMap.entrySet()) { Integer pixelIndex = entry.getKey(); PairInt loc = entry.getValue(); int edgeIdx = loc.getX(); int indexWithinEdge = loc.getY(); int edgeN = edges.get(edgeIdx).getN(); int x = edges.get(edgeIdx).getX(indexWithinEdge); int y = edges.get(edgeIdx).getY(indexWithinEdge); sb.append(String.format("edge=%d idx=%d (out of %d) pixIdx=%d (%d,%d)\n", edgeIdx, indexWithinEdge, edgeN, pixelIndex.intValue(), x, y)); }//edgeIdx=49 indexWithinEdge=28 return sb.toString(); } /** * If pointEdgeLocation is near the beginning or end of edge, * swap it with the point that is the endpoint and update the given * data structures with the updated information. * @param pointEdgeLocation * @param edge * @return 1 for did re-order, 0 for no need to re-order, else -1 for cannot * re-order */ private int reorderIfNearEnd(PairInt pointEdgeLocation, PairIntArray edge, PairInt connectingEdgeLocation, PairIntArray connectingEdge) { int n = edge.getN(); if ((pointEdgeLocation.getY() == 0) || (pointEdgeLocation.getY() == (n - 1))) { return 0; } /* looks like max offset from end is 2 @ . [....] @ . . [....] */ if ((pointEdgeLocation.getY() > 2) && (pointEdgeLocation.getY() < (n - 3))) { return 0; } int idxOrig = pointEdgeLocation.getY(); int idxSwap; if (idxOrig == 1) { idxSwap = 0; } else if (idxOrig == (n - 2)) { idxSwap = n - 1; } else { /* can just swap it with first or last point if the swapped point is adjacent to the point right before the point to be swapped, in other words, does not break a connection in the edge */ if (idxOrig == 2) { idxSwap = 0; } else { idxSwap = n - 1; } int prevX = edge.getX(idxOrig - 1); int prevY = edge.getY(idxOrig - 1); int endX = edge.getX(0); int endY = edge.getY(0); if ((Math.abs(prevX - endX) > 1) || (Math.abs(prevY - endY) > 1)) { return -1; } } /* if swap position is still adjacent to the connecting point, can complete the change. */ int connectedX = connectingEdge.getX(connectingEdgeLocation.getY()); int connectedY = connectingEdge.getY(connectingEdgeLocation.getY()); int swapX = edge.getX(idxSwap); int swapY = edge.getY(idxSwap); if ((Math.abs(connectedX - swapX) > 1) || (Math.abs(connectedY - swapY) > 1)) { return -1; } pointEdgeLocation.setY(idxSwap); return 1; } private void spliceEdgesAtJunctionsIfImproves(List<PairIntArray> edges) { /* The main goal is to make better contours. Edges with junctions can sometimes be spliced and rejoined with another junction edge to make a better edge where better edge may be a longer edge or a closed contour useful for determining transformations between images containing the contour. could be used with shape templates... For now, will make a simple algorithm which tries to increase the length of the longest edges in a junction. */ // key = edge index. // value = pixel indexes. // the pixel indexes are used to find values in junctionLocatorMap // to update it as points are moved to and from edges. Map<Integer, Set<Integer>> theEdgeToPixelIndexMap = new HashMap<Integer, Set<Integer>>(); for (Entry<Integer, PairInt> entry : junctionLocationMap.entrySet()) { Integer pixelIndex = entry.getKey(); PairInt loc = entry.getValue(); Integer edgeIndex = Integer.valueOf(loc.getX()); Set<Integer> pixelIndexes = theEdgeToPixelIndexMap.get(edgeIndex); if (pixelIndexes == null) { pixelIndexes = new HashSet<Integer>(); } pixelIndexes.add(pixelIndex); theEdgeToPixelIndexMap.put(edgeIndex, pixelIndexes); } if (debug) { assertConsistentEdgeCapacity(theEdgeToPixelIndexMap, junctionLocationMap, junctionMap, edges); } for (Entry<Integer, Set<Integer>> entry : junctionMap.entrySet()) { Integer centerPixelIndex = entry.getKey(); PairInt centerLoc = junctionLocationMap.get(centerPixelIndex); assert(centerLoc != null); Set<Integer> adjIndexes = entry.getValue(); int[] pixIndexes = new int[adjIndexes.size() + 1]; // lengths holds the edge up until the junction. splices the edge // at the junction figuratively and counts number of pixels before // and after splice and keeps the longest. int[] lengths = new int[pixIndexes.length]; pixIndexes[0] = centerPixelIndex.intValue(); lengths[0] = (new Splice(edges.get(centerLoc.getX()))) .getLengthOfLongestSide(centerLoc.getY()); int maxN = lengths[0]; int count = 1; for (Integer pixIndex : adjIndexes) { pixIndexes[count] = pixIndex.intValue(); PairInt loc = junctionLocationMap.get(pixIndex); if ((centerLoc.getX() == loc.getX())) { count++; continue; } lengths[count] = (new Splice(edges.get(loc.getX()))) .getLengthOfLongestSide(loc.getY()); if (lengths[count] > maxN) { maxN = lengths[count]; } count++; } if ((maxN > lengths.length) || (maxN > 10000000)) { MultiArrayMergeSort.sortByDecr(lengths, pixIndexes); } else { CountingSort.sortByDecr(lengths, pixIndexes, maxN); } int pixIdx0 = pixIndexes[0]; int pixIdx1 = pixIndexes[1]; PairInt loc0 = junctionLocationMap.get(Integer.valueOf(pixIdx0)); final int edge0Idx = loc0.getX(); final int indexWithinEdge0 = loc0.getY(); PairInt loc1 = junctionLocationMap.get(Integer.valueOf(pixIdx1)); final int edge1Idx = loc1.getX(); final int indexWithinEdge1 = loc1.getY(); if (edge0Idx != edge1Idx && (lengths[0] != 0) && (lengths[1] != 0)) { Set<Integer> edgePixelIndexes = theEdgeToPixelIndexMap.get(Integer.valueOf(edge0Idx)); assert(edgePixelIndexes != null); int[] splice0Y = new int[]{indexWithinEdge0}; Splice splice0 = new Splice(edges.get(edge0Idx)); Map<Integer, PairInt> smallerSpliceLocations0 = new HashMap<Integer, PairInt>(); Map<Integer, PairInt> largerSpliceLocations0 = new HashMap<Integer, PairInt>(); // splice splice0 into 2 edges and put updated i PairIntArray[] spliced0 = splice0.splice(splice0Y, edgePixelIndexes, junctionLocationMap, smallerSpliceLocations0, largerSpliceLocations0); int[] splice1Y = new int[]{indexWithinEdge1}; Splice splice1 = new Splice(edges.get(edge1Idx)); edgePixelIndexes = theEdgeToPixelIndexMap.get(Integer.valueOf(edge1Idx)); assert(edgePixelIndexes != null); Map<Integer, PairInt> smallerSpliceLocations1 = new HashMap<Integer, PairInt>(); Map<Integer, PairInt> largerSpliceLocations1 = new HashMap<Integer, PairInt>(); PairIntArray[] spliced1 = splice1.splice(splice1Y, edgePixelIndexes, junctionLocationMap, smallerSpliceLocations1, largerSpliceLocations1); // if not spliced, continue. if ((spliced0[0].getN() == 0) || (spliced1[0].getN() == 0)) { continue; } int splice01InsertedIdx = edges.size(); // add the smaller part of spliced0 and spliced1 to edges edges.add(spliced0[1]); int splice11InsertedIdx = edges.size(); edges.add(spliced1[1]); int splice00N = spliced0[0].getN(); int splice10N = spliced1[0].getN(); // if splice0Y[0] is first point, reverse the edge before append if (splice0Y[0] == 0) { spliced0[0].reverse(); splice0Y[0] = splice00N - 1; for (Entry<Integer, PairInt> sEntry : largerSpliceLocations0.entrySet()) { PairInt sLoc = sEntry.getValue(); int idxRev = splice00N - sLoc.getY() - 1; sLoc.setY(idxRev); assert(idxRev < splice00N); } } // if splice1Y[0] is not the first point, reverse the edge before append if (splice1Y[0] != 0) { spliced1[0].reverse(); splice1Y[0] = 0; for (Entry<Integer, PairInt> sEntry : largerSpliceLocations1.entrySet()) { PairInt sLoc = sEntry.getValue(); int idxRev = splice10N - sLoc.getY() - 1; sLoc.setY(idxRev); assert(idxRev < splice10N); } } // append splice1 to splice0 spliced0[0].addAll(spliced1[0]); PairIntArray edge0 = edges.get(edge0Idx); edge0.swapContents(spliced0[0]); spliced0[0] = null; for (Entry<Integer, PairInt> sEntry : largerSpliceLocations0.entrySet()) { Integer sPixelIndex = sEntry.getKey(); PairInt sLoc = sEntry.getValue(); PairInt loc = junctionLocationMap.get(sPixelIndex); assert (loc != null); // edge index remains same, but the index within edge may have changed loc.setY(sLoc.getY()); assert(sLoc.getY() < edge0.getN()); } for (Entry<Integer, PairInt> sEntry : smallerSpliceLocations0.entrySet()) { Integer sPixelIndex = sEntry.getKey(); PairInt sLoc = sEntry.getValue(); PairInt loc = junctionLocationMap.get(sPixelIndex); assert (loc != null); // location is new edge with edited index within edge loc.setX(splice01InsertedIdx); loc.setY(sLoc.getY()); //-- move item from theEdgeToPixelIndexMap too //-- remove sPixelIndex from edge loc0.getX() and add it to splice01InsertedIdx Set<Integer> sPixelIndexes = theEdgeToPixelIndexMap.get(Integer.valueOf(edge0Idx)); boolean removed = sPixelIndexes.remove(sPixelIndex); assert(removed == true); sPixelIndexes = theEdgeToPixelIndexMap.get(Integer.valueOf(splice01InsertedIdx)); if (sPixelIndexes == null) { sPixelIndexes = new HashSet<Integer>(); } sPixelIndexes.add(sPixelIndex); theEdgeToPixelIndexMap.put(Integer.valueOf(splice01InsertedIdx), sPixelIndexes); } for (Entry<Integer, PairInt> sEntry : smallerSpliceLocations1.entrySet()) { Integer sPixelIndex = sEntry.getKey(); PairInt sLoc = sEntry.getValue(); PairInt loc = junctionLocationMap.get(sPixelIndex); assert (loc != null); // location is new edge with edited index within edge loc.setX(splice11InsertedIdx); loc.setY(sLoc.getY()); //-- move item from theEdgeToPixelIndexMap too //-- remove sPixelIndex from edge loc1.getX() and add it to splice11InsertedIdx Set<Integer> sPixelIndexes = theEdgeToPixelIndexMap.get(Integer.valueOf(edge1Idx)); boolean removed = sPixelIndexes.remove(sPixelIndex); assert(removed == true); theEdgeToPixelIndexMap.put(Integer.valueOf(edge1Idx), sPixelIndexes); sPixelIndexes = theEdgeToPixelIndexMap.get(Integer.valueOf(splice11InsertedIdx)); if (sPixelIndexes == null) { sPixelIndexes = new HashSet<Integer>(); } sPixelIndexes.add(sPixelIndex); theEdgeToPixelIndexMap.put(Integer.valueOf(splice11InsertedIdx), sPixelIndexes); } for (Entry<Integer, PairInt> sEntry : largerSpliceLocations1.entrySet()) { Integer sPixelIndex = sEntry.getKey(); PairInt sLoc = sEntry.getValue(); PairInt loc = junctionLocationMap.get(sPixelIndex); assert (loc != null); // location after append is loc0.getX() with offset of splice00N loc.setX(edge0Idx); loc.setY(sLoc.getY() + splice00N); assert(loc.getY() < edge0.getN()); //-- move item from theEdgeToPixelIndexMap too //-- remove sPixelIndex from edge loc1.getX() and add it to loc0.getX() Integer key = Integer.valueOf(edge1Idx); Set<Integer> sPixelIndexes = theEdgeToPixelIndexMap.get(key); boolean removed = sPixelIndexes.remove(sPixelIndex); assert(removed == true); theEdgeToPixelIndexMap.put(key, sPixelIndexes); key = Integer.valueOf(edge0Idx); sPixelIndexes = theEdgeToPixelIndexMap.get(key); if (sPixelIndexes == null) { sPixelIndexes = new HashSet<Integer>(); } sPixelIndexes.add(sPixelIndex); theEdgeToPixelIndexMap.put(key, sPixelIndexes); } // remove edge1Idx from edges as it's now part of edge edge0Idx PairIntArray removedEdge = edges.remove(edge1Idx); assert(removedEdge != null); if (debug) { // assert that theEdgeToPixelIndexMap does not have any // entries for the edge that was just removed. // all entries in theEdgeToPixelIndexMap and the junction // maps should have been updated above for edge1Idx Set<Integer> pixelIndexes = theEdgeToPixelIndexMap.get(edge1Idx); assert(pixelIndexes == null || pixelIndexes.isEmpty()); } /* 0 0 ... 49 49 50 <-- rm prev 51, now 50. 51 */ for (int eIdx = (edge1Idx + 1); eIdx <= edges.size(); ++eIdx) { Integer edgeIndex = Integer.valueOf(eIdx); Set<Integer> pixelIndexes = theEdgeToPixelIndexMap.get(edgeIndex); if (pixelIndexes != null) { for (Integer pixelIndex : pixelIndexes) { PairInt loc = junctionLocationMap.get(pixelIndex); loc.setX(loc.getX() - 1); } theEdgeToPixelIndexMap.remove(edgeIndex); Integer edgeIndexEarlier = Integer.valueOf(eIdx - 1); theEdgeToPixelIndexMap.put(edgeIndexEarlier, pixelIndexes); } } if (debug) { assertConsistentEdgeCapacity(theEdgeToPixelIndexMap, junctionLocationMap, junctionMap, edges); } } } } private void assertConsistentEdgeCapacity( Map<Integer, Set<Integer>> theEdgeToPixelIndexMap, Map<Integer, PairInt> junctionLocationMap, Map<Integer, Set<Integer>> junctionMap, List<PairIntArray> edges) { for (Entry<Integer, PairInt> entry : junctionLocationMap.entrySet()) { Integer pixelIndex = entry.getKey(); assert(pixelIndex != null); PairInt loc = entry.getValue(); int edgeIdx = loc.getX(); int idx = loc.getY(); PairIntArray edge = edges.get(edgeIdx); assert(edge != null); assert (idx < edge.getN()) : "idx=" + idx + " edgeN=" + edge.getN() + " edgeIndex=" + edgeIdx; } for (Entry<Integer, Set<Integer>> entry : junctionMap.entrySet()) { Integer pixelIndex = entry.getKey(); Set<Integer> adjPixelIndexes = entry.getValue(); PairInt loc = junctionLocationMap.get(pixelIndex); assert(loc != null); int edgeIdx = loc.getX(); int idx = loc.getY(); PairIntArray edge = edges.get(edgeIdx); assert(edge != null); assert(idx < edge.getN()); for (Integer adjPixelIndex : adjPixelIndexes) { PairInt adjLoc = junctionLocationMap.get(adjPixelIndex); assert(adjLoc != null); edgeIdx = adjLoc.getX(); idx = adjLoc.getY(); edge = edges.get(edgeIdx); assert(edge != null); assert(idx < edge.getN()); } } for (Entry<Integer, Set<Integer>> entry : theEdgeToPixelIndexMap.entrySet()) { Integer edgeIndex = entry.getKey(); Set<Integer> pixelIndexes = entry.getValue(); PairIntArray edge = edges.get(edgeIndex.intValue()); assert(edge != null); for (Integer pixelIndex : pixelIndexes) { PairInt loc = junctionLocationMap.get(pixelIndex); assert(loc != null); int edgeIdx = loc.getX(); int idx = loc.getY(); assert(edgeIdx == edgeIndex.intValue()); assert(idx < edge.getN()); } } } }
package com.lekebilen.quasseldroid.gui; import java.util.ArrayList; import android.app.ListActivity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import com.lekebilen.quasseldroid.Buffer; import com.lekebilen.quasseldroid.BufferInfo; import com.lekebilen.quasseldroid.R; public class BufferActivity extends ListActivity { public static final String BUFFER_ID_EXTRA = "bufferid"; ArrayList<Buffer> bufferList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.buffer_list); bufferList = new ArrayList<Buffer>(); Buffer test = new Buffer(new BufferInfo()); test.getInfo().name = "#testlolol1"; bufferList.add(test); test = new Buffer(new BufferInfo()); test.getInfo().name = "#testlolol2"; bufferList.add(test); test = new Buffer(new BufferInfo()); test.getInfo().name = "#testlolol3"; bufferList.add(test); test = new Buffer(new BufferInfo()); test.getInfo().name = "#testlolol4"; bufferList.add(test); ListAdapter adapter = new BufferListAdapter(this, bufferList); setListAdapter(adapter); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); Intent i = new Intent(BufferActivity.this, ChatActivity.class); i.putExtra(BUFFER_ID_EXTRA, bufferList.get(position).getInfo().id); startActivity(i); } private class BufferListAdapter extends BaseAdapter { private ArrayList<Buffer> list; private LayoutInflater inflater; public BufferListAdapter(Context context, ArrayList<Buffer> list) { if (list==null) { this.list = new ArrayList<Buffer>(); }else { this.list = list; } inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return list.size(); } @Override public Buffer getItem(int position) { return list.get(position); } @Override public long getItemId(int arg0) { return arg0; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView==null) { convertView = inflater.inflate(R.layout.buffer_list_item, null); holder = new ViewHolder(); holder.bufferView = (TextView)convertView.findViewById(R.id.buffer_list_item_name); convertView.setTag(holder); } else { holder = (ViewHolder)convertView.getTag(); } Buffer entry = list.get(position); holder.bufferView.setText(entry.getInfo().name); //Check here if there are any unread messages in the buffer, and then set this color if there is holder.bufferView.setTextColor(getResources().getColor(R.color.unread_buffer_color)); return convertView; } } public static class ViewHolder { public TextView bufferView; } }
package com.sixsq.slipstream.util; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.EntityManager; import com.sixsq.slipstream.configuration.Configuration; import com.sixsq.slipstream.connector.Connector; import com.sixsq.slipstream.connector.ConnectorFactory; import com.sixsq.slipstream.exceptions.ConfigurationException; import com.sixsq.slipstream.exceptions.SlipStreamException; import com.sixsq.slipstream.exceptions.ValidationException; import com.sixsq.slipstream.metrics.Metrics; import com.sixsq.slipstream.metrics.MetricsTimer; import com.sixsq.slipstream.persistence.Parameter; import com.sixsq.slipstream.persistence.ParameterCategory; import com.sixsq.slipstream.persistence.PersistenceUtil; import com.sixsq.slipstream.persistence.Run; import com.sixsq.slipstream.persistence.User; import com.sixsq.slipstream.persistence.UserParameter; import com.sixsq.slipstream.statemachine.StateMachine; import com.sixsq.slipstream.statemachine.States; public class Terminator { /* I WILL BE BACK */ private static MetricsTimer purgeTimer = Metrics.newTimer(Terminator.class, "purge"); private static final Logger logger = Logger.getLogger(Terminator.class.getName()); private static final String threadInfoFormatStart = "START purge run: %s, username: %s, thread name: %s, thread id: %d"; private static final String threadInfoFormatEnd = "END purge run: %s, username: %s, thread name: %s, thread id: %d"; public static int purge() throws ConfigurationException, ValidationException { // This method has been rewritten to minimize the number of users queried and // the number of times a user object is loaded. int runPurged = 0; purgeTimer.start(); try { List<Run> runs = Run.listAllTransient(); HashMap<String, List<Run>> batchedRuns = new HashMap<>(); for (Run r: runs) { String username = r.getUser(); if (batchedRuns.containsKey(username)) { List<Run> userRuns = batchedRuns.get(username); userRuns.add(r); } else { List<Run> userRuns = new ArrayList<>(); userRuns.add(r); batchedRuns.put(username, userRuns); } } for (String username: batchedRuns.keySet()) { User user = User.loadByName(username); if (user != null) { int timeout = user.getTimeout(); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MINUTE, -timeout); Date timeoutDate = calendar.getTime(); for (Run r : batchedRuns.get(username)) { Date lastStateChange = r.getLastStateChange(); if (lastStateChange.before(timeoutDate)) { EntityManager em = PersistenceUtil.createEntityManager(); logger.log(Level.INFO, String.format(threadInfoFormatStart, r.getUuid(), username, Thread.currentThread().getName(), Thread.currentThread().getId())); try { r = Run.load(r.getResourceUri(), em); purgeRun(r, user); runPurged += 1; } catch (SlipStreamException e) { logger.log(Level.SEVERE, e.getMessage(), e.getCause()); } finally { logger.log(Level.INFO, String.format(threadInfoFormatEnd, r.getUuid(), username, Thread.currentThread().getName(), Thread.currentThread().getId())); em.close(); } } } } else { logger.log(Level.SEVERE, "could not load user " + username + " when trying to purge runs"); } } } finally { purgeTimer.stop(); } return runPurged; } /* This method is expected to be run from within an hibernate context. */ public static void purgeRun(Run run, User user) throws SlipStreamException { Run.abort("The run has timed out", run.getUuid()); boolean isGarbageCollected = Run.isGarbageCollected(run); Run.setGarbageCollected(run); String onErrorKeepRunning = run.getParameterValue(Parameter .constructKey(ParameterCategory.General.toString(), UserParameter.KEY_ON_ERROR_RUN_FOREVER), "false"); if (! Boolean.parseBoolean(onErrorKeepRunning) && ! run.isMutable() && (run.getState() == States.Initializing || isGarbageCollected)) { terminateInsideTransaction(run, user); run.postEventGarbageCollectorTerminated(); } else if (!isGarbageCollected) { run.postEventGarbageCollectorTimedOut(); } } /* This version of the terminate method is expected to run from within a hibernate transactions. You have been warned. */ public static void terminateInsideTransaction(Run run, User user) throws SlipStreamException { StateMachine sc = StateMachine.createStateMachine(run); run.store(); if (sc.canCancel()) { sc.tryAdvanceToCancelled(); terminateInstances(run, user); } else { if (sc.getState() == States.Ready) { sc.tryAdvanceToFinalizing(); } terminateInstances(run, user); sc.tryAdvanceState(true); } } public static void terminate(String runResourceUri) throws SlipStreamException { EntityManager em = PersistenceUtil.createEntityManager(); Run run = Run.load(runResourceUri, em); User user = User.loadByName(run.getUser()); StateMachine sc = StateMachine.createStateMachine(run); if (sc.canCancel()) { sc.tryAdvanceToCancelled(); terminateInstances(run, user); } else { if (sc.getState() == States.Ready) { sc.tryAdvanceToFinalizing(); } terminateInstances(run, user); sc.tryAdvanceState(true); } em.close(); } private static void terminateInstances(Run run, User user) throws SlipStreamException { user.addSystemParametersIntoUser(Configuration.getInstance().getParameters()); for (String cloudServiceName : run.getCloudServiceNamesList()) { Connector connector = ConnectorFactory.getConnector(cloudServiceName); connector.terminate(run, user); } } }
package org.openqa.selenium.qtwebkit; import com.google.common.collect.ImmutableMap; import org.openqa.selenium.remote.Command; import org.openqa.selenium.remote.CommandInfo; import org.openqa.selenium.remote.HttpCommandExecutor; import org.openqa.selenium.remote.HttpVerb; import org.openqa.selenium.remote.Response; import java.io.IOException; import java.net.URL; import java.util.Map; import static org.openqa.selenium.qtwebkit.QtWebKitDriverCommand.*; public class QtWebDriverExecutor extends HttpCommandExecutor { private static final Map<String, CommandInfo> additionalCommands; static { ImmutableMap.Builder<String, CommandInfo> builder = ImmutableMap.builder(); builder.put(GET_PLAYER_STATE, new CommandInfo("/session/:sessionId/element/:id/-cisco-player-element/state", HttpVerb.GET)) .put(SET_PLAYER_STATE, new CommandInfo("/session/:sessionId/element/:id/-cisco-player-element/state", HttpVerb.POST)) .put(GET_PLAYER_VOLUME, new CommandInfo("/session/:sessionId/element/:id/-cisco-player-element/volume", HttpVerb.GET)) .put(SET_PLAYER_VOLUME, new CommandInfo("/session/:sessionId/element/:id/-cisco-player-element/volume", HttpVerb.POST)) .put(GET_CURRENT_PLAYING_POSITION, new CommandInfo("/session/:sessionId/element/:id/-cisco-player-element/seek", HttpVerb.GET)) .put(SET_CURRENT_PLAYING_POSITION, new CommandInfo("/session/:sessionId/element/:id/-cisco-player-element/seek", HttpVerb.POST)) .put(SET_PLAYER_MUTE, new CommandInfo("/session/:sessionId/element/:id/-cisco-player-element/mute", HttpVerb.POST)) .put(GET_PLAYER_MUTE, new CommandInfo("/session/:sessionId/element/:id/-cisco-player-element/mute", HttpVerb.GET)) .put(SET_PLAYBACK_SPEED, new CommandInfo("/session/:sessionId/element/:id/-cisco-player-element/speed", HttpVerb.POST)) .put(GET_PLAYBACK_SPEED, new CommandInfo("/session/:sessionId/element/:id/-cisco-player-element/speed", HttpVerb.GET)) .put(TOUCH_PINCH_ZOOM, new CommandInfo("/session/:sessionId/touch/-cisco-pinch-zoom", HttpVerb.POST)) .put(TOUCH_PINCH_ROTATE, new CommandInfo("/session/:sessionId/touch/-cisco-pinch-rotate", HttpVerb.POST)) .put(GET_VISUALIZER_SOURCE, new CommandInfo("/session/:sessionId/-cisco-visualizer-source", HttpVerb.GET)) .put(GET_VISUALIZER_SHOW_POINT, new CommandInfo("/session/:sessionId/-cisco-visualizer-show-point", HttpVerb.GET)); additionalCommands = builder.build(); } public QtWebDriverExecutor(URL addressOfRemoteServer) { super(additionalCommands, addressOfRemoteServer); } public Response execute(Command command) throws IOException { Response response = super.execute(command); return response; } }
package com.shaubert.contacts; import android.content.Context; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; import com.google.i18n.phonenumbers.NumberParseException; import com.google.i18n.phonenumbers.PhoneNumberUtil; import com.google.i18n.phonenumbers.Phonenumber; import java.util.Locale; public class Phones { public static String formatInternationalPhone(String phone) { return formatInternationalPhone(phone, ""); } public static String formatInternationalPhone(String phone, String defaultRegion) { Phonenumber.PhoneNumber phoneNumber = parseInternationalPhone(phone, defaultRegion); if (phoneNumber == null) { return phone; } return formatInternationalPhone(phoneNumber); } public static String formatInternationalPhone(Phonenumber.PhoneNumber phoneNumber) { return PhoneNumberUtil.getInstance().format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL); } public static String formatE164(Phonenumber.PhoneNumber phoneNumber) { return PhoneNumberUtil.getInstance().format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164); } public static String appendPlusIfNeeded(String phone) { if (TextUtils.isEmpty(phone)) return phone; if (!phone.contains("+")) { phone = "+" + phone.trim(); } return phone; } public static Phonenumber.PhoneNumber parsePhone(String phone, Context context) { return parsePhone(phone, getPossibleRegions(context)); } public static Phonenumber.PhoneNumber parsePhone(String phone, String[] possibleRegions) { if (phone == null) return null; Phonenumber.PhoneNumber phoneNumber; if (phone.startsWith("+")) { phoneNumber = parseInternationalPhone(phone); if (phoneNumber == null) { phoneNumber = parseLocalPhone(phone, possibleRegions); } } else { phoneNumber = parseLocalPhone(phone, possibleRegions); } return phoneNumber; } public static Phonenumber.PhoneNumber parseInternationalPhone(String phone) { return parseInternationalPhone(phone, ""); } public static Phonenumber.PhoneNumber parseInternationalPhone(String phone, String defaultRegion) { phone = appendPlusIfNeeded(phone); if (TextUtils.isEmpty(phone)) return null; PhoneNumberUtil util = PhoneNumberUtil.getInstance(); try { return util.parse(phone, defaultRegion); } catch (NumberParseException ignored) { } return null; } public static Phonenumber.PhoneNumber parseLocalPhone(String phone, Context context) { return parseLocalPhone(phone, getPossibleRegions(context)); } public static String[] getPossibleRegions(Context context) { return new String[] { getRegionFromSim(context), getRegionFromNetwork(context), getRegionFromLocale(), }; } public static Phonenumber.PhoneNumber parseLocalPhone(String phone, String[] possibleRegions) { for (String region : possibleRegions) { if (!TextUtils.isEmpty(region)) { try { Phonenumber.PhoneNumber number = PhoneNumberUtil.getInstance().parse(phone, region.toUpperCase()); if (PhoneNumberUtil.getInstance().isValidNumber(number)) { return number; } } catch (NumberParseException ignored) { Log.e("!!!", "!!!", ignored); } } } return null; } public static String getRegionFromSim(Context context) { try { TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); return manager.getSimCountryIso(); } catch (Exception ignored) { } return null; } public static String getRegionFromNetwork(Context context) { try { TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); return manager.getNetworkCountryIso(); } catch (Exception ignored) { } return null; } public static String getRegionFromLocale() { return Locale.getDefault().getCountry(); } public static String leaveOnlyDigits(String phone) { if (TextUtils.isEmpty(phone)) return phone; return PhoneNumberUtil.normalizeDigitsOnly(phone); } public static String leaveOnlyDigitsAndPlus(String phone) { if (TextUtils.isEmpty(phone)) return phone; boolean hasPlus = phone.startsWith("+"); String digitsOnly = PhoneNumberUtil.normalizeDigitsOnly(phone); return hasPlus ? ("+" + digitsOnly) : digitsOnly; } }
package com.maddyhome.idea.vim.ex.handler; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.LogicalPosition; import com.intellij.openapi.editor.SelectionModel; import com.intellij.openapi.util.text.StringUtil; import com.maddyhome.idea.vim.VimPlugin; import com.maddyhome.idea.vim.ex.CommandHandler; import com.maddyhome.idea.vim.ex.ExCommand; import com.maddyhome.idea.vim.ex.ExException; import com.maddyhome.idea.vim.ex.LineRange; import org.jetbrains.annotations.NotNull; import java.util.Comparator; /** * @author Alex Selesse */ public class SortHandler extends CommandHandler { public SortHandler() { super("sor", "t", RANGE_OPTIONAL | ARGUMENT_OPTIONAL | WRITABLE); } @Override public boolean execute(@NotNull Editor editor, @NotNull DataContext context, @NotNull ExCommand cmd) throws ExException { final String arg = cmd.getArgument(); final boolean nonEmptyArg = arg.trim().length() > 0; final boolean reverse = nonEmptyArg && arg.contains("!"); final boolean ignoreCase = nonEmptyArg && arg.contains("i"); final boolean number = nonEmptyArg && arg.contains("n"); final LineRange range = getLineRange(editor, context, cmd); final Comparator<String> lineComparator = new VimLineComparator(ignoreCase, number, reverse); return VimPlugin.getChange().sortRange(editor, range, lineComparator); } @NotNull private LineRange getLineRange(@NotNull Editor editor, @NotNull DataContext context, @NotNull ExCommand cmd) { final LineRange range = cmd.getLineRange(editor, context, false); final LineRange normalizedRange; // Something like "30,20sort" gets converted to "20,30sort" if (range.getEndLine() < range.getStartLine()) { normalizedRange = new LineRange(range.getEndLine(), range.getStartLine()); } else { normalizedRange = range; } // If we don't have a range, we either have "sort", a selection, or a block if (normalizedRange.getEndLine() - normalizedRange.getStartLine() == 0) { // If we have a selection. final SelectionModel selectionModel = editor.getSelectionModel(); if (selectionModel.hasSelection()) { final int start = selectionModel.getSelectionStart(); final int end = selectionModel.getSelectionEnd(); final int startLine = editor.offsetToLogicalPosition(start).line; final int endLine = editor.offsetToLogicalPosition(end).line; return new LineRange(startLine, endLine); } // If we have a block selection else if (selectionModel.hasBlockSelection()) { final LogicalPosition blockStart = selectionModel.getBlockStart(); final LogicalPosition blockEnd = selectionModel.getBlockEnd(); if (blockStart != null && blockEnd != null) { return new LineRange(blockStart.line, blockEnd.line); } } // If we have a generic selection, i.e. "sort" entire document else { return new LineRange(0, editor.getDocument().getLineCount() - 1); } } return normalizedRange; } private static class VimLineComparator implements Comparator<String> { private final boolean myIgnoreCase; private final boolean myNumber; private final boolean myReverse; public VimLineComparator(boolean ignoreCase, boolean number, boolean reverse) { myIgnoreCase = ignoreCase; myNumber = number; myReverse = reverse; } @Override public int compare(String o1, String o2) { if (myReverse) { final String tmp = o2; o2 = o1; o1 = tmp; } if (myIgnoreCase) { o1 = o1.toUpperCase(); o2 = o2.toUpperCase(); } return myNumber ? StringUtil.naturalCompare(o1, o2) : o1.compareTo(o2); } } }
package com.chariotsolutions.nfc.plugin; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; // using wildcard imports so we can support Cordova 3.x import org.apache.cordova.*; // Cordova 3.x import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; import android.content.IntentFilter; import android.content.IntentFilter.MalformedMimeTypeException; import android.net.Uri; import android.nfc.FormatException; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.nfc.NfcEvent; import android.nfc.Tag; import android.nfc.TagLostException; import android.nfc.tech.Ndef; import android.nfc.tech.NdefFormatable; import android.nfc.tech.TagTechnology; import android.os.Bundle; import android.os.Parcelable; import android.util.Log; public class NfcPlugin extends CordovaPlugin implements NfcAdapter.OnNdefPushCompleteCallback { private static final String REGISTER_MIME_TYPE = "registerMimeType"; private static final String REMOVE_MIME_TYPE = "removeMimeType"; private static final String REGISTER_NDEF = "registerNdef"; private static final String REMOVE_NDEF = "removeNdef"; private static final String REGISTER_NDEF_FORMATABLE = "registerNdefFormatable"; private static final String REGISTER_DEFAULT_TAG = "registerTag"; private static final String REMOVE_DEFAULT_TAG = "removeTag"; private static final String WRITE_TAG = "writeTag"; private static final String MAKE_READ_ONLY = "makeReadOnly"; private static final String ERASE_TAG = "eraseTag"; private static final String SHARE_TAG = "shareTag"; private static final String UNSHARE_TAG = "unshareTag"; private static final String HANDOVER = "handover"; // Android Beam private static final String STOP_HANDOVER = "stopHandover"; private static final String ENABLED = "enabled"; private static final String INIT = "init"; private static final String SHOW_SETTINGS = "showSettings"; private static final String NDEF = "ndef"; private static final String NDEF_MIME = "ndef-mime"; private static final String NDEF_FORMATABLE = "ndef-formatable"; private static final String TAG_DEFAULT = "tag"; private static final String READER_MODE = "readerMode"; private static final String DISABLE_READER_MODE = "disableReaderMode"; // TagTechnology IsoDep, NfcA, NfcB, NfcV, NfcF, MifareClassic, MifareUltralight private static final String CONNECT = "connect"; private static final String CLOSE = "close"; private static final String TRANSCEIVE = "transceive"; private TagTechnology tagTechnology = null; private Class<?> tagTechnologyClass; private static final String CHANNEL = "channel"; private static final String STATUS_NFC_OK = "NFC_OK"; private static final String STATUS_NO_NFC = "NO_NFC"; private static final String STATUS_NFC_DISABLED = "NFC_DISABLED"; private static final String STATUS_NDEF_PUSH_DISABLED = "NDEF_PUSH_DISABLED"; private static final String TAG = "NfcPlugin"; private final List<IntentFilter> intentFilters = new ArrayList<>(); private final ArrayList<String[]> techLists = new ArrayList<>(); private NdefMessage p2pMessage = null; private PendingIntent pendingIntent = null; private Intent savedIntent = null; private CallbackContext readerModeCallback; private CallbackContext channelCallback; private CallbackContext shareTagCallback; private CallbackContext handoverCallback; @Override public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException { Log.d(TAG, "execute " + action); // showSettings can be called if NFC is disabled // might want to skip this if NO_NFC if (action.equalsIgnoreCase(SHOW_SETTINGS)) { showSettings(callbackContext); return true; } // the channel is set up when the plugin starts if (action.equalsIgnoreCase(CHANNEL)) { channelCallback = callbackContext; return true; // short circuit } // allow reader mode to be disabled even if nfc is disabled if (action.equalsIgnoreCase(DISABLE_READER_MODE)) { disableReaderMode(callbackContext); return true; // short circuit } if (!getNfcStatus().equals(STATUS_NFC_OK)) { callbackContext.error(getNfcStatus()); return true; // short circuit } createPendingIntent(); if (action.equalsIgnoreCase(READER_MODE)) { int flags = data.getInt(0); readerMode(flags, callbackContext); } else if (action.equalsIgnoreCase(REGISTER_MIME_TYPE)) { registerMimeType(data, callbackContext); } else if (action.equalsIgnoreCase(REMOVE_MIME_TYPE)) { removeMimeType(data, callbackContext); } else if (action.equalsIgnoreCase(REGISTER_NDEF)) { registerNdef(callbackContext); } else if (action.equalsIgnoreCase(REMOVE_NDEF)) { removeNdef(callbackContext); } else if (action.equalsIgnoreCase(REGISTER_NDEF_FORMATABLE)) { registerNdefFormatable(callbackContext); } else if (action.equals(REGISTER_DEFAULT_TAG)) { registerDefaultTag(callbackContext); } else if (action.equals(REMOVE_DEFAULT_TAG)) { removeDefaultTag(callbackContext); } else if (action.equalsIgnoreCase(WRITE_TAG)) { writeTag(data, callbackContext); } else if (action.equalsIgnoreCase(MAKE_READ_ONLY)) { makeReadOnly(callbackContext); } else if (action.equalsIgnoreCase(ERASE_TAG)) { eraseTag(callbackContext); } else if (action.equalsIgnoreCase(SHARE_TAG)) { shareTag(data, callbackContext); } else if (action.equalsIgnoreCase(UNSHARE_TAG)) { unshareTag(callbackContext); } else if (action.equalsIgnoreCase(HANDOVER)) { handover(data, callbackContext); } else if (action.equalsIgnoreCase(STOP_HANDOVER)) { stopHandover(callbackContext); } else if (action.equalsIgnoreCase(INIT)) { init(callbackContext); } else if (action.equalsIgnoreCase(ENABLED)) { // status is checked before every call // if code made it here, NFC is enabled callbackContext.success(STATUS_NFC_OK); } else if (action.equalsIgnoreCase(CONNECT)) { String tech = data.getString(0); int timeout = data.optInt(1, -1); connect(tech, timeout, callbackContext); } else if (action.equalsIgnoreCase(TRANSCEIVE)) { CordovaArgs args = new CordovaArgs(data); // execute is using the old signature with JSON data byte[] command = args.getArrayBuffer(0); transceive(command, callbackContext); } else if (action.equalsIgnoreCase(CLOSE)) { close(callbackContext); } else { // invalid action return false; } return true; } private String getNfcStatus() { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); if (nfcAdapter == null) { return STATUS_NO_NFC; } else if (!nfcAdapter.isEnabled()) { return STATUS_NFC_DISABLED; } else { return STATUS_NFC_OK; } } private void readerMode(int flags, CallbackContext callbackContext) { Bundle extras = new Bundle(); // not used readerModeCallback = callbackContext; getActivity().runOnUiThread(() -> { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); nfcAdapter.enableReaderMode(getActivity(), callback, flags, extras); }); } private void disableReaderMode(CallbackContext callbackContext) { getActivity().runOnUiThread(() -> { readerModeCallback = null; NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); if (nfcAdapter != null) { nfcAdapter.disableReaderMode(getActivity()); } callbackContext.success(); }); } private NfcAdapter.ReaderCallback callback = new NfcAdapter.ReaderCallback() { @Override public void onTagDiscovered(Tag tag) { JSONObject json; // If the tag supports Ndef, try and return an Ndef message List<String> techList = Arrays.asList(tag.getTechList()); if (techList.contains(Ndef.class.getName())) { Ndef ndef = Ndef.get(tag); json = Util.ndefToJSON(ndef); } else { json = Util.tagToJSON(tag); } PluginResult result = new PluginResult(PluginResult.Status.OK, json); result.setKeepCallback(true); readerModeCallback.sendPluginResult(result); } }; private void registerDefaultTag(CallbackContext callbackContext) { addTagFilter(); restartNfc(); callbackContext.success(); } private void removeDefaultTag(CallbackContext callbackContext) { removeTagFilter(); restartNfc(); callbackContext.success(); } private void registerNdefFormatable(CallbackContext callbackContext) { addTechList(new String[]{NdefFormatable.class.getName()}); restartNfc(); callbackContext.success(); } private void registerNdef(CallbackContext callbackContext) { addTechList(new String[]{Ndef.class.getName()}); restartNfc(); callbackContext.success(); } private void removeNdef(CallbackContext callbackContext) { removeTechList(new String[]{Ndef.class.getName()}); restartNfc(); callbackContext.success(); } private void unshareTag(CallbackContext callbackContext) { p2pMessage = null; stopNdefPush(); shareTagCallback = null; callbackContext.success(); } private void init(CallbackContext callbackContext) { Log.d(TAG, "Enabling plugin " + getIntent()); startNfc(); if (!recycledIntent()) { parseMessage(); } callbackContext.success(); } private void removeMimeType(JSONArray data, CallbackContext callbackContext) throws JSONException { String mimeType = data.getString(0); removeIntentFilter(mimeType); restartNfc(); callbackContext.success(); } private void registerMimeType(JSONArray data, CallbackContext callbackContext) throws JSONException { String mimeType = ""; try { mimeType = data.getString(0); intentFilters.add(createIntentFilter(mimeType)); restartNfc(); callbackContext.success(); } catch (MalformedMimeTypeException e) { callbackContext.error("Invalid MIME Type " + mimeType); } } // Cheating and writing an empty record. We may actually be able to erase some tag types. private void eraseTag(CallbackContext callbackContext) { Tag tag = savedIntent.getParcelableExtra(NfcAdapter.EXTRA_TAG); NdefRecord[] records = { new NdefRecord(NdefRecord.TNF_EMPTY, new byte[0], new byte[0], new byte[0]) }; writeNdefMessage(new NdefMessage(records), tag, callbackContext); } private void writeTag(JSONArray data, CallbackContext callbackContext) throws JSONException { if (getIntent() == null) { // TODO remove this and handle LostTag callbackContext.error("Failed to write tag, received null intent"); } Tag tag = savedIntent.getParcelableExtra(NfcAdapter.EXTRA_TAG); NdefRecord[] records = Util.jsonToNdefRecords(data.getString(0)); writeNdefMessage(new NdefMessage(records), tag, callbackContext); } private void writeNdefMessage(final NdefMessage message, final Tag tag, final CallbackContext callbackContext) { cordova.getThreadPool().execute(() -> { try { Ndef ndef = Ndef.get(tag); if (ndef != null) { ndef.connect(); if (ndef.isWritable()) { int size = message.toByteArray().length; if (ndef.getMaxSize() < size) { callbackContext.error("Tag capacity is " + ndef.getMaxSize() + " bytes, message is " + size + " bytes."); } else { ndef.writeNdefMessage(message); callbackContext.success(); } } else { callbackContext.error("Tag is read only"); } ndef.close(); } else { NdefFormatable formatable = NdefFormatable.get(tag); if (formatable != null) { formatable.connect(); formatable.format(message); callbackContext.success(); formatable.close(); } else { callbackContext.error("Tag doesn't support NDEF"); } } } catch (FormatException e) { callbackContext.error(e.getMessage()); } catch (TagLostException e) { callbackContext.error(e.getMessage()); } catch (IOException e) { callbackContext.error(e.getMessage()); } }); } private void makeReadOnly(final CallbackContext callbackContext) { if (getIntent() == null) { // Lost Tag callbackContext.error("Failed to make tag read only, received null intent"); return; } final Tag tag = savedIntent.getParcelableExtra(NfcAdapter.EXTRA_TAG); if (tag == null) { callbackContext.error("Failed to make tag read only, tag is null"); return; } cordova.getThreadPool().execute(() -> { boolean success = false; String message = "Could not make tag read only"; Ndef ndef = Ndef.get(tag); try { if (ndef != null) { ndef.connect(); if (!ndef.isWritable()) { message = "Tag is not writable"; } else if (ndef.canMakeReadOnly()) { success = ndef.makeReadOnly(); } else { message = "Tag can not be made read only"; } } else { message = "Tag is not NDEF"; } } catch (IOException e) { Log.e(TAG, "Failed to make tag read only", e); if (e.getMessage() != null) { message = e.getMessage(); } else { message = e.toString(); } } if (success) { callbackContext.success(); } else { callbackContext.error(message); } }); } private void shareTag(JSONArray data, CallbackContext callbackContext) throws JSONException { NdefRecord[] records = Util.jsonToNdefRecords(data.getString(0)); this.p2pMessage = new NdefMessage(records); startNdefPush(callbackContext); } // setBeamPushUris // Every Uri you provide must have either scheme 'file' or scheme 'content'. // Note that this takes priority over setNdefPush // See http://developer.android.com/reference/android/nfc/NfcAdapter.html#setBeamPushUris(android.net.Uri[],%20android.app.Activity) private void handover(JSONArray data, CallbackContext callbackContext) throws JSONException { Uri[] uri = new Uri[data.length()]; for (int i = 0; i < data.length(); i++) { uri[i] = Uri.parse(data.getString(i)); } startNdefBeam(callbackContext, uri); } private void stopHandover(CallbackContext callbackContext) { stopNdefBeam(); handoverCallback = null; callbackContext.success(); } private void showSettings(CallbackContext callbackContext) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) { Intent intent = new Intent(android.provider.Settings.ACTION_NFC_SETTINGS); getActivity().startActivity(intent); } else { Intent intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS); getActivity().startActivity(intent); } callbackContext.success(); } private void createPendingIntent() { if (pendingIntent == null) { Activity activity = getActivity(); Intent intent = new Intent(activity, activity.getClass()); intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); pendingIntent = PendingIntent.getActivity(activity, 0, intent, 0); } } private void addTechList(String[] list) { this.addTechFilter(); this.addToTechList(list); } private void removeTechList(String[] list) { this.removeTechFilter(); this.removeFromTechList(list); } private void addTechFilter() { intentFilters.add(new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED)); } private void removeTechFilter() { Iterator<IntentFilter> iterator = intentFilters.iterator(); while (iterator.hasNext()) { IntentFilter intentFilter = iterator.next(); if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intentFilter.getAction(0))) { iterator.remove(); } } } private void addTagFilter() { intentFilters.add(new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED)); } private void removeTagFilter() { Iterator<IntentFilter> iterator = intentFilters.iterator(); while (iterator.hasNext()) { IntentFilter intentFilter = iterator.next(); if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intentFilter.getAction(0))) { iterator.remove(); } } } private void restartNfc() { stopNfc(); startNfc(); } private void startNfc() { createPendingIntent(); // onResume can call startNfc before execute getActivity().runOnUiThread(() -> { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); if (nfcAdapter != null && !getActivity().isFinishing()) { try { IntentFilter[] intentFilters = getIntentFilters(); String[][] techLists = getTechLists(); // don't start NFC unless some intent filters or tech lists have been added, // because empty lists act as wildcards and receives ALL scan events if (intentFilters.length > 0 || techLists.length > 0) { nfcAdapter.enableForegroundDispatch(getActivity(), getPendingIntent(), intentFilters, techLists); } if (p2pMessage != null) { nfcAdapter.setNdefPushMessage(p2pMessage, getActivity()); } } catch (IllegalStateException e) { // issue 110 - user exits app with home button while nfc is initializing Log.w(TAG, "Illegal State Exception starting NFC. Assuming application is terminating."); } } }); } private void stopNfc() { Log.d(TAG, "stopNfc"); getActivity().runOnUiThread(() -> { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); if (nfcAdapter != null) { try { nfcAdapter.disableForegroundDispatch(getActivity()); } catch (IllegalStateException e) { // issue 125 - user exits app with back button while nfc Log.w(TAG, "Illegal State Exception stopping NFC. Assuming application is terminating."); } } }); } private void startNdefBeam(final CallbackContext callbackContext, final Uri[] uris) { getActivity().runOnUiThread(() -> { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); if (nfcAdapter == null) { callbackContext.error(STATUS_NO_NFC); } else if (!nfcAdapter.isNdefPushEnabled()) { callbackContext.error(STATUS_NDEF_PUSH_DISABLED); } else { nfcAdapter.setOnNdefPushCompleteCallback(NfcPlugin.this, getActivity()); try { nfcAdapter.setBeamPushUris(uris, getActivity()); PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); result.setKeepCallback(true); handoverCallback = callbackContext; callbackContext.sendPluginResult(result); } catch (IllegalArgumentException e) { callbackContext.error(e.getMessage()); } } }); } private void startNdefPush(final CallbackContext callbackContext) { getActivity().runOnUiThread(() -> { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); if (nfcAdapter == null) { callbackContext.error(STATUS_NO_NFC); } else if (!nfcAdapter.isNdefPushEnabled()) { callbackContext.error(STATUS_NDEF_PUSH_DISABLED); } else { nfcAdapter.setNdefPushMessage(p2pMessage, getActivity()); nfcAdapter.setOnNdefPushCompleteCallback(NfcPlugin.this, getActivity()); PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); result.setKeepCallback(true); shareTagCallback = callbackContext; callbackContext.sendPluginResult(result); } }); } private void stopNdefPush() { getActivity().runOnUiThread(() -> { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); if (nfcAdapter != null) { nfcAdapter.setNdefPushMessage(null, getActivity()); } }); } private void stopNdefBeam() { getActivity().runOnUiThread(() -> { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); if (nfcAdapter != null) { nfcAdapter.setBeamPushUris(null, getActivity()); } }); } private void addToTechList(String[] techs) { techLists.add(techs); } private void removeFromTechList(String[] techs) { Iterator<String[]> iterator = techLists.iterator(); while (iterator.hasNext()) { String[] list = iterator.next(); if (Arrays.equals(list, techs)) { iterator.remove(); } } } private void removeIntentFilter(String mimeType) { Iterator<IntentFilter> iterator = intentFilters.iterator(); while (iterator.hasNext()) { IntentFilter intentFilter = iterator.next(); String mt = intentFilter.getDataType(0); if (mimeType.equals(mt)) { iterator.remove(); } } } private IntentFilter createIntentFilter(String mimeType) throws MalformedMimeTypeException { IntentFilter intentFilter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED); intentFilter.addDataType(mimeType); return intentFilter; } private PendingIntent getPendingIntent() { return pendingIntent; } private IntentFilter[] getIntentFilters() { return intentFilters.toArray(new IntentFilter[intentFilters.size()]); } private String[][] getTechLists() { //noinspection ToArrayCallWithZeroLengthArrayArgument return techLists.toArray(new String[0][0]); } private void parseMessage() { cordova.getThreadPool().execute(() -> { Log.d(TAG, "parseMessage " + getIntent()); Intent intent = getIntent(); String action = intent.getAction(); Log.d(TAG, "action " + action); if (action == null) { return; } Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); Parcelable[] messages = intent.getParcelableArrayExtra((NfcAdapter.EXTRA_NDEF_MESSAGES)); if (action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) { Ndef ndef = Ndef.get(tag); fireNdefEvent(NDEF_MIME, ndef, messages); } else if (action.equals(NfcAdapter.ACTION_TECH_DISCOVERED)) { for (String tagTech : tag.getTechList()) { Log.d(TAG, tagTech); if (tagTech.equals(NdefFormatable.class.getName())) { fireNdefFormatableEvent(tag); } else if (tagTech.equals(Ndef.class.getName())) { Ndef ndef = Ndef.get(tag); fireNdefEvent(NDEF, ndef, messages); } } } if (action.equals(NfcAdapter.ACTION_TAG_DISCOVERED)) { fireTagEvent(tag); } setIntent(new Intent()); }); } // Send the event data through a channel so the JavaScript side can fire the event private void sendEvent(String type, JSONObject tag) { try { JSONObject event = new JSONObject(); event.put("type", type); // TAG_DEFAULT, NDEF, NDEF_MIME, NDEF_FORMATABLE event.put("tag", tag); // JSON representing the NFC tag and NDEF messages PluginResult result = new PluginResult(PluginResult.Status.OK, event); result.setKeepCallback(true); channelCallback.sendPluginResult(result); } catch (JSONException e) { Log.e(TAG, "Error sending NFC event through the channel", e); } } private void fireNdefEvent(String type, Ndef ndef, Parcelable[] messages) { JSONObject json = buildNdefJSON(ndef, messages); sendEvent(type, json); } private void fireNdefFormatableEvent(Tag tag) { sendEvent(NDEF_FORMATABLE, Util.tagToJSON(tag)); } private void fireTagEvent(Tag tag) { sendEvent(TAG_DEFAULT, Util.tagToJSON(tag)); } private JSONObject buildNdefJSON(Ndef ndef, Parcelable[] messages) { JSONObject json = Util.ndefToJSON(ndef); // ndef is null for peer-to-peer // ndef and messages are null for ndef format-able if (ndef == null && messages != null) { try { if (messages.length > 0) { NdefMessage message = (NdefMessage) messages[0]; json.put("ndefMessage", Util.messageToJSON(message)); // guessing type, would prefer a more definitive way to determine type json.put("type", "NDEF Push Protocol"); } if (messages.length > 1) { Log.wtf(TAG, "Expected one ndefMessage but found " + messages.length); } } catch (JSONException e) { // shouldn't happen Log.e(Util.TAG, "Failed to convert ndefMessage into json", e); } } return json; } private boolean recycledIntent() { // TODO this is a kludge, find real solution int flags = getIntent().getFlags(); if ((flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) { Log.i(TAG, "Launched from history, killing recycled intent"); setIntent(new Intent()); return true; } return false; } @Override public void onPause(boolean multitasking) { Log.d(TAG, "onPause " + getIntent()); super.onPause(multitasking); if (multitasking) { // nfc can't run in background stopNfc(); } } @Override public void onResume(boolean multitasking) { Log.d(TAG, "onResume " + getIntent()); super.onResume(multitasking); startNfc(); } @Override public void onNewIntent(Intent intent) { Log.d(TAG, "onNewIntent " + intent); super.onNewIntent(intent); setIntent(intent); savedIntent = intent; parseMessage(); } private Activity getActivity() { return this.cordova.getActivity(); } private Intent getIntent() { return getActivity().getIntent(); } private void setIntent(Intent intent) { getActivity().setIntent(intent); } @Override public void onNdefPushComplete(NfcEvent event) { // handover (beam) take precedence over share tag (ndef push) if (handoverCallback != null) { PluginResult result = new PluginResult(PluginResult.Status.OK, "Beamed Message to Peer"); result.setKeepCallback(true); handoverCallback.sendPluginResult(result); } else if (shareTagCallback != null) { PluginResult result = new PluginResult(PluginResult.Status.OK, "Shared Message with Peer"); result.setKeepCallback(true); shareTagCallback.sendPluginResult(result); } } /** * Enable I/O operations to the tag from this TagTechnology object. * * * * @param tech TagTechnology class name e.g. 'android.nfc.tech.IsoDep' or 'android.nfc.tech.NfcV' * @param timeout tag timeout * @param callbackContext Cordova callback context */ private void connect(final String tech, final int timeout, final CallbackContext callbackContext) { this.cordova.getThreadPool().execute(() -> { try { Tag tag = getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG); if (tag == null) { tag = savedIntent.getParcelableExtra(NfcAdapter.EXTRA_TAG); } if (tag == null) { Log.e(TAG, "No Tag"); callbackContext.error("No Tag"); return; } // get technologies supported by this tag List<String> techList = Arrays.asList(tag.getTechList()); if (techList.contains(tech)) { // use reflection to call the static function Tech.get(tag) tagTechnologyClass = Class.forName(tech); Method method = tagTechnologyClass.getMethod("get", Tag.class); tagTechnology = (TagTechnology) method.invoke(null, tag); } if (tagTechnology == null) { callbackContext.error("Tag does not support " + tech); return; } tagTechnology.connect(); setTimeout(timeout); callbackContext.success(); } catch (IOException ex) { Log.e(TAG, "Tag connection failed", ex); callbackContext.error("Tag connection failed"); // Users should never get these reflection errors } catch (ClassNotFoundException e) { Log.e(TAG, e.getMessage(), e); callbackContext.error(e.getMessage()); } catch (NoSuchMethodException e) { Log.e(TAG, e.getMessage(), e); callbackContext.error(e.getMessage()); } catch (IllegalAccessException e) { Log.e(TAG, e.getMessage(), e); callbackContext.error(e.getMessage()); } catch (InvocationTargetException e) { Log.e(TAG, e.getMessage(), e); callbackContext.error(e.getMessage()); } }); } // Call tagTech setTimeout with reflection or fail silently private void setTimeout(int timeout) { if (timeout < 0) { return; } try { Method setTimeout = tagTechnologyClass.getMethod("setTimeout", int.class); setTimeout.invoke(tagTechnology, timeout); } catch (NoSuchMethodException e) { // ignore } catch (IllegalAccessException e) { // ignore } catch (InvocationTargetException e) { // ignore } } /** * Disable I/O operations to the tag from this TagTechnology object, and release resources. * * @param callbackContext Cordova callback context */ private void close(CallbackContext callbackContext) { cordova.getThreadPool().execute(() -> { try { if (tagTechnology != null && tagTechnology.isConnected()) { tagTechnology.close(); tagTechnology = null; callbackContext.success(); } else { // connection already gone callbackContext.success(); } } catch (IOException ex) { Log.e(TAG, "Error closing nfc connection", ex); callbackContext.error("Error closing nfc connection " + ex.getLocalizedMessage()); } }); } /** * Send raw commands to the tag and receive the response. * * @param data byte[] command to be passed to the tag * @param callbackContext Cordova callback context */ private void transceive(final byte[] data, final CallbackContext callbackContext) { cordova.getThreadPool().execute(() -> { try { if (tagTechnology == null) { Log.e(TAG, "No Tech"); callbackContext.error("No Tech"); return; } if (!tagTechnology.isConnected()) { Log.e(TAG, "Not connected"); callbackContext.error("Not connected"); return; } // Use reflection so we can support many tag types Method transceiveMethod = tagTechnologyClass.getMethod("transceive", byte[].class); @SuppressWarnings("PrimitiveArrayArgumentToVarargsMethod") byte[] response = (byte[]) transceiveMethod.invoke(tagTechnology, data); callbackContext.success(response); } catch (NoSuchMethodException e) { String error = "TagTechnology " + tagTechnologyClass.getName() + " does not have a transceive function"; Log.e(TAG, error, e); callbackContext.error(error); } catch (IllegalAccessException e) { Log.e(TAG, e.getMessage(), e); callbackContext.error(e.getMessage()); } catch (InvocationTargetException e) { Log.e(TAG, e.getMessage(), e); Throwable cause = e.getCause(); callbackContext.error(cause.getMessage()); } }); } }
package org.wysaid.myUtils; import android.graphics.Bitmap; import android.media.FaceDetector; import android.os.Environment; import android.util.Log; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class ImageUtil { public static final String LOG_TAG = Common.LOG_TAG; public static final File parentPath = Environment.getExternalStorageDirectory(); public static String storagePath = null; public static final String DST_FOLDER = "libCGE"; public static String getPath() { if(storagePath == null) { storagePath = parentPath.getAbsolutePath() + "/" + DST_FOLDER; File file = new File(storagePath); if(!file.exists()) { file.mkdir(); } } return storagePath; } public static void saveBitmap(Bitmap bmp) { String path = getPath(); long currentTime = System.currentTimeMillis(); String filename = path + "/" + currentTime + ".jpg"; saveBitmap(bmp, filename); } public static void saveBitmap(Bitmap bmp, String filename) { Log.i(LOG_TAG, "saving Bitmap : " + filename); try { FileOutputStream fileout = new FileOutputStream(filename); BufferedOutputStream bufferOutStream = new BufferedOutputStream(fileout); bmp.compress(Bitmap.CompressFormat.JPEG, 100, bufferOutStream); bufferOutStream.flush(); bufferOutStream.close(); } catch (IOException e) { Log.e(LOG_TAG, "Err when saving bitmap..."); e.printStackTrace(); return; } Log.i(LOG_TAG, "Bitmap " + filename + " saved!"); } public static class FaceRects { public int numOfFaces; public FaceDetector.Face[] faces; // faces.length >= numOfFaces } public static FaceRects findFaceByBitmap(Bitmap bmp) { return findFaceByBitmap(bmp, 1); } public static FaceRects findFaceByBitmap(Bitmap bmp, int maxFaces) { if(bmp == null) { Log.e(LOG_TAG, "Invalid Bitmap for Face Detection!"); return null; } Bitmap newBitmap = bmp; //API RGB_565 . (for now) if(newBitmap.getConfig() != Bitmap.Config.RGB_565) { newBitmap = newBitmap.copy(Bitmap.Config.RGB_565, false); } FaceRects rects = new FaceRects(); rects.faces = new FaceDetector.Face[maxFaces]; try { FaceDetector detector = new FaceDetector(newBitmap.getWidth(), newBitmap.getHeight(), maxFaces); rects.numOfFaces = detector.findFaces(newBitmap, rects.faces); } catch (Exception e) { Log.e(LOG_TAG, "findFaceByBitmap error: " + e.getMessage()); return null; } if(newBitmap != bmp) { newBitmap.recycle(); } return rects; } }
package com.mebigfatguy.patchanim.gui; import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowFocusListener; import java.io.File; import java.io.IOException; import java.text.MessageFormat; import java.util.ResourceBundle; import javax.swing.ImageIcon; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import javax.swing.filechooser.FileFilter; import com.mebigfatguy.patchanim.ExportType; import com.mebigfatguy.patchanim.PatchAnimDocument; import com.mebigfatguy.patchanim.gui.events.ActivePatchChangedEvent; import com.mebigfatguy.patchanim.gui.events.ActivePatchChangedListener; import com.mebigfatguy.patchanim.gui.events.SettingsChangedEvent; import com.mebigfatguy.patchanim.gui.events.SettingsChangedListener; import com.mebigfatguy.patchanim.io.PatchAnimIO; import com.mebigfatguy.patchanim.io.PatchExporter; import com.mebigfatguy.patchanim.main.PatchAnimBundle; public class JPatchAnimFrame extends JFrame { private static final long serialVersionUID = -4610407923936772733L; private static final String ICON_URL = "/com/mebigfatguy/patchanim/gui/patchanimicon.jpg"; private JMenuItem newItem; private JMenuItem openItem; private JMenuItem saveItem; private JMenuItem saveAsItem; private JMenu exportMenu; private JMenuItem exportJpgsItem; private JMenuItem exportPngsItem; private JMenuItem exportGifsItem; private JMenuItem exportAnimatedGifItem; private JMenuItem exportAnimatedPngItem; private JMenuItem exportAnimatedMngItem; private JMenuItem quitItem; private PatchAnimDocument document; private File documentLocation; public JPatchAnimFrame() { initComponents(); initMenus(); initListeners(); } private void initComponents() { ResourceBundle rb = PatchAnimBundle.getBundle(); Container cp = getContentPane(); cp.setLayout(new BorderLayout(4, 4)); JPatchAnimPanel patchPanel = new JPatchAnimPanel(); document = new PatchAnimDocument(4, false); documentLocation = null; PatchPanelMediator mediator = PatchPanelMediator.getMediator(); mediator.setDocument(document); cp.add(patchPanel, BorderLayout.CENTER); String title = MessageFormat.format(rb.getString(PatchAnimBundle.NAMEDTITLE), rb.getString(PatchAnimBundle.UNTITLED)); setTitle(title); setIconImage(new ImageIcon(JPatchAnimFrame.class.getResource(ICON_URL)).getImage()); pack(); } private void initMenus() { ResourceBundle rb = PatchAnimBundle.getBundle(); JMenuBar mb = new JMenuBar(); JMenu fileMenu = new JMenu(rb.getString(PatchAnimBundle.FILE)); newItem = new JMenuItem(rb.getString(PatchAnimBundle.NEW)); fileMenu.add(newItem); openItem = new JMenuItem(rb.getString(PatchAnimBundle.OPEN)); fileMenu.add(openItem); fileMenu.addSeparator(); saveItem = new JMenuItem(rb.getString(PatchAnimBundle.SAVE)); saveItem.setEnabled(false); fileMenu.add(saveItem); saveAsItem = new JMenuItem(rb.getString(PatchAnimBundle.SAVEAS)); fileMenu.add(saveAsItem); fileMenu.addSeparator(); exportMenu = new JMenu(rb.getString(PatchAnimBundle.EXPORT)); exportJpgsItem = new JMenuItem(rb.getString(PatchAnimBundle.JPGSERIES)); exportPngsItem = new JMenuItem(rb.getString(PatchAnimBundle.PNGSERIES)); exportGifsItem = new JMenuItem(rb.getString(PatchAnimBundle.GIFSERIES)); exportAnimatedGifItem = new JMenuItem(rb.getString(PatchAnimBundle.ANIMATEDGIF)); exportAnimatedPngItem = new JMenuItem(rb.getString(PatchAnimBundle.ANIMATEDPNG)); exportAnimatedMngItem = new JMenuItem(rb.getString(PatchAnimBundle.ANIMATEDMNG)); exportMenu.add(exportJpgsItem); exportMenu.add(exportPngsItem); exportMenu.add(exportGifsItem); exportMenu.addSeparator(); exportMenu.add(exportAnimatedGifItem); exportMenu.add(exportAnimatedPngItem); exportMenu.add(exportAnimatedMngItem); fileMenu.add(exportMenu); fileMenu.addSeparator(); quitItem = new JMenuItem(rb.getString(PatchAnimBundle.QUIT)); fileMenu.add(quitItem); mb.add(fileMenu); setJMenuBar(mb); } private void initListeners() { setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent we) { try { if (document.isDirty()) { int choice = askSave(); if (choice == JOptionPane.CANCEL_OPTION) return; if (choice == JOptionPane.YES_OPTION) { save(); } } dispose(); System.exit(0); } catch (IOException ioe) { ResourceBundle rb = PatchAnimBundle.getBundle(); JOptionPane.showMessageDialog(JPatchAnimFrame.this, rb.getString(PatchAnimBundle.SAVEFAILED)); } } }); addWindowFocusListener(new WindowFocusListener() { @Override public void windowGainedFocus(WindowEvent e) { PatchPanelMediator mediator = PatchPanelMediator.getMediator(); mediator.setFocused(true); } @Override public void windowLostFocus(WindowEvent e) { PatchPanelMediator mediator = PatchPanelMediator.getMediator(); mediator.setFocused(false); } }); newItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { try { if (document.isDirty()) { int choice = askSave(); if (choice == JOptionPane.CANCEL_OPTION) return; if (choice == JOptionPane.YES_OPTION) { save(); } } newDocument(); } catch (IOException ioe) { ResourceBundle rb = PatchAnimBundle.getBundle(); JOptionPane.showMessageDialog(JPatchAnimFrame.this, rb.getString(PatchAnimBundle.SAVEFAILED)); } } }); openItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { try { if (document.isDirty()) { int choice = askSave(); if (choice == JOptionPane.CANCEL_OPTION) return; if (choice == JOptionPane.YES_OPTION) { save(); } } load(); ResourceBundle rb = PatchAnimBundle.getBundle(); String title = MessageFormat.format(rb.getString(PatchAnimBundle.NAMEDTITLE), documentLocation == null ? "" : documentLocation.getName()); setTitle(title); } catch (IOException ioe) { ResourceBundle rb = PatchAnimBundle.getBundle(); JOptionPane.showMessageDialog(JPatchAnimFrame.this, rb.getString(PatchAnimBundle.LOADFAILED)); } } }); saveItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { try { if (documentLocation == null) { saveAs(); } else { save(); } } catch (IOException ioe) { ResourceBundle rb = PatchAnimBundle.getBundle(); JOptionPane.showMessageDialog(JPatchAnimFrame.this, rb.getString(PatchAnimBundle.SAVEFAILED)); } } }); saveAsItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { try { saveAs(); } catch (IOException ioe) { ResourceBundle rb = PatchAnimBundle.getBundle(); JOptionPane.showMessageDialog(JPatchAnimFrame.this, rb.getString(PatchAnimBundle.SAVEFAILED)); } } }); exportJpgsItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { export(ExportType.JPegs); } }); exportPngsItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { export(ExportType.Pngs); } }); exportGifsItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { export(ExportType.Gifs); } }); exportAnimatedGifItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { export(ExportType.AnimatedGif); } }); exportAnimatedPngItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { export(ExportType.AnimatedPng); } }); exportAnimatedMngItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { export(ExportType.AnimatedMng); } }); quitItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { try { if (document.isDirty()) { int choice = askSave(); if (choice == JOptionPane.CANCEL_OPTION) return; if (choice == JOptionPane.YES_OPTION) { save(); } } dispose(); System.exit(0); } catch (IOException ioe) { ResourceBundle rb = PatchAnimBundle.getBundle(); JOptionPane.showMessageDialog(JPatchAnimFrame.this, rb.getString(PatchAnimBundle.SAVEFAILED)); } } }); PatchPanelMediator mediator = PatchPanelMediator.getMediator(); mediator.addActivePatchChangedListener(new ActivePatchChangedListener () { @Override public void activePatchChanged(ActivePatchChangedEvent apce) { document.setDirty(true); saveItem.setEnabled(true); } }); mediator.addSettingsChangedListener(new SettingsChangedListener() { @Override public void settingsChanged(SettingsChangedEvent sce) { document.setDirty(true); saveItem.setEnabled(true); } }); } @Override public void setVisible(boolean show) { newDocument(); super.setVisible(show); } private void newDocument() { ResourceBundle rb = PatchAnimBundle.getBundle(); NewDocumentDialog newDialog = new NewDocumentDialog(); newDialog.setModal(true); newDialog.setLocationRelativeTo(JPatchAnimFrame.this); newDialog.setVisible(true); int order = newDialog.getOrder(); boolean useAlpha = newDialog.useAlpha(); document = new PatchAnimDocument(order, useAlpha); documentLocation = null; saveItem.setEnabled(false); PatchPanelMediator mediator = PatchPanelMediator.getMediator(); mediator.setDocument(document); String title = MessageFormat.format(rb.getString(PatchAnimBundle.NAMEDTITLE), rb.getString(PatchAnimBundle.UNTITLED)); setTitle(title); } private void load() { try { JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setFileFilter(new PatchAnimFileFilter()); chooser.setCurrentDirectory(new File(System.getProperty("user.dir"))); int option = chooser.showOpenDialog(JPatchAnimFrame.this); if (option == JFileChooser.APPROVE_OPTION) { documentLocation = chooser.getSelectedFile(); document = PatchAnimIO.loadFile(documentLocation); } } catch (IOException e) { ResourceBundle rb = PatchAnimBundle.getBundle(); JOptionPane.showMessageDialog(JPatchAnimFrame.this, rb.getString(PatchAnimBundle.LOADFAILED)); documentLocation = null; document = new PatchAnimDocument(4, false); } finally { PatchPanelMediator mediator = PatchPanelMediator.getMediator(); mediator.setDocument(document); saveItem.setEnabled(false); } } private void saveAs() throws IOException { JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); File defLocation; if (documentLocation == null) defLocation = new File(System.getProperty("user.dir")); else defLocation = documentLocation.getParentFile(); chooser.setCurrentDirectory(defLocation); chooser.setFileFilter(new PatchAnimFileFilter()); int option = chooser.showSaveDialog(JPatchAnimFrame.this); if (option == JFileChooser.APPROVE_OPTION) { String path = chooser.getSelectedFile().getPath(); if (!path.toLowerCase().endsWith(".paf")) path += ".paf"; documentLocation = new File(path); PatchAnimIO.saveFile(documentLocation, document); documentLocation = chooser.getSelectedFile(); document.setDirty(false); saveItem.setEnabled(false); } } private void save() throws IOException { PatchAnimIO.saveFile(documentLocation, document); document.setDirty(false); saveItem.setEnabled(false); } private int askSave() { ResourceBundle rb = PatchAnimBundle.getBundle(); return JOptionPane.showConfirmDialog(JPatchAnimFrame.this, rb.getString(PatchAnimBundle.ASKSAVE), rb.getString(PatchAnimBundle.TITLE), JOptionPane.YES_NO_CANCEL_OPTION); } private File getExportLocation(final ExportType type) { JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); File defLocation; if (documentLocation == null) defLocation = new File(System.getProperty("user.dir")); else defLocation = documentLocation.getParentFile(); chooser.setCurrentDirectory(defLocation); if (!type.isMultipleFiles()) { chooser.setFileFilter(new FileFilter() { private final ResourceBundle rb = PatchAnimBundle.getBundle(); @Override public boolean accept(File f) { return (f.isDirectory() || f.getPath().toLowerCase().endsWith("." + type.getExtension())); } @Override public String getDescription() { return rb.getString(type.getDescriptionKey()); } }); } int option = chooser.showSaveDialog(JPatchAnimFrame.this); if (option != JFileChooser.APPROVE_OPTION) return null; return chooser.getSelectedFile(); } private void export(ExportType type) { File f = getExportLocation(type); if (f != null) { final PatchExporter exporter = new PatchExporter(type, f); final ExportFrame ed = new ExportFrame(); ed.setLocationRelativeTo(JPatchAnimFrame.this); ed.setVisible(true); Thread t = new Thread(new Runnable() { @Override public void run() { try { exporter.addExportListener(ed); exporter.export(document); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { ed.dispose(); } }); } catch (IOException ioe) { ResourceBundle rb = PatchAnimBundle.getBundle(); JOptionPane.showMessageDialog(JPatchAnimFrame.this, rb.getString(PatchAnimBundle.EXPORTFAILED)); } } }); t.start(); } } }
package com.chariotsolutions.nfc.plugin; import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; import android.content.IntentFilter; import android.content.IntentFilter.MalformedMimeTypeException; import android.net.Uri; import android.nfc.FormatException; // Cordova 3.x import android.nfc.NdefMessage; // Cordova 2.9 import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.nfc.NfcEvent; import android.nfc.Tag; import android.nfc.TagLostException; import android.nfc.tech.IsoDep; import android.nfc.tech.Ndef; import android.nfc.tech.NdefFormatable; import android.os.Parcelable; import android.util.Log; import java.io.IOException; import java.math.BigInteger; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class NfcPlugin extends CordovaPlugin implements NfcAdapter.OnNdefPushCompleteCallback { private static final String CONNECT = "connect"; private static final String CLOSE = "close"; private static final String TRANSCEIVE = "transceive"; private static final String GETCARDNUMBER = "getcardnumber"; private static final String REGISTER_MIME_TYPE = "registerMimeType"; private static final String REMOVE_MIME_TYPE = "removeMimeType"; private static final String REGISTER_NDEF = "registerNdef"; private static final String REMOVE_NDEF = "removeNdef"; private static final String REGISTER_NDEF_FORMATABLE = "registerNdefFormatable"; private static final String REGISTER_DEFAULT_TAG = "registerTag"; private static final String REMOVE_DEFAULT_TAG = "removeTag"; private static final String WRITE_TAG = "writeTag"; private static final String ERASE_TAG = "eraseTag"; private static final String SHARE_TAG = "shareTag"; private static final String UNSHARE_TAG = "unshareTag"; private static final String HANDOVER = "handover"; // Android Beam private static final String STOP_HANDOVER = "stopHandover"; private static final String ENABLED = "enabled"; private static final String INIT = "init"; private static final String SHOW_SETTINGS = "showSettings"; private static final String NDEF = "ndef"; private static final String NDEF_MIME = "ndef-mime"; private static final String NDEF_FORMATABLE = "ndef-formatable"; private static final String TAG_DEFAULT = "tag"; private static final String STATUS_NFC_OK = "NFC_OK"; private static final String STATUS_NO_NFC = "NO_NFC"; private static final String STATUS_NFC_DISABLED = "NFC_DISABLED"; private static final String STATUS_NDEF_PUSH_DISABLED = "NDEF_PUSH_DISABLED"; private static final String ID = "NfcPlugin"; private final List<IntentFilter> intentFilters = new ArrayList<IntentFilter>(); private final ArrayList<String[]> techLists = new ArrayList<String[]>(); private NdefMessage p2pMessage = null; private PendingIntent pendingIntent = null; private Intent savedIntent = null; private CallbackContext shareTagCallback; private CallbackContext handoverCallback; /** * APDU */ private IsoDep isoDep = null; private Tag tag = null; @Override public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException { if (action.equalsIgnoreCase(SHOW_SETTINGS)) { showSettings(callbackContext); return true; } if (!getNfcStatus().equals(STATUS_NFC_OK)) { callbackContext.error(getNfcStatus()); return true; // short circuit } createPendingIntent(); if (action.equalsIgnoreCase(REGISTER_MIME_TYPE)) { registerMimeType(data, callbackContext); } else if (action.equalsIgnoreCase(REMOVE_MIME_TYPE)) { removeMimeType(data, callbackContext); } else if (action.equalsIgnoreCase(REGISTER_NDEF)) { registerNdef(callbackContext); } else if (action.equalsIgnoreCase(REMOVE_NDEF)) { removeNdef(callbackContext); } else if (action.equalsIgnoreCase(REGISTER_NDEF_FORMATABLE)) { registerNdefFormatable(callbackContext); } else if (action.equals(REGISTER_DEFAULT_TAG)) { registerDefaultTag(callbackContext); } else if (action.equals(REMOVE_DEFAULT_TAG)) { removeDefaultTag(callbackContext); } else if (action.equalsIgnoreCase(WRITE_TAG)) { writeTag(data, callbackContext); } else if (action.equalsIgnoreCase(ERASE_TAG)) { eraseTag(callbackContext); } else if (action.equalsIgnoreCase(SHARE_TAG)) { shareTag(data, callbackContext); } else if (action.equalsIgnoreCase(UNSHARE_TAG)) { unshareTag(callbackContext); } else if (action.equalsIgnoreCase(HANDOVER)) { handover(data, callbackContext); } else if (action.equalsIgnoreCase(STOP_HANDOVER)) { stopHandover(callbackContext); } else if (action.equalsIgnoreCase(INIT)) { init(callbackContext); } else if (action.equalsIgnoreCase(ENABLED)) { // status is checked before every call // if code made it here, NFC is enabled callbackContext.success(STATUS_NFC_OK); } else if (action.equalsIgnoreCase(CONNECT)) { // APDU connect(callbackContext); } else if (action.equalsIgnoreCase(CLOSE)) { // APDU close(callbackContext); } else if (action.equalsIgnoreCase(TRANSCEIVE)) { // APDU transceive(data, callbackContext); } else if (action.equalsIgnoreCase(GETCARDNUMBER)) { // APDU getcardnumber(callbackContext); } else { // invalid action return false; } return true; } /** * APDU */ private void connect(final CallbackContext callbackContext) throws JSONException { try { this.cordova.getThreadPool().execute(new NfcConnect(this, callbackContext)); } catch (Throwable e) { callbackContext.error("COULD_NOT_CONNECT"); } } /** * APDU */ private void close(CallbackContext callbackContext) throws JSONException { try { this.cordova.getThreadPool().execute(new NfcClose(this, callbackContext)); } catch (Throwable e) { callbackContext.error("COULD_NOT_CLOSE"); } } /** * APDU */ private String BCDtoString(byte[] bytes) { StringBuffer number = new StringBuffer(); for (byte bcd : bytes) { StringBuffer sb = new StringBuffer(); byte high = (byte) (bcd & 0xf0); high = (byte) ((high >>> 4) & 0xff); high = (byte) (high & 0x0f); byte low = (byte) (bcd & 0x0f); sb.append(high); sb.append(low); number.append(sb.toString()); } return number.toString(); } private void getcardnumber(final CallbackContext callbackContext) throws JSONException { int isodeptimeout = isoDep.getTimeout(); cordova.getThreadPool().execute(new Runnable() { @Override public void run() { try { if (isoDep == null) { callbackContext.error("NO_TECH"); } if (!isoDep.isConnected()) { callbackContext.error("NOT_CONNECTED"); } byte[] commandAPDU = { (byte) 0x90, (byte) 0x5A, // SELECT FILE (byte) 0x00, // (byte) 0x04,// Direct selection by DF name (byte) 0x00, // Select First record 00 , last re 01 , next record 02 (byte) 0x03, // length of command data (byte) 0x11, (byte) 0x20, (byte) 0Xef, (byte) 0X00 // HSL DFname EF2011 }; byte[] responseAPDU = isoDep.transceive(commandAPDU); byte[] commandAPDU2 = { (byte) 0x90, // CLA (byte) 0xBD, (byte) 0x00, (byte) 0x00, (byte) 0x07, (byte) 0x08, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x0b, (byte) 0x00, (byte) 0x00, (byte) 0x00 }; byte[] responseAPDU2 = isoDep.transceive(commandAPDU2); String cardnumber = BCDtoString(responseAPDU2).substring(2, 20); callbackContext.success(cardnumber); } catch (Throwable e) { callbackContext.error("ERROR_GETTING_CARD_NUMBER, " + e.getMessage()); } } }); } JSONArray jsonarray = new JSONArray(); private void transceive(final JSONArray data, final CallbackContext callbackContext) throws JSONException { int isodeptimeout = isoDep.getTimeout(); cordova.getThreadPool().execute(new Runnable() { @Override public void run() { try { if (isoDep == null) { callbackContext.error("NO_TECH"); } if (!isoDep.isConnected()) { callbackContext.error("NOT_CONNECTED"); } String apdustring = data.getString(0); Pattern apdus = Pattern.compile("<apdu id=([^<]*)>([^<]*)</apdu>"); Matcher matcher = apdus.matcher(apdustring); String sendback = apdustring; while (matcher.find()) { String currentResponseId = matcher.group(1); String currentCommandApdu = matcher.group(2); int jsonarrayLength = jsonarray.length(); if (jsonarrayLength == 0) { byte[] commandAPDU = hexStringToByteArray(matcher.group(2)); byte[] responseAPDU = isoDep.transceive(commandAPDU); String id = String.format("id=%s", matcher.group(1)); String replacethis = matcher.group(0); String replacewith = "<apdu "+id+">"+byte2Hex(responseAPDU)+"</apdu>"; String currentResponseApdu = byte2Hex(responseAPDU); //Log.e(ID, "COMMAND APDU: " + matcher.group(2) + " - ID: " + id + " - RESPONSE: " + byte2Hex(responseAPDU)); sendback = sendback.replaceFirst(replacethis, replacewith); String containsAF = currentResponseApdu.length() > 2 ? currentResponseApdu.substring(currentResponseApdu.length() - 2) : currentResponseApdu; if (currentCommandApdu.equals("9060000000") && containsAF.equals("af")) { byte[] commandAPDU2 = hexStringToByteArray("90af000000"); byte[] responseAPDU2 = isoDep.transceive(commandAPDU2); String currentResponseApdu2 = byte2Hex(responseAPDU2); JSONObject item1 = new JSONObject(); item1.put("id", "2"); item1.put("response", currentResponseApdu2); jsonarray.put(item1); String containsAF2 = currentResponseApdu2.length() > 2 ? currentResponseApdu2.substring(currentResponseApdu2.length() - 2) : currentResponseApdu; if (containsAF2.equals("af")) { byte[] commandAPDU3 = hexStringToByteArray("90af000000"); byte[] responseAPDU3 = isoDep.transceive(commandAPDU3); String currentResponseApdu3 = byte2Hex(responseAPDU3); JSONObject item2 = new JSONObject(); item2.put("id", "3"); item2.put("response", currentResponseApdu3); jsonarray.put(item2); } } } else { //Log.e(ID, "REMAINING JSONARRAY: " + jsonarray.toString()); for (int i = 0; i < jsonarray.length(); ++i) { JSONObject listitem = jsonarray.getJSONObject(i); String itemid = listitem.getString("id"); String itemresponse = listitem.getString("response"); String originalResponseId = currentResponseId.replace("\"", ""); if (itemid.equals(originalResponseId)) { String replacethis = matcher.group(0); String id = String.format("id=\"%s\"", itemid); String replacewith = "<apdu "+id+">"+itemresponse+"</apdu>"; //Log.e(ID, "REPLACE THIS: " + replacethis); //Log.e(ID, "WITH THIS: " + replacewith); sendback = sendback.replaceFirst(replacethis, replacewith); jsonarray.remove(i); break; } } } } //Log.i(ID, "SENDBACK: " + sendback); callbackContext.success(sendback); } catch (Throwable e) { callbackContext.error("ERROR_IN_TRANSCEIVE, " + e.getMessage()); } } }); } public static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16)); } return data; } private byte[] hex2Byte(final String hex) { return new BigInteger(hex, 16).toByteArray(); } private String byte2Hex(final byte[] b) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < b.length; i++) { sb.append(Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); } private String getNfcStatus() { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); if (nfcAdapter == null) { return STATUS_NO_NFC; } else if (!nfcAdapter.isEnabled()) { return STATUS_NFC_DISABLED; } else { return STATUS_NFC_OK; } } private void registerDefaultTag(CallbackContext callbackContext) { addTagFilter(); callbackContext.success(); } private void removeDefaultTag(CallbackContext callbackContext) { removeTagFilter(); callbackContext.success(); } private void registerNdefFormatable(CallbackContext callbackContext) { addTechList(new String[] { NdefFormatable.class.getName() }); callbackContext.success(); } private void registerNdef(CallbackContext callbackContext) { addTechList(new String[] { Ndef.class.getName() }); callbackContext.success(); } private void removeNdef(CallbackContext callbackContext) { removeTechList(new String[] { Ndef.class.getName() }); callbackContext.success(); } private void unshareTag(CallbackContext callbackContext) { p2pMessage = null; stopNdefPush(); shareTagCallback = null; callbackContext.success(); } private void init(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { startNfc(); if (!recycledIntent()) { parseMessage(); } callbackContext.success(); } }); } private void removeMimeType(JSONArray data, CallbackContext callbackContext) throws JSONException { String mimeType = ""; try { mimeType = data.getString(0); /*boolean removed =*/ removeIntentFilter(mimeType); callbackContext.success(); } catch (MalformedMimeTypeException e) { callbackContext.error("Invalid MIME Type " + mimeType); } } private void registerMimeType(JSONArray data, CallbackContext callbackContext) throws JSONException { String mimeType = ""; try { mimeType = data.getString(0); intentFilters.add(createIntentFilter(mimeType)); callbackContext.success(); } catch (MalformedMimeTypeException e) { callbackContext.error("Invalid MIME Type " + mimeType); } } // Cheating and writing an empty record. We may actually be able to erase some tag types. private void eraseTag(CallbackContext callbackContext) throws JSONException { Tag _tag = savedIntent.getParcelableExtra(NfcAdapter.EXTRA_TAG); NdefRecord[] records = { new NdefRecord(NdefRecord.TNF_EMPTY, new byte[0], new byte[0], new byte[0]) }; writeNdefMessage(new NdefMessage(records), _tag, callbackContext); } private void writeTag(JSONArray data, CallbackContext callbackContext) throws JSONException { if (getIntent() == null) { // TODO remove this and handle LostTag callbackContext.error("Failed to write tag, received null intent"); } Tag _tag = savedIntent.getParcelableExtra(NfcAdapter.EXTRA_TAG); NdefRecord[] records = Util.jsonToNdefRecords(data.getString(0)); writeNdefMessage(new NdefMessage(records), _tag, callbackContext); } private void writeNdefMessage(final NdefMessage message, final Tag tag, final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { try { Ndef ndef = Ndef.get(tag); if (ndef != null) { ndef.connect(); if (ndef.isWritable()) { int size = message.toByteArray().length; if (ndef.getMaxSize() < size) { callbackContext.error("Tag capacity is " + ndef.getMaxSize() + " bytes, message is " + size + " bytes."); } else { ndef.writeNdefMessage(message); callbackContext.success(); } } else { callbackContext.error("Tag is read only"); } ndef.close(); } else { NdefFormatable formatable = NdefFormatable.get(tag); if (formatable != null) { formatable.connect(); formatable.format(message); callbackContext.success(); formatable.close(); } else { callbackContext.error("Tag doesn't support NDEF"); } } } catch (FormatException e) { callbackContext.error(e.getMessage()); } catch (TagLostException e) { callbackContext.error(e.getMessage()); } catch (IOException e) { callbackContext.error(e.getMessage()); } } }); } private void shareTag(JSONArray data, CallbackContext callbackContext) throws JSONException { NdefRecord[] records = Util.jsonToNdefRecords(data.getString(0)); this.p2pMessage = new NdefMessage(records); startNdefPush(callbackContext); } // setBeamPushUris // Every Uri you provide must have either scheme 'file' or scheme 'content'. // Note that this takes priority over setNdefPush // See http://developer.android.com/reference/android/nfc/NfcAdapter.html#setBeamPushUris(android.net.Uri[],%20android.app.Activity) private void handover(JSONArray data, CallbackContext callbackContext) throws JSONException { Uri[] uri = new Uri[data.length()]; for (int i = 0; i < data.length(); i++) { uri[i] = Uri.parse(data.getString(i)); } startNdefBeam(callbackContext, uri); } private void stopHandover(CallbackContext callbackContext) throws JSONException { stopNdefBeam(); handoverCallback = null; callbackContext.success(); } private void showSettings(CallbackContext callbackContext) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) { Intent intent = new Intent(android.provider.Settings.ACTION_NFC_SETTINGS); getActivity().startActivity(intent); } else { Intent intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS); getActivity().startActivity(intent); } callbackContext.success(); } private void createPendingIntent() { if (pendingIntent == null) { Activity activity = getActivity(); Intent intent = new Intent(activity, activity.getClass()); intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); pendingIntent = PendingIntent.getActivity(activity, 0, intent, 0); } } private void addTechList(String[] list) { this.addTechFilter(); this.addToTechList(list); } private void removeTechList(String[] list) { this.removeTechFilter(); this.removeFromTechList(list); } private void addTechFilter() { intentFilters.add(new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED)); } private boolean removeTechFilter() { boolean removed = false; Iterator<IntentFilter> iter = intentFilters.iterator(); while (iter.hasNext()) { IntentFilter intentFilter = iter.next(); if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intentFilter.getAction(0))) { intentFilters.remove(intentFilter); removed = true; } } return removed; } private void addTagFilter() { intentFilters.add(new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED)); } private boolean removeTagFilter() { boolean removed = false; Iterator<IntentFilter> iter = intentFilters.iterator(); while (iter.hasNext()) { IntentFilter intentFilter = iter.next(); if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intentFilter.getAction(0))) { intentFilters.remove(intentFilter); removed = true; } } return removed; } private void startNfc() { createPendingIntent(); // onResume can call startNfc before execute getActivity().runOnUiThread(new Runnable() { @Override public void run() { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); if (nfcAdapter != null && !getActivity().isFinishing()) { try { nfcAdapter.enableForegroundDispatch(getActivity(), getPendingIntent(), getIntentFilters(), getTechLists()); if (p2pMessage != null) { nfcAdapter.setNdefPushMessage(p2pMessage, getActivity()); } } catch (IllegalStateException e) { // issue 110 - user exits app with home button while nfc is initializing Log.w(ID, "Illegal State Exception starting NFC. Assuming application is terminating."); } } } }); } private void stopNfc() { getActivity().runOnUiThread(new Runnable() { @Override public void run() { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); if (nfcAdapter != null) { try { nfcAdapter.disableForegroundDispatch(getActivity()); } catch (IllegalStateException e) { // issue 125 - user exits app with back button while nfc Log.w(ID, "Illegal State Exception stopping NFC. Assuming application is terminating."); } } } }); } private void startNdefBeam(final CallbackContext callbackContext, final Uri[] uris) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); if (nfcAdapter == null) { callbackContext.error(STATUS_NO_NFC); } else if (!nfcAdapter.isNdefPushEnabled()) { callbackContext.error(STATUS_NDEF_PUSH_DISABLED); } else { nfcAdapter.setOnNdefPushCompleteCallback(NfcPlugin.this, getActivity()); try { nfcAdapter.setBeamPushUris(uris, getActivity()); PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); result.setKeepCallback(true); handoverCallback = callbackContext; callbackContext.sendPluginResult(result); } catch (IllegalArgumentException e) { callbackContext.error(e.getMessage()); } } } }); } private void startNdefPush(final CallbackContext callbackContext) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); if (nfcAdapter == null) { callbackContext.error(STATUS_NO_NFC); } else if (!nfcAdapter.isNdefPushEnabled()) { callbackContext.error(STATUS_NDEF_PUSH_DISABLED); } else { nfcAdapter.setNdefPushMessage(p2pMessage, getActivity()); nfcAdapter.setOnNdefPushCompleteCallback(NfcPlugin.this, getActivity()); PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); result.setKeepCallback(true); shareTagCallback = callbackContext; callbackContext.sendPluginResult(result); } } }); } private void stopNdefPush() { getActivity().runOnUiThread(new Runnable() { @Override public void run() { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); if (nfcAdapter != null) { nfcAdapter.setNdefPushMessage(null, getActivity()); } } }); } private void stopNdefBeam() { getActivity().runOnUiThread(new Runnable() { @Override public void run() { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); if (nfcAdapter != null) { nfcAdapter.setBeamPushUris(null, getActivity()); } } }); } private void addToTechList(String[] techs) { techLists.add(techs); } private void removeFromTechList(String[] techs) { techLists.remove(techs); } private boolean removeIntentFilter(String mimeType) throws MalformedMimeTypeException { boolean removed = false; Iterator<IntentFilter> iter = intentFilters.iterator(); while (iter.hasNext()) { IntentFilter intentFilter = iter.next(); String mt = intentFilter.getDataType(0); if (mimeType.equals(mt)) { intentFilters.remove(intentFilter); removed = true; } } return removed; } private IntentFilter createIntentFilter(String mimeType) throws MalformedMimeTypeException { IntentFilter intentFilter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED); intentFilter.addDataType(mimeType); return intentFilter; } private PendingIntent getPendingIntent() { return pendingIntent; } private IntentFilter[] getIntentFilters() { return intentFilters.toArray(new IntentFilter[intentFilters.size()]); } private String[][] getTechLists() { //noinspection ToArrayCallWithZeroLengthArrayArgument return techLists.toArray(new String[0][0]); } void parseMessage() { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { Intent intent = getIntent(); String action = intent.getAction(); if (action == null) { return; } /*Tag*/ tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); Parcelable[] messages = intent.getParcelableArrayExtra((NfcAdapter.EXTRA_NDEF_MESSAGES)); if (action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) { Ndef ndef = Ndef.get(tag); fireNdefEvent(NDEF_MIME, ndef, messages); } else if (action.equals(NfcAdapter.ACTION_TECH_DISCOVERED)) { for (String tagTech : tag.getTechList()) { if (tagTech.equals(NdefFormatable.class.getName())) { fireNdefFormatableEvent(tag); } else if (tagTech.equals(Ndef.class.getName())) { Ndef ndef = Ndef.get(tag); fireNdefEvent(NDEF, ndef, messages); } } } if (action.equals(NfcAdapter.ACTION_TAG_DISCOVERED)) { fireTagEvent(tag); } setIntent(new Intent()); } }); } private void fireNdefEvent(String type, Ndef ndef, Parcelable[] messages) { JSONObject jsonObject = buildNdefJSON(ndef, messages); String tagAsString = jsonObject.toString(); String command = MessageFormat.format(javaScriptEventTemplate, type, tagAsString); this.webView.sendJavascript(command); } private void fireNdefFormatableEvent(Tag tag) { String command = MessageFormat.format(javaScriptEventTemplate, NDEF_FORMATABLE, Util.tagToJSON(tag)); this.webView.sendJavascript(command); } private void fireTagEvent(Tag tag) { String command = MessageFormat.format(javaScriptEventTemplate, TAG_DEFAULT, Util.tagToJSON(tag)); this.webView.sendJavascript(command); } private void fireConnected(Tag tag) { String command = MessageFormat.format(javaScriptEventTemplate, "nfc-connected", Util.tagToJSON(tag)); this.webView.sendJavascript(command); } JSONObject buildNdefJSON(Ndef ndef, Parcelable[] messages) { JSONObject json = Util.ndefToJSON(ndef); // ndef is null for peer-to-peer // ndef and messages are null for ndef format-able if (ndef == null && messages != null) { try { if (messages.length > 0) { NdefMessage message = (NdefMessage) messages[0]; json.put("ndefMessage", Util.messageToJSON(message)); // guessing type, would prefer a more definitive way to determine type json.put("type", "NDEF Push Protocol"); } if (messages.length > 1) { Log.e(ID, "Expected one ndefMessage but found " + messages.length); } } catch (JSONException e) { // shouldn't happen Log.e(Util.TAG, "Failed to convert ndefMessage into json", e); } } return json; } private boolean recycledIntent() { // TODO this is a kludge, find real solution int flags = getIntent().getFlags(); if ((flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) { Log.i(ID, "Launched from history, killing recycled intent"); setIntent(new Intent()); return true; } return false; } @Override public void onPause(boolean multitasking) { super.onPause(multitasking); if (multitasking) { // nfc can't run in background stopNfc(); } } @Override public void onResume(boolean multitasking) { super.onResume(multitasking); startNfc(); } @Override public void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); savedIntent = intent; parseMessage(); } private Activity getActivity() { return this.cordova.getActivity(); } private Intent getIntent() { return getActivity().getIntent(); } private void setIntent(Intent intent) { getActivity().setIntent(intent); } String javaScriptEventTemplate = "var e = document.createEvent(''Events'');\n" + "e.initEvent(''{0}'');\n" + "e.tag = {1};\n" + "document.dispatchEvent(e);"; @Override public void onNdefPushComplete(NfcEvent event) { // handover (beam) take precedence over share tag (ndef push) if (handoverCallback != null) { PluginResult result = new PluginResult(PluginResult.Status.OK, "Beamed Message to Peer"); result.setKeepCallback(true); handoverCallback.sendPluginResult(result); } else if (shareTagCallback != null) { PluginResult result = new PluginResult(PluginResult.Status.OK, "Shared Message with Peer"); result.setKeepCallback(true); shareTagCallback.sendPluginResult(result); } } public Intent getSavedIntent() { return savedIntent; } public void setSavedIntent(Intent savedIntent) { this.savedIntent = savedIntent; } class NfcConnect implements Runnable { NfcPlugin nfcPlugin; CallbackContext callbackContext; NfcConnect(NfcPlugin nfcPlugin, CallbackContext callbackContext) { this.nfcPlugin = nfcPlugin; this.callbackContext = callbackContext; } @Override public void run() { try { if (nfcPlugin.tag == null) { nfcPlugin.tag = (Tag) getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG); } if (nfcPlugin.tag == null) { nfcPlugin.tag = (Tag) nfcPlugin.savedIntent.getParcelableExtra(NfcAdapter.EXTRA_TAG); } if (nfcPlugin.tag == null) { callbackContext.error("NO_TAG"); } nfcPlugin.isoDep = IsoDep.get(tag); if (nfcPlugin.isoDep == null) { callbackContext.error("NO_TECH"); } nfcPlugin.isoDep.connect(); nfcPlugin.isoDep.setTimeout(3000); nfcPlugin.fireConnected(nfcPlugin.tag); callbackContext.success(); } catch (IOException ex) { callbackContext.error("ERROR_CONNECTING_ISODEP, " + ex); } } } class NfcClose implements Runnable { NfcPlugin nfcPlugin; CallbackContext callbackContext; NfcClose(NfcPlugin nfcPlugin, CallbackContext callbackContext) { this.nfcPlugin = nfcPlugin; this.callbackContext = callbackContext; } @Override public void run() { try { if (nfcPlugin.isoDep == null) { callbackContext.error("NO_TECH"); return; } if (!isoDep.isConnected()) { callbackContext.error("NOT_CONNECTED"); } nfcPlugin.isoDep.close(); nfcPlugin.isoDep = null; callbackContext.success(); } catch (IOException ex) { Log.e(ID, "Can't connect to IsoDep", ex); } } } class NfcTransceive implements Runnable { NfcPlugin nfcPlugin; JSONArray data; CallbackContext callbackContext; NfcTransceive(NfcPlugin nfcPlugin, JSONArray data, CallbackContext callbackContext) { this.nfcPlugin = nfcPlugin; this.data = data; this.callbackContext = callbackContext; } @Override public void run() { try { if (nfcPlugin.isoDep == null) { callbackContext.error("NO_TECH"); } if (!nfcPlugin.isoDep.isConnected()) { callbackContext.error("NOT_CONNECTED"); } String apdustring = data.getString(0); Pattern apdus = Pattern.compile("<apdu id=([^<]*)>([^<]*)</apdu>"); Matcher matcher = apdus.matcher(apdustring); String sendback = apdustring; while (matcher.find()) { byte[] commandAPDU = hexStringToByteArray(matcher.group(2)); byte[] responseAPDU = isoDep.transceive(commandAPDU); String id = String.format("id=%s", matcher.group(1)); String replacethis = matcher.group(0); String replacewith = "<apdu "+id+">"+byte2Hex(responseAPDU)+"</apdu>"; sendback = sendback.replaceFirst(replacethis, replacewith); } callbackContext.success(sendback); } catch (IOException ex) { Log.e(ID, "Can't connect to IsoDep", ex); } catch (JSONException ex) { Log.e(ID, "Can't get data", ex); } } } }
package org.wyona.yanel.servlet; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.net.URL; import java.util.Enumeration; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.wyona.yanel.core.Path; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.ResourceTypeDefinition; import org.wyona.yanel.core.ResourceTypeRegistry; import org.wyona.yanel.core.Yanel; import org.wyona.yanel.core.api.attributes.ModifiableV1; import org.wyona.yanel.core.api.attributes.ModifiableV2; import org.wyona.yanel.core.api.attributes.ViewableV1; import org.wyona.yanel.core.api.attributes.ViewableV2; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.core.map.Map; import org.wyona.yanel.core.map.MapFactory; import org.wyona.yanel.core.map.Realm; import org.wyona.yanel.util.ResourceAttributeHelper; import org.wyona.security.core.IdentityManagerFactory; import org.wyona.security.core.PolicyManagerFactory; import org.wyona.security.core.api.Identity; import org.wyona.security.core.api.IdentityManager; import org.wyona.security.core.api.PolicyManager; import org.wyona.security.core.api.Role; import org.apache.log4j.Category; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder; import org.w3c.dom.Document; import org.w3c.dom.Element; public class YanelServlet extends HttpServlet { private static Category log = Category.getInstance(YanelServlet.class); private ServletConfig config; ResourceTypeRegistry rtr; PolicyManager pm; IdentityManager im; Map map; Yanel yanel; private static String IDENTITY_KEY = "identity"; private static final String METHOD_PROPFIND = "PROPFIND"; private static final String METHOD_GET = "GET"; private static final String METHOD_POST = "POST"; private static final String METHOD_PUT = "PUT"; private static final String METHOD_DELETE = "DELETE"; public void init(ServletConfig config) { this.config = config; rtr = new ResourceTypeRegistry(); PolicyManagerFactory pmf = PolicyManagerFactory.newInstance(); pm = pmf.newPolicyManager(); IdentityManagerFactory imf = IdentityManagerFactory.newInstance(); im = imf.newIdentityManager(); MapFactory mf = MapFactory.newInstance(); map = mf.newMap(); yanel = new Yanel(); } public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String httpAcceptMediaTypes = request.getHeader("Accept"); log.debug("HTTP Accept Media Types: " + httpAcceptMediaTypes); String httpUserAgent = request.getHeader("User-Agent"); log.debug("HTTP User Agent: " + httpUserAgent); String httpAcceptLanguage = request.getHeader("Accept-Language"); log.debug("HTTP Accept Language: " + httpAcceptLanguage); // Logout from Yanel String yanelUsecase = request.getParameter("yanel.usecase"); if(yanelUsecase != null && yanelUsecase.equals("logout")) { if(doLogout(request, response) != null) return; } // Authentication if(doAuthenticate(request, response) != null) return; // Check authorization if(doAuthorize(request, response) != null) return; // Delegate ... String method = request.getMethod(); if (method.equals(METHOD_PROPFIND)) { doPropfind(request, response); } else if (method.equals(METHOD_GET)) { doGet(request, response); } else if (method.equals(METHOD_POST)) { doPost(request, response); } else if (method.equals(METHOD_PUT)) { doPut(request, response); } else if (method.equals(METHOD_DELETE)) { doDelete(request, response); } else { log.error("No such method implemented: " + method); } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { getContent(request, response); } private void getContent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { View view = null; org.w3c.dom.Document doc = null; javax.xml.parsers.DocumentBuilderFactory dbf= javax.xml.parsers.DocumentBuilderFactory.newInstance(); try { javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder(); org.w3c.dom.DOMImplementation impl = parser.getDOMImplementation(); org.w3c.dom.DocumentType doctype = null; doc = impl.createDocument("http: } catch(Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage()); } Element rootElement = doc.getDocumentElement(); String servletContextRealPath = config.getServletContext().getRealPath("/"); rootElement.setAttribute("servlet-context-real-path", servletContextRealPath); Element requestElement = (Element) rootElement.appendChild(doc.createElement("request")); requestElement.setAttribute("uri", request.getRequestURI()); requestElement.setAttribute("servlet-path", request.getServletPath()); HttpSession session = request.getSession(true); Element sessionElement = (Element) rootElement.appendChild(doc.createElement("session")); sessionElement.setAttribute("id", session.getId()); Enumeration attrNames = session.getAttributeNames(); if (!attrNames.hasMoreElements()) { Element sessionNoAttributesElement = (Element) sessionElement.appendChild(doc.createElement("no-attributes")); } while (attrNames.hasMoreElements()) { String name = (String)attrNames.nextElement(); String value = session.getAttribute(name).toString(); Element sessionAttributeElement = (Element) sessionElement.appendChild(doc.createElement("attribute")); sessionAttributeElement.setAttribute("name", name); sessionAttributeElement.appendChild(doc.createTextNode(value)); } String rti = map.getResourceTypeIdentifier(new Path(request.getServletPath())); Resource res = null; long lastModified = -1; if (rti != null) { ResourceTypeDefinition rtd = rtr.getResourceTypeDefinition(rti); if (rtd == null) { String message = "No such resource type registered: " + rti + ", check " + rtr.getConfigurationFile(); log.error(message); Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); setYanelOutput(response, doc); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } Element rtiElement = (Element) rootElement.appendChild(doc.createElement("resource-type-identifier")); rtiElement.setAttribute("namespace", rtd.getResourceTypeNamespace()); rtiElement.setAttribute("local-name", rtd.getResourceTypeLocalName()); try { res = rtr.newResource(rti); if (res != null) { // TODO: This has been already set by ResourceTypeRegistry res.setRTD(rtd); res.setYanel(yanel); Element resourceElement = (Element) rootElement.appendChild(doc.createElement("resource")); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "1")) { Element viewElement = (Element) resourceElement.appendChild(doc.createElement("view")); viewElement.appendChild(doc.createTextNode("View Descriptors: " + ((ViewableV1) res).getViewDescriptors())); String viewId = request.getParameter("yanel.resource.viewid"); try { view = ((ViewableV1) res).getView(request, viewId); } catch(org.wyona.yarep.core.NoSuchNodeException e) { // TODO: Log all 404 within a dedicated file (with client info attached) such that an admin can react to it ... String message = "No such node exception: " + e; log.warn(e); //log.error(e.getMessage(), e); Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); exceptionElement.setAttribute("status", "404"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND); setYanelOutput(response, doc); return; } catch(Exception e) { log.error(e.getMessage(), e); String message = e.toString(); log.error(e.getMessage(), e); Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); exceptionElement.setAttribute("status", "500"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(response, doc); return; } } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "2")) { log.error("DEBUG: Resource is viewable V2"); String viewId = request.getParameter("yanel.resource.viewid"); ((ViewableV2) res).getView(request, response, viewId); return; } else { Element noViewElement = (Element) resourceElement.appendChild(doc.createElement("no-view")); noViewElement.appendChild(doc.createTextNode(res.getClass().getName() + " is not viewable!")); } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) { lastModified = ((ModifiableV2) res).getLastModified(new Path(request.getServletPath())); Element lastModifiedElement = (Element) resourceElement.appendChild(doc.createElement("last-modified")); lastModifiedElement.appendChild(doc.createTextNode(new java.util.Date(lastModified).toString())); } else { Element noLastModifiedElement = (Element) resourceElement.appendChild(doc.createElement("no-last-modified")); } } else { Element resourceIsNullElement = (Element) rootElement.appendChild(doc.createElement("resource-is-null")); } } catch(Exception e) { log.error(e.getMessage(), e); String message = e.toString(); log.error(e.getMessage(), e); Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); setYanelOutput(response, doc); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } else { Element noRTIFoundElement = (Element) rootElement.appendChild(doc.createElement("no-resource-type-identifier-found")); noRTIFoundElement.setAttribute("servlet-path", request.getServletPath()); } String usecase = request.getParameter("yanel.resource.usecase"); if (usecase != null && usecase.equals("checkout")) { log.debug("Checkout data ..."); // TODO: Implement checkout ... log.warn("Acquire lock has not been implemented yet ...!"); // acquireLock(); } String meta = request.getParameter("yanel.resource.meta"); if (meta != null) { if (meta.length() > 0) { log.error("DEBUG: meta length: " + meta.length()); } else { log.error("DEBUG: Show all meta"); } response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); setYanelOutput(response, doc); return; } if (view != null) { response.setContentType(patchContentType(view.getMimeType(), request)); InputStream is = view.getInputStream(); byte buffer[] = new byte[8192]; int bytesRead; if (is != null) { // TODO: Yarep does not set returned Stream to null resp. is missing Exception Handling for the constructor. Exceptions should be handled here, but rather within Yarep or whatever repositary layer is being used ... bytesRead = is.read(buffer); if (bytesRead == -1) { String message = "InputStream of view does not seem to contain any data!"; Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); setYanelOutput(response, doc); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } // TODO: Compare If-Modified-Since with lastModified and return 304 without content resp. check on ETag String ifModifiedSince = request.getHeader("If-Modified-Since"); if (ifModifiedSince != null) { log.error("DEBUG: TODO: Implement 304 ..."); } java.io.OutputStream os = response.getOutputStream(); os.write(buffer, 0, bytesRead); while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } if(lastModified >= 0) response.setDateHeader("Last-Modified", lastModified); return; } else { String message = "InputStream of view is null!"; Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); } } else { String message = "View is null!"; Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); } setYanelOutput(response, doc); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String value = request.getParameter("yanel.resource.usecase"); if (value != null && value.equals("save")) { log.debug("Save data ..."); save(request, response); return; } else if (value != null && value.equals("checkin")) { log.debug("Checkin data ..."); save(request, response); // TODO: Implement checkin ... log.warn("Release lock has not been implemented yet ..."); // releaseLock(); return; } else { log.info("No parameter yanel.resource.usecase!"); String contentType = request.getContentType(); if (contentType.indexOf("application/atom+xml") >= 0) { InputStream in = intercept(request.getInputStream()); try { Resource atomEntry = rtr.newResource("<{http: // TODO: Initiate Atom Feed Resource Type to get actual path for saving ... log.error("DEBUG: Atom Feed: " + request.getServletPath() + " " + request.getRequestURI()); Path entryPath = new Path(request.getServletPath() + "/" + new java.util.Date().getTime() + ".xml"); Path p = ((ModifiableV2)atomEntry).write(entryPath, in); if (p != null) { log.error("DEBUG: Atom entry has been created: " + p); } else { log.error("Atom entry has NOT been created!"); // TODO: Return HTTP ... } byte buffer[] = new byte[8192]; int bytesRead; InputStream resourceIn = ((ModifiableV2)atomEntry).getInputStream(entryPath); OutputStream responseOut = response.getOutputStream(); while ((bytesRead = resourceIn.read(buffer)) != -1) { responseOut.write(buffer, 0, bytesRead); } // TODO: Fix Location ... response.setHeader("Location", "http://ulysses.wyona.org" + entryPath); response.setStatus(javax.servlet.http.HttpServletResponse.SC_CREATED); return; } catch (Exception e) { log.error(e.getMessage(), e); throw new IOException(e.getMessage()); } } getContent(request, response); } } /** * HTTP PUT implementation */ public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO: Reuse code doPost resp. share code with doPut String value = request.getParameter("yanel.resource.usecase"); if (value != null && value.equals("save")) { log.debug("Save data ..."); save(request, response); return; } else if (value != null && value.equals("checkin")) { log.debug("Checkin data ..."); save(request, response); // TODO: Implement checkin ... log.warn("Release lock has not been implemented yet ...!"); // releaseLock(); return; } else { log.warn("No parameter yanel.resource.usecase!"); String contentType = request.getContentType(); if (contentType.indexOf("application/atom+xml") >= 0) { InputStream in = intercept(request.getInputStream()); try { Resource atomEntry = rtr.newResource("<{http: log.error("DEBUG: Atom Entry: " + request.getServletPath() + " " + request.getRequestURI()); Path entryPath = new Path(request.getServletPath()); // TODO: There seems to be a problem ... Path p = ((ModifiableV2)atomEntry).write(entryPath, in); // NOTE: This method does not update updated date /* OutputStream out = ((ModifiableV2)atomEntry).getOutputStream(entryPath); byte buffer[] = new byte[8192]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } */ log.error("DEBUG: Atom entry has been saved: " + entryPath); response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); return; } catch (Exception e) { log.error(e.getMessage(), e); throw new IOException(e.getMessage()); } } else { save(request, response); /* log.warn("TODO: WebDAV PUT ..."); response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_IMPLEMENTED); return; */ } } } /** * HTTP DELETE implementation */ public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Resource res = getResource(request); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) { if (((ModifiableV2) res).delete(new Path(request.getServletPath()))) { log.debug("Resource has been deleted: " + res); response.setStatus(response.SC_OK); return; } else { log.warn("Resource could not be deleted: " + res); response.setStatus(response.SC_FORBIDDEN); return; } } else { log.error("Resource '" + res + "' has interface ModifiableV2 not implemented." ); response.sendError(response.SC_NOT_IMPLEMENTED); return; } } private Resource getResource(HttpServletRequest request) { String rti = map.getResourceTypeIdentifier(new Path(request.getServletPath())); if (rti != null) { ResourceTypeDefinition rtd = rtr.getResourceTypeDefinition(rti); try { Resource res = rtr.newResource(rti); // TODO: This has been already set by ResourceTypeRegistry res.setRTD(rtd); res.setYanel(yanel); return res; } catch(Exception e) { log.error(e.getMessage(), e); return null; } } else { log.error("<no-resource-type-identifier-found servlet-path=\""+request.getServletPath()+"\"/>"); return null; } } private void save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Save data ..."); InputStream in = request.getInputStream(); java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); byte[] buf = new byte[8192]; int bytesR; while ((bytesR = in.read(buf)) != -1) { baos.write(buf, 0, bytesR); } // Buffer within memory (TODO: Maybe replace with File-buffering ...) byte[] memBuffer = baos.toByteArray(); // Check on well-formedness ... String contentType = request.getContentType(); log.debug("Content-Type: " + contentType); if (contentType.indexOf("application/xml") >= 0 || contentType.indexOf("application/xhtml+xml") >= 0) { log.info("Check well-formedness ..."); javax.xml.parsers.DocumentBuilderFactory dbf= javax.xml.parsers.DocumentBuilderFactory.newInstance(); try { javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder(); // TODO: Get log messages into log4j ... //parser.setErrorHandler(...); // NOTE: DOCTYPE is being resolved/retrieved (e.g. xhtml schema from w3.org) also // if isValidating is set to false. // Hence, for performance and network reasons we use a local catalog ... // TODO: What about a resolver factory? parser.setEntityResolver(new org.apache.xml.resolver.tools.CatalogResolver()); parser.parse(new java.io.ByteArrayInputStream(memBuffer)); //org.w3c.dom.Document document = parser.parse(new ByteArrayInputStream(memBuffer)); } catch (org.xml.sax.SAXException e) { log.warn("Data is not well-formed: "+e.getMessage()); StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: sb.append("<message>Data is not well-formed: "+e.getMessage()+"</message>"); sb.append("</exception>"); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); PrintWriter w = response.getWriter(); w.print(sb); return; } catch (Exception e) { log.error(e.getMessage(), e); StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: //sb.append("<message>" + e.getStackTrace() + "</message>"); //sb.append("<message>" + e.getMessage() + "</message>"); sb.append("<message>" + e + "</message>"); sb.append("</exception>"); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); PrintWriter w = response.getWriter(); w.print(sb); return; } log.info("Data seems to be well-formed :-)"); } else { log.info("No well-formedness check required for content type: " + contentType); } /* if (bytesRead == -1) { response.setContentType("text/plain"); PrintWriter writer = response.getWriter(); writer.print("No content!"); return; } */ OutputStream out = null; Resource res = getResource(request); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "1")) { out = ((ModifiableV1) res).getOutputStream(new Path(request.getServletPath())); } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) { out = ((ModifiableV2) res).getOutputStream(new Path(request.getServletPath())); } else { String message = res.getClass().getName() + " is not modifiable (neither V1 nor V2)!"; log.warn(message); StringBuffer sb = new StringBuffer(); // TODO: Differentiate between Neutron based and other clients ... /* sb.append("<?xml version=\"1.0\"?>"); sb.append("<html>"); sb.append("<body>"); sb.append("<resource>" + message + "</resource>"); sb.append("</body>"); sb.append("</html>"); response.setContentType("application/xhtml+xml"); */ sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: sb.append("<message>" + message + "</message>"); sb.append("</exception>"); response.setContentType("application/xml"); PrintWriter w = response.getWriter(); w.print(sb); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } if (out != null) { log.debug("Content-Type: " + contentType); // TODO: Compare mime-type from response with mime-type of resource //if (contentType.equals("text/xml")) { ... } byte[] buffer = new byte[8192]; int bytesRead; java.io.ByteArrayInputStream memIn = new java.io.ByteArrayInputStream(memBuffer); while ((bytesRead = memIn.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<html>"); sb.append("<body>"); sb.append("<p>Data has been saved ...</p>"); sb.append("</body>"); sb.append("</html>"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); response.setContentType("application/xhtml+xml"); PrintWriter w = response.getWriter(); w.print(sb); log.info("Data has been saved ..."); return; } else { log.error("OutputStream is null!"); StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<html>"); sb.append("<body>"); sb.append("<p>Exception: OutputStream is null!</p>"); sb.append("</body>"); sb.append("</html>"); PrintWriter w = response.getWriter(); w.print(sb); response.setContentType("application/xhtml+xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } /** * Authorize request */ private HttpServletResponse doAuthorize(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Role role = null; // TODO: Replace hardcoded roles by mapping between roles amd query strings ... String value = request.getParameter("yanel.resource.usecase"); String contentType = request.getContentType(); String method = request.getMethod(); if (value != null && value.equals("save")) { log.debug("Save data ..."); role = new Role("write"); } else if (value != null && value.equals("checkin")) { log.debug("Checkin data ..."); role = new Role("write"); } else if (value != null && value.equals("checkout")) { log.debug("Checkout data ..."); role = new Role("open"); } else if (contentType != null && contentType.indexOf("application/atom+xml") >= 0 && (method.equals(METHOD_PUT) || method.equals(METHOD_POST))) { log.error("DEBUG: Write/Checkin Atom entry ..."); role = new Role("write"); } else if (method.equals(METHOD_DELETE)) { log.error("DEBUG: Delete resource ..."); role = new Role("delete"); } else { log.debug("Role will be 'view'!"); role = new Role("view"); } boolean authorized = false; // HTTP BASIC Authorization (For clients without session handling, e.g. OpenOffice or cadaver) String authorization = request.getHeader("Authorization"); log.debug("Checking for Authorization Header: " + authorization); if (authorization != null) { if (authorization.toUpperCase().startsWith("BASIC")) { log.debug("Using BASIC authorization ..."); // Get encoded user and password, comes after "BASIC " String userpassEncoded = authorization.substring(6); // Decode it, using any base 64 decoder sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder(); String userpassDecoded = new String(dec.decodeBuffer(userpassEncoded)); log.error("DEBUG: userpassDecoded: " + userpassDecoded); // TODO: Use security package and remove hardcoded ... // Authenticate every request ... //if (im.authenticate(...)) { if (userpassDecoded.equals("lenya:levi")) { //return pm.authorize(new org.wyona.commons.io.Path(request.getServletPath()), new Identity(...), new Role("view")); authorized = true; return null; } authorized = false; response.setHeader("WWW-Authenticate", "BASIC realm=\"yanel\""); response.sendError(response.SC_UNAUTHORIZED); PrintWriter writer = response.getWriter(); writer.print("BASIC Authorization/Authentication Failed!"); return response; } else if (authorization.toUpperCase().startsWith("DIGEST")) { log.error("DIGEST is not implemented"); authorized = false; response.sendError(response.SC_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "DIGEST realm=\"yanel\""); PrintWriter writer = response.getWriter(); writer.print("DIGEST is not implemented!"); return response; } else { log.warn("No such authorization implemented resp. handled by session based authorization: " + authorization); authorized = false; } } // Custom Authorization log.debug("Do session based custom authorization"); //String[] groupnames = {"null", "null"}; HttpSession session = request.getSession(true); Identity identity = (Identity) session.getAttribute(IDENTITY_KEY); if (identity == null) { log.debug("Identity is WORLD"); identity = new Identity(); } authorized = pm.authorize(new org.wyona.commons.io.Path(request.getServletPath()), identity, role); if(!authorized) { log.warn("Access denied: " + getRequestURLQS(request, null, false)); // TODO: Shouldn't this be here instead at the beginning of service() ...? //if(doAuthenticate(request, response) != null) return response; // HTTP Authorization/Authentication // TODO: Ulysses has not HTTP BASIC or DIGEST implemented yet! /* response.setHeader("WWW-Authenticate", "BASIC realm=\"yanel\""); response.sendError(response.SC_UNAUTHORIZED); */ // Custom Authorization/Authentication // TODO: Check if this is a neutron request or just a common GET request StringBuffer sb = new StringBuffer(""); String neutronVersions = request.getHeader("Neutron"); String clientSupportedAuthScheme = request.getHeader("WWW-Authenticate"); Realm realm = map.getRealm(new Path(request.getServletPath())); if (clientSupportedAuthScheme != null && clientSupportedAuthScheme.equals("Neutron-Auth")) { log.debug("Neutron Versions supported by client: " + neutronVersions); log.debug("Authentication Scheme supported by client: " + clientSupportedAuthScheme); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: sb.append("<message>Authorization denied: " + getRequestURLQS(request, null, true) + "</message>"); sb.append("<authentication>"); sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>"); //TODO: Also support https ... sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">"); sb.append("<form>"); sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>"); sb.append("<param description=\"Username\" name=\"username\"/>"); sb.append("<param description=\"Password\" name=\"password\"/>"); sb.append("</form>"); sb.append("</login>"); // NOTE: Needs to be a full URL, because user might switch the server ... sb.append("<logout url=\"" + getRequestURLQS(request, "yanel.usecase=logout", true) + "\" realm=\"" + realm.getName() + "\"/>"); sb.append("</authentication>"); sb.append("</exception>"); log.debug("Neutron-Auth response: " + sb); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "NEUTRON-AUTH"); } else { // Custom HTML Form authentication // TODO: Use configurable XSLT for layout, whereas each realm should be able to overwrite ... sb.append("<?xml version=\"1.0\"?>"); sb.append("<html xmlns=\"http: sb.append("<body>"); sb.append("<p>Authorization denied: " + getRequestURLQS(request, null, true) + "</p>"); sb.append("<p>Enter username and password for realm \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\" (Context Path: " + request.getContextPath() + ")</p>"); sb.append("<form method=\"POST\">"); sb.append("<p>"); sb.append("<table>"); sb.append("<tr><td>Username:</td><td>&#160;</td><td><input type=\"text\" name=\"yanel.login.username\"/></td></tr>"); sb.append("<tr><td>Password:</td><td>&#160;</td><td><input type=\"password\" name=\"yanel.login.password\"/></td></tr>"); sb.append("<tr><td colspan=\"2\">&#160;</td><td align=\"right\"><input type=\"submit\" value=\"Login\"/></td></tr>"); sb.append("</table>"); sb.append("</p>"); sb.append("</form>"); sb.append("</body>"); sb.append("</html>"); response.setContentType("application/xhtml+xml"); } PrintWriter w = response.getWriter(); w.print(sb); return response; } else { log.info("Access granted: " + getRequestURLQS(request, null, false)); return null; } } private String getRequestURLQS(HttpServletRequest request, String addQS, boolean xml) { Realm realm = map.getRealm(new Path(request.getServletPath())); String proxyHostName = realm.getProxyHostName(); String proxyPort = realm.getProxyPort(); String proxyPrefix = realm.getProxyPrefix(); URL url = null; try { url = new URL(request.getRequestURL().toString()); if (proxyHostName != null) { url = new URL(url.getProtocol(), proxyHostName, url.getPort(), url.getFile()); } if (proxyPort != null) { if (proxyPort.length() > 0) { url = new URL(url.getProtocol(), url.getHost(), new Integer(proxyPort).intValue(), url.getFile()); } else { url = new URL(url.getProtocol(), url.getHost(), url.getDefaultPort(), url.getFile()); } } if (proxyPrefix != null) { url = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile().substring(proxyPrefix.length())); } if(proxyHostName != null || proxyPort != null || proxyPrefix != null) { log.debug("Proxy enabled request: " + url); } } catch (Exception e) { log.error(e); } String urlQS = url.toString(); if (request.getQueryString() != null) { urlQS = urlQS + "?" + request.getQueryString(); if (addQS != null) urlQS = urlQS + "&" + addQS; } else { if (addQS != null) urlQS = urlQS + "?" + addQS; } if (xml) urlQS = urlQS.replaceAll("&", "&amp;"); log.debug("Request: " + urlQS); return urlQS; } public void doPropfind(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { getContent(request, response); } public HttpServletResponse doAuthenticate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Realm realm = map.getRealm(new Path(request.getServletPath())); // HTML Form based authentication String loginUsername = request.getParameter("yanel.login.username"); if(loginUsername != null) { HttpSession session = request.getSession(true); if (im.authenticate(loginUsername, request.getParameter("yanel.login.password"), realm.getID())) { log.debug("Realm: " + realm); session.setAttribute(IDENTITY_KEY, new Identity(loginUsername, null)); return null; } else { log.warn("Login failed: " + loginUsername); // TODO: Implement form based response ... response.setHeader("WWW-Authenticate", "BASIC realm=\"yanel\""); response.sendError(response.SC_UNAUTHORIZED); return response; } } // Neutron-Auth based authentication String yanelUsecase = request.getParameter("yanel.usecase"); if(yanelUsecase != null && yanelUsecase.equals("neutron-auth")) { log.debug("Neutron Authentication ..."); String username = null; String password = null; String originalRequest = null; DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder(); try { Configuration config = builder.build(request.getInputStream()); Configuration originalRequestConfig = config.getChild("original-request"); originalRequest = originalRequestConfig.getAttribute("url", null); Configuration[] paramConfig = config.getChildren("param"); for (int i = 0; i < paramConfig.length; i++) { String paramName = paramConfig[i].getAttribute("name", null); if (paramName != null) { if (paramName.equals("username")) { username = paramConfig[i].getValue(); } else if (paramName.equals("password")) { password = paramConfig[i].getValue(); } } } } catch(Exception e) { log.warn(e); } log.debug("Username: " + username); if (username != null) { HttpSession session = request.getSession(true); log.debug("Realm ID: " + realm.getID()); if (im.authenticate(username, password, realm.getID())) { log.info("Authentication successful: " + username); session.setAttribute(IDENTITY_KEY, new Identity(username, null)); // TODO: send some XML content, e.g. <authentication-successful/> response.setContentType("text/plain"); response.setStatus(response.SC_OK); PrintWriter writer = response.getWriter(); writer.print("Neutron Authentication Successful!"); return response; } else { log.warn("Neutron Authentication failed: " + username); // TODO: Refactor this code with the one from doAuthenticate ... log.debug("Original Request: " + originalRequest); StringBuffer sb = new StringBuffer(""); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: sb.append("<message>Authentication failed!</message>"); sb.append("<authentication>"); // TODO: ... sb.append("<original-request url=\"" + originalRequest + "\"/>"); //sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>"); //TODO: Also support https ... // TODO: ... sb.append("<login url=\"" + originalRequest + "&amp;yanel.usecase=neutron-auth" + "\" method=\"POST\">"); //sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">"); sb.append("<form>"); sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>"); sb.append("<param description=\"Username\" name=\"username\"/>"); sb.append("<param description=\"Password\" name=\"password\"/>"); sb.append("</form>"); sb.append("</login>"); // NOTE: Needs to be a full URL, because user might switch the server ... // TODO: ... sb.append("<logout url=\"" + originalRequest + "&amp;yanel.usecase=logout" + "\" realm=\"" + realm.getName() + "\"/>"); sb.append("</authentication>"); sb.append("</exception>"); log.debug("Neutron-Auth response: " + sb); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "NEUTRON-AUTH"); PrintWriter w = response.getWriter(); w.print(sb); return response; } } else { // TODO: Refactor resp. reuse response from above ... log.warn("Neutron Authentication failed because username is NULL!"); StringBuffer sb = new StringBuffer(""); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: sb.append("<message>Authentication failed because no username was sent!</message>"); sb.append("<authentication>"); // TODO: ... sb.append("<original-request url=\"" + originalRequest + "\"/>"); //sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>"); //TODO: Also support https ... // TODO: ... sb.append("<login url=\"" + originalRequest + "&amp;yanel.usecase=neutron-auth" + "\" method=\"POST\">"); //sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">"); sb.append("<form>"); sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>"); sb.append("<param description=\"Username\" name=\"username\"/>"); sb.append("<param description=\"Password\" name=\"password\"/>"); sb.append("</form>"); sb.append("</login>"); // NOTE: Needs to be a full URL, because user might switch the server ... // TODO: ... sb.append("<logout url=\"" + originalRequest + "&amp;yanel.usecase=logout" + "\" realm=\"" + realm.getName() + "\"/>"); sb.append("</authentication>"); sb.append("</exception>"); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "NEUTRON-AUTH"); PrintWriter writer = response.getWriter(); writer.print(sb); return response; } } else { log.debug("Neutron Authentication successful."); return null; } } public HttpServletResponse doLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.info("Logout from Yanel ..."); HttpSession session = request.getSession(true); session.setAttribute(IDENTITY_KEY, null); String clientSupportedAuthScheme = request.getHeader("WWW-Authenticate"); if (clientSupportedAuthScheme != null && clientSupportedAuthScheme.equals("Neutron-Auth")) { // TODO: send some XML content, e.g. <logout-successful/> response.setContentType("text/plain"); response.setStatus(response.SC_OK); PrintWriter writer = response.getWriter(); writer.print("Neutron Logout Successful!"); return response; } return null; } public String patchContentType(String contentType, HttpServletRequest request) throws ServletException, IOException { String httpAcceptMediaTypes = request.getHeader("Accept"); log.debug("HTTP Accept Media Types: " + httpAcceptMediaTypes); if (contentType != null && contentType.equals("application/xhtml+xml") && httpAcceptMediaTypes != null && httpAcceptMediaTypes.indexOf("application/xhtml+xml") < 0) { log.error("DEBUG: Patch contentType with text/html because client (" + request.getHeader("User-Agent") + ") does not seem to understand application/xhtml+xml"); return "text/html"; } return contentType; } /** * Intercept InputStream and log content ... */ public InputStream intercept(InputStream in) throws IOException { java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); byte[] buf = new byte[8192]; int bytesR; while ((bytesR = in.read(buf)) != -1) { baos.write(buf, 0, bytesR); } // Buffer within memory (TODO: Maybe replace with File-buffering ...) byte[] memBuffer = baos.toByteArray(); log.error("DEBUG: InputStream: " + baos); return new java.io.ByteArrayInputStream(memBuffer); } private void setYanelOutput(HttpServletResponse response, Document doc) throws ServletException { response.setContentType("application/xml"); try { javax.xml.transform.TransformerFactory.newInstance().newTransformer().transform(new javax.xml.transform.dom.DOMSource(doc), new javax.xml.transform.stream.StreamResult(response.getWriter())); /* OutputStream out = response.getOutputStream(); javax.xml.transform.TransformerFactory.newInstance().newTransformer().transform(new javax.xml.transform.dom.DOMSource(doc), new javax.xml.transform.stream.StreamResult(out)); out.close(); */ } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage()); } } }
package models; import java.util.List; /** * Data access object for Question objects. It helps to perform database operations on the Question table in the database. */ public class CategoryDAO { /** * Constructor for CategoryDAO */ public CategoryDAO() {} /** * Searches the database for the Category where the ID field is the same as id. * @param id The ID of the Category we want to retrieve. * @return The Category where id matches ID or null if no matches were found. */ public Category getCategory(Long id) { return Category.find.byId(id); } /** * Searches by ID to find the Category and then deletes this Category from the database. * @param id The ID of the Category we want to delete. */ public void deleteCategory(Long id) { Category.find.byId(id).delete(); } /** * Gives a List of all of the Category objects in the database. * @return A List of all Category objects in the database. */ public List<Category> getAllCategories() { return Category.find.all(); } }
package com.africastalking; import retrofit2.Call; import retrofit2.http.*; interface IVoice { @FormUrlEncoded @POST("call") Call<String> call(@Field("username") String username, @Field("to") String to, @Field("from") String from); @FormUrlEncoded @POST("/queueStatus") Call<String> queueStatus(@Field("username") String username, @Field("phoneNumbers") String phoneNumbers); @FormUrlEncoded @POST("/mediaUpload") Call<String> mediaUpload(@Field("username") String username, @Field("url") String url, @Field("phoneNumber") String phoneNumber); }
package org.jenkinsci.plugins.workflow.job; import org.jenkinsci.plugins.workflow.actions.TimingAction; import org.jenkinsci.plugins.workflow.flow.FlowExecutionList; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import hudson.AbortException; import hudson.Extension; import hudson.FilePath; import hudson.XmlFile; import hudson.console.AnnotatedLargeText; import hudson.model.AbstractBuild; import hudson.model.Computer; import hudson.model.Executor; import hudson.model.Queue; import hudson.model.Result; import hudson.model.Run; import hudson.model.StreamBuildListener; import hudson.model.TaskListener; import hudson.model.listeners.RunListener; import hudson.model.listeners.SCMListener; import hudson.scm.ChangeLogSet; import hudson.scm.SCM; import hudson.scm.SCMRevisionState; import hudson.util.NullStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; import jenkins.model.CauseOfInterruption; import jenkins.model.InterruptedBuildAction; import jenkins.model.Jenkins; import jenkins.model.lazy.BuildReference; import jenkins.model.lazy.LazyBuildMixIn; import org.jenkinsci.plugins.workflow.actions.LogAction; import org.jenkinsci.plugins.workflow.flow.FlowDefinition; import org.jenkinsci.plugins.workflow.flow.FlowExecution; import org.jenkinsci.plugins.workflow.flow.FlowExecutionOwner; import org.jenkinsci.plugins.workflow.flow.GraphListener; import org.jenkinsci.plugins.workflow.graph.FlowEndNode; import org.jenkinsci.plugins.workflow.graph.FlowNode; import org.jenkinsci.plugins.workflow.steps.FlowInterruptedException; import org.kohsuke.stapler.HttpResponse; import org.kohsuke.stapler.HttpResponses; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.interceptor.RequirePOST; @SuppressWarnings("SynchronizeOnNonFinalField") @edu.umd.cs.findbugs.annotations.SuppressWarnings("JLM_JSR166_UTILCONCURRENT_MONITORENTER") // completed is an unusual usage public final class WorkflowRun extends Run<WorkflowJob,WorkflowRun> implements Queue.Executable, LazyBuildMixIn.LazyLoadingRun<WorkflowJob,WorkflowRun> { private static final Logger LOGGER = Logger.getLogger(WorkflowRun.class.getName()); /** null until started */ private @Nullable FlowExecution execution; /** * {@link Future} that yields {@link #execution}, when it is fully configured and ready to be exposed. */ private transient SettableFuture<FlowExecution> executionPromise = SettableFuture.create(); private transient final LazyBuildMixIn.RunMixIn<WorkflowJob,WorkflowRun> runMixIn = new LazyBuildMixIn.RunMixIn<WorkflowJob,WorkflowRun>() { @Override protected WorkflowRun asRun() { return WorkflowRun.this; } }; private transient StreamBuildListener listener; private transient AtomicBoolean completed; /** Jenkins instance in effect when {@link #waitForCompletion} was last called. */ private transient Jenkins jenkins; /** map from node IDs to log positions from which we should copy text */ private Map<String,Long> logsToCopy; List<SCMCheckout> checkouts; // TODO could use a WeakReference to reduce memory, but that complicates how we add to it incrementally; perhaps keep a List<WeakReference<ChangeLogSet<?>>> private transient List<ChangeLogSet<? extends ChangeLogSet.Entry>> changeSets; public WorkflowRun(WorkflowJob job) throws IOException { super(job); //System.err.printf("created %s @%h%n", this, this); } public WorkflowRun(WorkflowJob job, File dir) throws IOException { super(job, dir); //System.err.printf("loaded %s @%h%n", this, this); } @Override public LazyBuildMixIn.RunMixIn<WorkflowJob,WorkflowRun> getRunMixIn() { return runMixIn; } @Override protected BuildReference<WorkflowRun> createReference() { return getRunMixIn().createReference(); } @Override protected void dropLinks() { getRunMixIn().dropLinks(); } @Exported @Override public WorkflowRun getPreviousBuild() { return getRunMixIn().getPreviousBuild(); } @Exported @Override public WorkflowRun getNextBuild() { return getRunMixIn().getNextBuild(); } /** * Actually executes the workflow. */ @Override public void run() { // Some code here copied from execute(RunExecution), but subsequently modified quite a bit. try { onStartBuilding(); OutputStream logger = new FileOutputStream(getLogFile()); listener = new StreamBuildListener(logger, Charset.defaultCharset()); listener.started(getCauses()); RunListener.fireStarted(this, listener); updateSymlinks(listener); FlowDefinition definition = getParent().getDefinition(); if (definition == null) { listener.error("No flow definition, cannot run"); return; } Owner owner = new Owner(this); execution = definition.create(owner, getAllActions()); FlowExecutionList.get().register(owner); execution.addListener(new GraphL()); completed = new AtomicBoolean(); logsToCopy = new LinkedHashMap<String,Long>(); checkouts = new LinkedList<SCMCheckout>(); execution.start(); executionPromise.set(execution); waitForCompletion(); } catch (Exception x) { if (listener == null) { LOGGER.log(Level.WARNING, this + " failed to start", x); } else { x.printStackTrace(listener.error("failed to start build")); } setResult(Result.FAILURE); executionPromise.setException(x); } } /** * Sleeps until the run is finished, updating log messages periodically. */ void waitForCompletion() { jenkins = Jenkins.getInstance(); synchronized (completed) { while (!completed.get()) { if (jenkins == null || jenkins.isTerminating()) { LOGGER.log(Level.FINE, "shutting down, breaking waitForCompletion on {0}", this); // Stop writing content, in case a new set of objects gets loaded after in-VM restart and starts writing to the same file: listener.closeQuietly(); listener = new StreamBuildListener(new NullStream()); break; } try { completed.wait(1000); } catch (InterruptedException x) { try { execution.interrupt(Result.ABORTED); } catch (Exception x2) { LOGGER.log(Level.WARNING, null, x2); } Executor exec = Executor.currentExecutor(); if (exec != null) { exec.recordCauseOfInterruption(this, listener); } } copyLogs(); } } } @GuardedBy("completed") private void copyLogs() { if (logsToCopy == null) { // finished return; } Iterator<Map.Entry<String,Long>> it = logsToCopy.entrySet().iterator(); boolean modified = false; while (it.hasNext()) { Map.Entry<String,Long> entry = it.next(); FlowNode node; try { node = execution.getNode(entry.getKey()); } catch (IOException x) { LOGGER.log(Level.WARNING, null, x); it.remove(); modified = true; continue; } if (node == null) { LOGGER.log(Level.WARNING, "no such node {0}", entry.getKey()); it.remove(); modified = true; continue; } LogAction la = node.getAction(LogAction.class); if (la != null) { AnnotatedLargeText<? extends FlowNode> logText = la.getLogText(); try { long old = entry.getValue(); long revised = logText.writeRawLogTo(old, listener.getLogger()); if (revised != old) { entry.setValue(revised); modified = true; } if (logText.isComplete()) { logText.writeRawLogTo(entry.getValue(), listener.getLogger()); // defend against race condition? assert !node.isRunning() : "LargeText.complete yet " + node + " claims to still be running"; it.remove(); modified = true; } } catch (IOException x) { LOGGER.log(Level.WARNING, null, x); it.remove(); modified = true; } } else if (!node.isRunning()) { it.remove(); modified = true; } } if (modified) { try { save(); } catch (IOException x) { LOGGER.log(Level.WARNING, null, x); } } } private static final Map<String,WorkflowRun> LOADING_RUNS = new HashMap<String,WorkflowRun>(); private String key() { return getParent().getFullName() + '/' + getId(); } /** Hack to allow {@link #execution} to use an {@link Owner} referring to this run, even when it has not yet been loaded. */ @Override public void reload() throws IOException { synchronized (LOADING_RUNS) { LOADING_RUNS.put(key(), this); } // super.reload() forces result to be FAILURE, so working around that new XmlFile(XSTREAM,new File(getRootDir(),"build.xml")).unmarshal(this); } @Override protected void onLoad() { super.onLoad(); if (execution != null) { execution.onLoad(); execution.addListener(new GraphL()); executionPromise.set(execution); if (!execution.isComplete()) { // we've been restarted while we were running. let's get the execution going again. try { OutputStream logger = new FileOutputStream(getLogFile(), true); listener = new StreamBuildListener(logger, Charset.defaultCharset()); listener.getLogger().println("Resuming build"); } catch (IOException x) { LOGGER.log(Level.WARNING, null, x); listener = new StreamBuildListener(new NullStream()); } completed = new AtomicBoolean(); Queue.getInstance().schedule(new AfterRestartTask(this), 0); } } synchronized (LOADING_RUNS) { LOADING_RUNS.remove(key()); // or could just make the value type be WeakReference<WorkflowRun> LOADING_RUNS.notifyAll(); } } // Overridden since super version has an unwanted assertion about this.state, which we do not use. @Override public void setResult(Result r) { if (result == null || r.isWorseThan(result)) { result = r; LOGGER.log(Level.FINE, this + " in " + getRootDir() + ": result is set to " + r, LOGGER.isLoggable(Level.FINER) ? new Exception() : null); } } private void finish(Result r) { LOGGER.log(Level.INFO, "{0} completed: {1}", new Object[] {this, r}); setResult(r); // TODO set duration RunListener.fireCompleted(WorkflowRun.this, listener); Throwable t = execution.getCauseOfFailure(); if (t instanceof AbortException) { listener.error(t.getMessage()); } else if (t instanceof FlowInterruptedException) { List<CauseOfInterruption> causes = ((FlowInterruptedException) t).getCauses(); addAction(new InterruptedBuildAction(causes)); for (CauseOfInterruption cause : causes) { cause.print(listener); } } else if (t != null) { t.printStackTrace(listener.getLogger()); } listener.finished(getResult()); listener.closeQuietly(); logsToCopy = null; duration = Math.max(0, System.currentTimeMillis() - getStartTimeInMillis()); try { save(); getParent().logRotate(); } catch (Exception x) { LOGGER.log(Level.WARNING, null, x); } onEndBuilding(); assert completed != null; synchronized (completed) { completed.set(true); completed.notifyAll(); } FlowExecutionList.get().unregister(execution.getOwner()); } /** * Gets the associated execution state. * @return non-null after the flow has started, even after finished (but may be null temporarily when about to start, or if starting failed) */ public @CheckForNull FlowExecution getExecution() { return execution; } /** * Allows the caller to block on {@link FlowExecution}, which gets created relatively quickly * after the build gets going. */ public ListenableFuture<FlowExecution> getExecutionPromise() { return executionPromise; } @Override public boolean hasntStartedYet() { return result == null && execution==null; } @Override public boolean isBuilding() { return result == null || isInProgress(); } @Exported @Override protected boolean isInProgress() { return execution != null && !execution.isComplete(); } @Override public boolean isLogUpdated() { return isBuilding(); // there is no equivalent to a post-production state for flows } @Exported public synchronized List<ChangeLogSet<? extends ChangeLogSet.Entry>> getChangeSets() { if (changeSets == null) { changeSets = new ArrayList<ChangeLogSet<? extends ChangeLogSet.Entry>>(); if (checkouts == null) { LOGGER.log(Level.WARNING, "no checkouts in {0}", this); return changeSets; } for (SCMCheckout co : checkouts) { if (co.changelogFile != null && co.changelogFile.isFile()) { try { changeSets.add(co.scm.createChangeLogParser().parse(this, co.scm.getEffectiveBrowser(), co.changelogFile)); } catch (Exception x) { LOGGER.log(Level.WARNING, "could not parse " + co.changelogFile, x); } } } } return changeSets; } /** TODO {@link AbstractBuild#doStop} could be pulled up into {@link Run} making this unnecessary. */ @RequirePOST public synchronized HttpResponse doStop() { Executor e = getOneOffExecutor(); if (e != null) { return e.doStop(); } else { return HttpResponses.forwardToPreviousPage(); } } @Override public Executor getExecutor() { return getOneOffExecutor(); } @Exported @Override public Executor getOneOffExecutor() { Jenkins j = Jenkins.getInstance(); if (j != null) { for (Computer c : j.getComputers()) { for (Executor e : c.getOneOffExecutors()) { Queue.Executable exec = e.getCurrentExecutable(); if (exec == this || (exec instanceof AfterRestartTask.Body && ((AfterRestartTask.Body) exec).run == this)) { return e; } } } } return null; } private void onCheckout(SCM scm, FilePath workspace, @CheckForNull File changelogFile, @CheckForNull SCMRevisionState pollingBaseline) throws Exception { if (changelogFile != null && changelogFile.isFile()) { ChangeLogSet<?> cls = scm.createChangeLogParser().parse(this, scm.getEffectiveBrowser(), changelogFile); getChangeSets().add(cls); for (SCMListener l : SCMListener.all()) { l.onChangeLogParsed(this, scm, listener, cls); } } String node = null; // TODO: switch to FilePath.toComputer in 1.571 Jenkins j = Jenkins.getInstance(); if (j != null) { for (Computer c : j.getComputers()) { if (workspace.getChannel() == c.getChannel()) { node = c.getName(); break; } } } if (node == null) { throw new IllegalStateException(); } checkouts.add(new SCMCheckout(scm, node, workspace.getRemote(), changelogFile, pollingBaseline)); } static final class SCMCheckout { final SCM scm; final String node; final String workspace; // TODO make this a String and relativize to Run.rootDir if possible final @CheckForNull File changelogFile; final @CheckForNull SCMRevisionState pollingBaseline; SCMCheckout(SCM scm, String node, String workspace, File changelogFile, SCMRevisionState pollingBaseline) { this.scm = scm; this.node = node; this.workspace = workspace; this.changelogFile = changelogFile; this.pollingBaseline = pollingBaseline; } } private static final class Owner extends FlowExecutionOwner { private final String job; private final String id; private transient @CheckForNull WorkflowRun run; Owner(WorkflowRun run) { job = run.getParent().getFullName(); id = run.getId(); this.run = run; } private String key() { return job + '/' + id; } private @Nonnull WorkflowRun run() throws IOException { if (run==null) { WorkflowRun candidate; synchronized (LOADING_RUNS) { candidate = LOADING_RUNS.get(key()); } if (candidate != null && candidate.getParent().getFullName().equals(job) && candidate.getId().equals(id)) { run = candidate; } else { Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { throw new IOException("Jenkins is not running"); } WorkflowJob j = jenkins.getItemByFullName(job, WorkflowJob.class); if (j == null) { throw new IOException("no such WorkflowJob " + job); } run = j._getRuns().getById(id); if (run == null) { throw new IOException("no such build " + id + " in " + job); } //System.err.printf("getById found %s @%h%n", run, run); } } return run; } @Override public FlowExecution get() throws IOException { WorkflowRun r = run(); synchronized (LOADING_RUNS) { while (r.execution == null && LOADING_RUNS.containsKey(key())) { try { LOADING_RUNS.wait(); } catch (InterruptedException x) { LOGGER.log(Level.WARNING, "failed to wait for " + r + " to be loaded", x); break; } } } FlowExecution exec = r.execution; if (exec != null) { return exec; } else { throw new IOException(r + " did not yet start"); } } @Override public File getRootDir() throws IOException { return run().getRootDir(); } @Override public Queue.Executable getExecutable() throws IOException { return run(); } @Override public PrintStream getConsole() { try { return run().listener.getLogger(); } catch (IOException e) { return System.out; // fallback } } @Override public String getUrl() throws IOException { return run().getUrl(); } @Override public String toString() { return "Owner[" + key() + ":" + run + "]"; } @Override public boolean equals(Object o) { if (!(o instanceof Owner)) { return false; } Owner that = (Owner) o; return job.equals(that.job) && id.equals(that.id); } @Override public int hashCode() { return job.hashCode() ^ id.hashCode(); } private static final long serialVersionUID = 1; } private final class GraphL implements GraphListener { @Override public void onNewHead(FlowNode node) { synchronized (completed) { copyLogs(); logsToCopy.put(node.getId(), 0L); } node.addAction(new TimingAction()); listener.getLogger().println("Running: " + node.getDisplayName()); if (node instanceof FlowEndNode) { finish(((FlowEndNode) node).getResult()); } else { try { save(); } catch (IOException x) { LOGGER.log(Level.WARNING, null, x); } } } } static void alias() { Run.XSTREAM2.alias("flow-build", WorkflowRun.class); new XmlFile(null).getXStream().aliasType("flow-owner", Owner.class); Run.XSTREAM2.aliasType("flow-owner", Owner.class); } @Extension public static final class SCMListenerImpl extends SCMListener { @Override public void onCheckout(Run<?,?> build, SCM scm, FilePath workspace, TaskListener listener, File changelogFile, SCMRevisionState pollingBaseline) throws Exception { if (build instanceof WorkflowRun) { ((WorkflowRun) build).onCheckout(scm, workspace, changelogFile, pollingBaseline); } } } }
package jade.core; import jade.util.leap.Iterator; import jade.util.leap.LinkedList; import jade.lang.acl.ACLMessage; /** @author Giovanni Rimassa - Universita` di Parma @version $Date$ $Revision$ */ class MessageQueue { // This class is sent onto the stream in place of the MessageQueue; // when read and resolved, it yields a new MessageQueue with the // same maximum size as the original one. /*private static class Memento implements Serializable { private int size; public Memento(int sz) { size = sz; } private Object readResolve() throws java.io.ObjectStreamException { return new MessageQueue(size); } } */ private LinkedList list; private int maxSize; public MessageQueue(int size) { maxSize = size; list = new LinkedList(); } public boolean isEmpty() { return list.isEmpty(); } public void setMaxSize(int newSize) throws IllegalArgumentException { if(newSize < 0) throw new IllegalArgumentException("Negative message queue size is not allowed."); maxSize = newSize; } public int getMaxSize() { return maxSize; } public void addFirst(ACLMessage msg) { if((maxSize != 0) && (list.size() >= maxSize)) list.removeFirst(); // FIFO replacement policy list.addFirst(msg); } public void addLast(ACLMessage msg) { if((maxSize != 0) && (list.size() >= maxSize)){ list.removeFirst(); // FIFO replacement policy System.err.println("WARNING: a message has been lost by an agent because of the FIFO replacement policy of its message queue.\n Notice that, under some circumstances, this might not be the proper expected behaviour and the size of the queue needs to be increased. Check the method Agent.setQueueSize()"); } list.addLast(msg); } public ACLMessage removeFirst() { return (ACLMessage)list.removeFirst(); } public boolean remove(ACLMessage item) { return list.remove(item); } public Iterator iterator() { return list.iterator(); } // This class is serialized by sending only its current size /*private Object writeReplace() throws java.io.ObjectStreamException { return new Memento(maxSize); } */ }
package nxt.http; import nxt.Account; import nxt.Alias; import nxt.Appendix; import nxt.Asset; import nxt.AssetTransfer; import nxt.Block; import nxt.DigitalGoodsStore; import nxt.Nxt; import nxt.Order; import nxt.Poll; import nxt.Token; import nxt.Trade; import nxt.Transaction; import nxt.crypto.Crypto; import nxt.crypto.EncryptedData; import nxt.peer.Hallmark; import nxt.peer.Peer; import nxt.util.Convert; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import java.util.Collections; final class JSONData { static JSONObject alias(Alias alias) { JSONObject json = new JSONObject(); putAccount(json, "account", alias.getAccountId()); json.put("aliasName", alias.getAliasName()); json.put("aliasURI", alias.getAliasURI()); json.put("timestamp", alias.getTimestamp()); json.put("alias", Convert.toUnsignedLong(alias.getId())); Alias.Offer offer = Alias.getOffer(alias); if (offer != null) { json.put("priceNQT", String.valueOf(offer.getPriceNQT())); if (offer.getBuyerId() != 0) { json.put("buyer", Convert.toUnsignedLong(offer.getBuyerId())); } } return json; } static JSONObject accountBalance(Account account) { JSONObject json = new JSONObject(); if (account == null) { json.put("balanceNQT", "0"); json.put("unconfirmedBalanceNQT", "0"); json.put("effectiveBalanceNXT", "0"); json.put("forgedBalanceNQT", "0"); json.put("guaranteedBalanceNQT", "0"); } else { json.put("balanceNQT", String.valueOf(account.getBalanceNQT())); json.put("unconfirmedBalanceNQT", String.valueOf(account.getUnconfirmedBalanceNQT())); json.put("effectiveBalanceNXT", account.getEffectiveBalanceNXT()); json.put("forgedBalanceNQT", String.valueOf(account.getForgedBalanceNQT())); json.put("guaranteedBalanceNQT", String.valueOf(account.getGuaranteedBalanceNQT(1440))); } return json; } static JSONObject asset(Asset asset) { JSONObject json = new JSONObject(); putAccount(json, "account", asset.getAccountId()); json.put("name", asset.getName()); json.put("description", asset.getDescription()); json.put("decimals", asset.getDecimals()); json.put("quantityQNT", String.valueOf(asset.getQuantityQNT())); json.put("asset", Convert.toUnsignedLong(asset.getId())); json.put("numberOfTrades", Trade.getTradeCount(asset.getId())); json.put("numberOfTransfers", AssetTransfer.getTransferCount(asset.getId())); json.put("numberOfAccounts", Account.getAssetAccountsCount(asset.getId())); return json; } static JSONObject accountAsset(Account.AccountAsset accountAsset) { JSONObject json = new JSONObject(); putAccount(json, "account", accountAsset.getAccountId()); json.put("asset", Convert.toUnsignedLong(accountAsset.getAssetId())); json.put("quantityQNT", String.valueOf(accountAsset.getQuantityQNT())); json.put("unconfirmedQuantityQNT", String.valueOf(accountAsset.getUnconfirmedQuantityQNT())); return json; } static JSONObject askOrder(Order.Ask order) { JSONObject json = order(order); json.put("type", "ask"); return json; } static JSONObject bidOrder(Order.Bid order) { JSONObject json = order(order); json.put("type", "bid"); return json; } static JSONObject order(Order order) { JSONObject json = new JSONObject(); json.put("order", Convert.toUnsignedLong(order.getId())); json.put("asset", Convert.toUnsignedLong(order.getAssetId())); putAccount(json, "account", order.getAccountId()); json.put("quantityQNT", String.valueOf(order.getQuantityQNT())); json.put("priceNQT", String.valueOf(order.getPriceNQT())); json.put("height", order.getHeight()); return json; } static JSONObject block(Block block, boolean includeTransactions) { JSONObject json = new JSONObject(); json.put("block", block.getStringId()); json.put("height", block.getHeight()); putAccount(json, "generator", block.getGeneratorId()); json.put("generatorPublicKey", Convert.toHexString(block.getGeneratorPublicKey())); json.put("timestamp", block.getTimestamp()); json.put("numberOfTransactions", block.getTransactions().size()); json.put("totalAmountNQT", String.valueOf(block.getTotalAmountNQT())); json.put("totalFeeNQT", String.valueOf(block.getTotalFeeNQT())); json.put("payloadLength", block.getPayloadLength()); json.put("version", block.getVersion()); json.put("baseTarget", Convert.toUnsignedLong(block.getBaseTarget())); if (block.getPreviousBlockId() != 0) { json.put("previousBlock", Convert.toUnsignedLong(block.getPreviousBlockId())); } if (block.getNextBlockId() != 0) { json.put("nextBlock", Convert.toUnsignedLong(block.getNextBlockId())); } json.put("payloadHash", Convert.toHexString(block.getPayloadHash())); json.put("generationSignature", Convert.toHexString(block.getGenerationSignature())); if (block.getVersion() > 1) { json.put("previousBlockHash", Convert.toHexString(block.getPreviousBlockHash())); } json.put("blockSignature", Convert.toHexString(block.getBlockSignature())); JSONArray transactions = new JSONArray(); for (Transaction transaction : block.getTransactions()) { transactions.add(includeTransactions ? transaction(transaction) : Convert.toUnsignedLong(transaction.getId())); } json.put("transactions", transactions); return json; } static JSONObject encryptedData(EncryptedData encryptedData) { JSONObject json = new JSONObject(); json.put("data", Convert.toHexString(encryptedData.getData())); json.put("nonce", Convert.toHexString(encryptedData.getNonce())); return json; } static JSONObject goods(DigitalGoodsStore.Goods goods) { JSONObject json = new JSONObject(); json.put("goods", Convert.toUnsignedLong(goods.getId())); json.put("name", goods.getName()); json.put("description", goods.getDescription()); json.put("quantity", goods.getQuantity()); json.put("priceNQT", String.valueOf(goods.getPriceNQT())); putAccount(json, "seller", goods.getSellerId()); json.put("tags", goods.getTags()); json.put("delisted", goods.isDelisted()); json.put("timestamp", goods.getTimestamp()); return json; } static JSONObject hallmark(Hallmark hallmark) { JSONObject json = new JSONObject(); putAccount(json, "account", Account.getId(hallmark.getPublicKey())); json.put("host", hallmark.getHost()); json.put("weight", hallmark.getWeight()); String dateString = Hallmark.formatDate(hallmark.getDate()); json.put("date", dateString); json.put("valid", hallmark.isValid()); return json; } static JSONObject token(Token token) { JSONObject json = new JSONObject(); putAccount(json, "account", Account.getId(token.getPublicKey())); json.put("timestamp", token.getTimestamp()); json.put("valid", token.isValid()); return json; } static JSONObject peer(Peer peer) { JSONObject json = new JSONObject(); json.put("state", peer.getState().ordinal()); json.put("announcedAddress", peer.getAnnouncedAddress()); json.put("shareAddress", peer.shareAddress()); if (peer.getHallmark() != null) { json.put("hallmark", peer.getHallmark().getHallmarkString()); } json.put("weight", peer.getWeight()); json.put("downloadedVolume", peer.getDownloadedVolume()); json.put("uploadedVolume", peer.getUploadedVolume()); json.put("application", peer.getApplication()); json.put("version", peer.getVersion()); json.put("platform", peer.getPlatform()); json.put("blacklisted", peer.isBlacklisted()); json.put("lastUpdated", peer.getLastUpdated()); return json; } static JSONObject poll(Poll poll) { JSONObject json = new JSONObject(); json.put("name", poll.getName()); json.put("description", poll.getDescription()); JSONArray options = new JSONArray(); Collections.addAll(options, poll.getOptions()); json.put("options", options); json.put("minNumberOfOptions", poll.getMinNumberOfOptions()); json.put("maxNumberOfOptions", poll.getMaxNumberOfOptions()); json.put("optionsAreBinary", poll.isOptionsAreBinary()); JSONArray voters = new JSONArray(); for (Long voterId : poll.getVoters().keySet()) { voters.add(Convert.toUnsignedLong(voterId)); } json.put("voters", voters); return json; } static JSONObject purchase(DigitalGoodsStore.Purchase purchase) { JSONObject json = new JSONObject(); json.put("purchase", Convert.toUnsignedLong(purchase.getId())); json.put("goods", Convert.toUnsignedLong(purchase.getGoodsId())); json.put("name", purchase.getName()); putAccount(json, "seller", purchase.getSellerId()); json.put("priceNQT", String.valueOf(purchase.getPriceNQT())); json.put("quantity", purchase.getQuantity()); putAccount(json, "buyer", purchase.getBuyerId()); json.put("timestamp", purchase.getTimestamp()); json.put("deliveryDeadlineTimestamp", purchase.getDeliveryDeadlineTimestamp()); if (purchase.getNote() != null) { json.put("note", encryptedData(purchase.getNote())); } json.put("pending", purchase.isPending()); if (purchase.getEncryptedGoods() != null) { json.put("goodsData", encryptedData(purchase.getEncryptedGoods())); json.put("goodsIsText", purchase.goodsIsText()); } if (purchase.getFeedbackNotes() != null) { JSONArray feedbacks = new JSONArray(); for (EncryptedData encryptedData : purchase.getFeedbackNotes()) { feedbacks.add(encryptedData(encryptedData)); } json.put("feedbackNotes", feedbacks); } if (purchase.getPublicFeedback() != null) { JSONArray publicFeedbacks = new JSONArray(); for (String publicFeedback : purchase.getPublicFeedback()) { publicFeedbacks.add(publicFeedback); } json.put("publicFeedbacks", publicFeedbacks); } if (purchase.getRefundNote() != null) { json.put("refundNote", encryptedData(purchase.getRefundNote())); } if (purchase.getDiscountNQT() > 0) { json.put("discountNQT", String.valueOf(purchase.getDiscountNQT())); } if (purchase.getRefundNQT() > 0) { json.put("refundNQT", String.valueOf(purchase.getRefundNQT())); } return json; } static JSONObject trade(Trade trade) { JSONObject json = new JSONObject(); json.put("timestamp", trade.getTimestamp()); json.put("quantityQNT", String.valueOf(trade.getQuantityQNT())); json.put("priceNQT", String.valueOf(trade.getPriceNQT())); json.put("asset", Convert.toUnsignedLong(trade.getAssetId())); json.put("askOrder", Convert.toUnsignedLong(trade.getAskOrderId())); json.put("bidOrder", Convert.toUnsignedLong(trade.getBidOrderId())); json.put("askOrderHeight", trade.getAskOrderHeight()); json.put("bidOrderHeight", trade.getBidOrderHeight()); putAccount(json, "seller", trade.getSellerId()); putAccount(json, "buyer", trade.getBuyerId()); json.put("block", Convert.toUnsignedLong(trade.getBlockId())); json.put("height", trade.getHeight()); Asset asset = Asset.getAsset(trade.getAssetId()); json.put("name", asset.getName()); json.put("decimals", asset.getDecimals()); return json; } static JSONObject assetTransfer(AssetTransfer assetTransfer) { JSONObject json = new JSONObject(); json.put("assetTransfer", Convert.toUnsignedLong(assetTransfer.getId())); json.put("asset", Convert.toUnsignedLong(assetTransfer.getAssetId())); putAccount(json, "sender", assetTransfer.getSenderId()); putAccount(json, "recipient", assetTransfer.getRecipientId()); json.put("quantityQNT", String.valueOf(assetTransfer.getQuantityQNT())); json.put("height", assetTransfer.getHeight()); Asset asset = Asset.getAsset(assetTransfer.getAssetId()); json.put("name", asset.getName()); json.put("decimals", asset.getDecimals()); return json; } static JSONObject unconfirmedTransaction(Transaction transaction) { JSONObject json = new JSONObject(); json.put("type", transaction.getType().getType()); json.put("subtype", transaction.getType().getSubtype()); json.put("timestamp", transaction.getTimestamp()); json.put("deadline", transaction.getDeadline()); json.put("senderPublicKey", Convert.toHexString(transaction.getSenderPublicKey())); if (transaction.getRecipientId() != 0) { putAccount(json, "recipient", transaction.getRecipientId()); } json.put("amountNQT", String.valueOf(transaction.getAmountNQT())); json.put("feeNQT", String.valueOf(transaction.getFeeNQT())); if (transaction.getReferencedTransactionFullHash() != null) { json.put("referencedTransactionFullHash", transaction.getReferencedTransactionFullHash()); } byte[] signature = Convert.emptyToNull(transaction.getSignature()); if (signature != null) { json.put("signature", Convert.toHexString(signature)); json.put("signatureHash", Convert.toHexString(Crypto.sha256().digest(signature))); json.put("fullHash", transaction.getFullHash()); json.put("transaction", transaction.getStringId()); } JSONObject attachmentJSON = new JSONObject(); for (Appendix appendage : transaction.getAppendages()) { attachmentJSON.putAll(appendage.getJSONObject()); } if (! attachmentJSON.isEmpty()) { modifyAttachmentJSON(attachmentJSON); json.put("attachment", attachmentJSON); } putAccount(json, "sender", transaction.getSenderId()); json.put("height", transaction.getHeight()); json.put("version", transaction.getVersion()); if (transaction.getVersion() > 0) { json.put("ecBlockId", Convert.toUnsignedLong(transaction.getECBlockId())); json.put("ecBlockHeight", transaction.getECBlockHeight()); } return json; } static JSONObject transaction(Transaction transaction) { JSONObject json = unconfirmedTransaction(transaction); json.put("block", Convert.toUnsignedLong(transaction.getBlockId())); json.put("confirmations", Nxt.getBlockchain().getHeight() - transaction.getHeight()); json.put("blockTimestamp", transaction.getBlockTimestamp()); return json; } // ugly, hopefully temporary private static void modifyAttachmentJSON(JSONObject json) { Long quantityQNT = (Long) json.remove("quantityQNT"); if (quantityQNT != null) { json.put("quantityQNT", String.valueOf(quantityQNT)); } Long priceNQT = (Long) json.remove("priceNQT"); if (priceNQT != null) { json.put("priceNQT", String.valueOf(priceNQT)); } Long discountNQT = (Long) json.remove("discountNQT"); if (discountNQT != null) { json.put("discountNQT", String.valueOf(discountNQT)); } Long refundNQT = (Long) json.remove("refundNQT"); if (refundNQT != null) { json.put("refundNQT", String.valueOf(refundNQT)); } } static void putAccount(JSONObject json, String name, long accountId) { json.put(name, Convert.toUnsignedLong(accountId)); json.put(name + "RS", Convert.rsAccount(accountId)); } private JSONData() {} // never }
package de.lmu.ifi.dbs.elki.algorithm.outlier; import java.util.BitSet; import java.util.List; import de.lmu.ifi.dbs.elki.data.RealVector; import de.lmu.ifi.dbs.elki.database.Database; import de.lmu.ifi.dbs.elki.distance.distancefunction.DimensionsSelectingEuclideanDistanceFunction; import de.lmu.ifi.dbs.elki.normalization.NonNumericFeaturesException; import de.lmu.ifi.dbs.elki.result.textwriter.TextWriteable; import de.lmu.ifi.dbs.elki.result.textwriter.TextWriterStream; /** * todo arthur comment * * @author Arthur Zimek * @param <O> the type of DatabaseObjects handled by this Result */ public class SODModel<O extends RealVector<O, Double>> implements TextWriteable, Comparable<SODModel<?>> { private final DimensionsSelectingEuclideanDistanceFunction<O> DISTANCE_FUNCTION = new DimensionsSelectingEuclideanDistanceFunction<O>(); private double[] centerValues; private O center; private double[] variances; private double expectationOfVariance; private BitSet weightVector; private double sod; /** * TODO: arthur comment * * @param database * @param neighborhood * @param alpha * @param queryObject */ public SODModel(Database<O> database, List<Integer> neighborhood, double alpha, O queryObject) { // TODO: store database link? centerValues = new double[database.dimensionality()]; variances = new double[centerValues.length]; for (Integer id : neighborhood) { O databaseObject = database.get(id); for (int d = 0; d < centerValues.length; d++) { centerValues[d] += databaseObject.getValue(d + 1); } } for (int d = 0; d < centerValues.length; d++) { centerValues[d] /= neighborhood.size(); } for (Integer id : neighborhood) { O databaseObject = database.get(id); for (int d = 0; d < centerValues.length; d++) { // distance double distance = centerValues[d] - databaseObject.getValue(d + 1); // variance variances[d] += distance * distance; } } expectationOfVariance = 0; for (int d = 0; d < variances.length; d++) { variances[d] /= neighborhood.size(); expectationOfVariance += variances[d]; } expectationOfVariance /= variances.length; weightVector = new BitSet(variances.length); for (int d = 0; d < variances.length; d++) { if (variances[d] < alpha * expectationOfVariance) { weightVector.set(d, true); } } center = queryObject.newInstance(centerValues); sod = subspaceOutlierDegree(queryObject, center, weightVector); } /** * TODO arthur comment * * @param queryObject * @param center * @param weightVector * @return sod value */ private double subspaceOutlierDegree(O queryObject, O center, BitSet weightVector) { DISTANCE_FUNCTION.setSelectedDimensions(weightVector); double distance = DISTANCE_FUNCTION.distance(queryObject, center).getValue(); distance /= weightVector.cardinality(); return distance; } /** * Return the SOD of the point. * * @return sod value */ public double getSod() { return this.sod; } @Override public void writeToText(TextWriterStream out, String label) { out.inlinePrint(label+"="+this.sod); out.commentPrintLn(this.getClass().getSimpleName() + ":"); out.commentPrintLn("relevant attributes (counting starts with 0): " + this.weightVector.toString()); try { out.commentPrintLn("center of neighborhood: " + out.normalizationRestore(center).toString()); } catch(NonNumericFeaturesException e) { e.printStackTrace(); } out.commentPrintLn("subspace outlier degree: " + this.sod); out.commentPrintSeparator(); } @Override public int compareTo(SODModel<?> o) { return Double.compare(this.getSod(), o.getSod()); } }
package de.mrapp.android.adapter.util; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; /** * A list iterator, which allows to iterate over the data of a list's items. * * @param <DataType> * The type of the item's data * * @author Michael Rapp */ public class ItemListIterator<DataType> implements ListIterator<DataType> { /** * A list, which contains the items, whose data should be iterated. */ private List<Item<DataType>> items; /** * The current index of the iterator. */ private int currentIndex; /** * Creates a new list iterator, which allows to iterate over the data of a * list's items. * * @param items * The list, which contains the items, whose data should be * iterated, as an instance of the type {@link List}. The list * may not be null */ public ItemListIterator(final List<Item<DataType>> items) { this.items = items; this.currentIndex = 0; } @Override public final void add(final DataType item) { items.add(currentIndex, new Item<DataType>(item)); } @Override public final boolean hasNext() { return currentIndex < items.size() - 1; } @Override public final boolean hasPrevious() { return currentIndex > 0; } @Override public final DataType next() { if (!hasNext()) { throw new NoSuchElementException(); } currentIndex++; return items.get(currentIndex).getData(); } @Override public final int nextIndex() { if (!hasNext()) { throw new NoSuchElementException(); } return currentIndex + 1; } @Override public final DataType previous() { if (!hasPrevious()) { throw new NoSuchElementException(); } return items.get(currentIndex - 1).getData(); } @Override public final int previousIndex() { if (!hasPrevious()) { throw new NoSuchElementException(); } return currentIndex - 1; } @Override public final void remove() { items.remove(currentIndex); } @Override public final void set(final DataType item) { items.set(currentIndex, new Item<DataType>(item)); } }
package org.jpos.security; import org.jpos.util.Loggeable; import java.io.PrintStream; import java.util.Enumeration; import java.util.Hashtable; import java.util.StringTokenizer; import java.util.Vector; /** * Cryptographic Service Message (CSM for short). * * A message for transporting keys or * related information used to control a keying relationship. * It is typically the contents of ISOField(123). * For more information refer to ANSI X9.17: Financial Institution Key Mangement * (Wholesale). * </p> * @todo add sub-fields support * @author Hani S. Kirollos * @version $Revision$ $Date$ */ public class CryptographicServiceMessage implements Loggeable { Hashtable fields = new Hashtable(); Vector orderedTags = new Vector(); String mcl; public static final String MCL_RSI = "RSI"; public static final String MCL_KSM = "KSM"; public static final String MCL_RSM = "RSM"; public static final String MCL_ESM = "ESM"; public static final String TAG_RCV = "RCV"; public static final String TAG_ORG = "ORG"; public static final String TAG_SVR = "SVR"; public static final String TAG_KD = "KD" ; public static final String TAG_CTP = "CTP"; public static final String TAG_CTR = "CTR"; public static final String TAG_ERF = "ERF"; public static class ParsingException extends Exception { private static final long serialVersionUID = 6984718759445061L; public ParsingException() { super(); } public ParsingException(String detail) { super(detail); } } public CryptographicServiceMessage() { } /** * Creates a CSM and sets its Message Class * @param mcl message class name. e.g. MCL_KSM, MCL_RSM... */ public CryptographicServiceMessage(String mcl) { setMCL(mcl); } public void setMCL(String mcl) { this.mcl = mcl; } public String getMCL() { return mcl; } /** * adds a field to the CSM * @param tag Field Tag * @param content Field Content, can't be null, use an empty string ("") instead * @throws NullPointerException if tag or content is null */ public void addField(String tag, String content) { tag = tag.toUpperCase(); fields.put(tag, content); orderedTags.add(tag); } /** * Returns the field content of a field with the given tag * @param tag * @return field Field Content, or null if tag not found */ public String getFieldContent(String tag) { return (String) fields.get(tag.toUpperCase()); } /** * Formats the CSM as a string, suitable for transfer. * This is the inverse of parse * @return the CSM in string format */ public String toString() { StringBuilder csm = new StringBuilder(); csm.append("CSM(MCL/"); csm.append(getMCL()); csm.append(" "); for (Object tagObject : orderedTags) { String tag = (String) tagObject; csm.append(tag); csm.append("/"); csm.append(getFieldContent(tag)); csm.append(" "); } csm.append(")"); return csm.toString(); } /** * dumps CSM basic information * @param p a PrintStream usually supplied by Logger * @param indent indention string, usually suppiled by Logger * @see org.jpos.util.Loggeable */ public void dump (PrintStream p, String indent) { String inner = indent + " "; p.print(indent + "<csm"); p.print(" class=\"" + getMCL() + "\""); p.println(">"); for (Object tagObject : orderedTags) { String tag = (String) tagObject; p.println(inner + "<field tag=\"" + tag + "\" value=\"" + getFieldContent(tag) + "\"/>"); } p.println(indent + "</csm>"); } /** * Parses a csm string * @param csmString * @return CSM object * @throws ParsingException */ public static CryptographicServiceMessage parse(String csmString) throws ParsingException { CryptographicServiceMessage csm = new CryptographicServiceMessage(); StringTokenizer st = new StringTokenizer(csmString, "() \t\n\r\f"); if (!st.nextToken().equalsIgnoreCase("CSM")) throw new ParsingException("Invalid CSM, doesn't start with the \"CSM(\" tag: " + csmString); do { String field = st.nextToken(); int separatorIndex = field.indexOf('/'); if (separatorIndex > 0) { String tag = field.substring(0, separatorIndex).toUpperCase(); String content = ""; if (separatorIndex < field.length()) content = field.substring(separatorIndex + 1); if (tag.equalsIgnoreCase("MCL")) csm.setMCL(content); else csm.addField(tag, content); } else throw new ParsingException("Invalid field, doesn't have a tag: " + field); } while (st.hasMoreTokens()); if (csm.getMCL() == null) throw new ParsingException("Invalid CSM, doesn't contain an MCL: " + csmString); return csm; } }
package jsettlers.graphics.map.minimap; import jsettlers.common.Color; import jsettlers.common.CommonConstants; import jsettlers.common.buildings.IBuilding; import jsettlers.common.map.IGraphicsGrid; import jsettlers.common.mapobject.EMapObjectType; import jsettlers.common.mapobject.IMapObject; import jsettlers.common.movable.IMovable; import jsettlers.graphics.map.MapDrawContext; import jsettlers.graphics.map.minimap.MinimapMode.OccupiedAreaMode; import jsettlers.graphics.map.minimap.MinimapMode.SettlersMode; class LineLoader implements Runnable { protected static final short BLACK = 0x0001; private static final short TRANSPARENT = 0; private static final int Y_STEP_HEIGHT = 5; private static final int X_STEP_WIDTH = 5; private static final int LINES_PER_RUN = 30; /** * The minimap we work for. */ private final Minimap minimap; private int currentline = 0; private boolean stopped; private final MinimapMode modeSettings; private short[][] buffer = new short[1][1]; private int currYOffset = 0; private int currXOffset = 0; public LineLoader(Minimap minimap, MinimapMode modeSettings) { this.minimap = minimap; this.modeSettings = modeSettings; } @Override public void run() { while (!stopped) { try { updateLine(); } catch (Throwable e) { e.printStackTrace(); } } }; private boolean isFirstRun; /** * Updates a line by putting it to the update buffer. Next time the gl context is available, it is updated. */ private void updateLine() { minimap.blockUntilUpdateAllowedOrStopped(); for (int i = 0; i < LINES_PER_RUN; i++) { if (buffer.length != minimap.getHeight() || buffer[currentline].length != minimap.getWidth()) { buffer = new short[minimap.getHeight()][minimap.getWidth()]; for (int y = 0; y < minimap.getHeight(); y++) { for (int x = 0; x < minimap.getWidth(); x++) { buffer[y][x] = BLACK; } } minimap.setBufferArray(buffer); currentline = 0; isFirstRun = true; currXOffset = 0; currYOffset = 0; } calculateLineData(currentline); minimap.setUpdatedLine(currentline); currentline += Y_STEP_HEIGHT; if (currentline >= minimap.getHeight()) { currYOffset++; if (currYOffset > Y_STEP_HEIGHT) { currYOffset = 0; currXOffset += 3; currXOffset %= X_STEP_WIDTH; if (currXOffset == 0) { isFirstRun = false; } } currentline = currYOffset; } } } private void calculateLineData(final int currentline) { // may change! final int safeWidth = this.minimap.getWidth(); final int safeHeight = this.minimap.getHeight(); final MapDrawContext context = this.minimap.getContext(); final IGraphicsGrid map = context.getMap(); // for height shades final short mapWidth = map.getWidth(); final short mapHeight = map.getHeight(); int mapLineHeight = mapHeight / safeHeight + 1; // first map tile in line int mapMaxY = (int) ((1 - (float) currentline / safeHeight) * mapHeight); // first map line not in line int mapMinY = (int) ((1 - (float) (currentline + 1) / safeHeight) * mapHeight); if (mapMinY == mapMaxY) { if (mapMaxY == mapHeight) { mapMinY = mapHeight - 1; } else { mapMaxY = mapMinY - 1; } } int myXOffset = (currXOffset + currentline * 3) % X_STEP_WIDTH; for (int x = myXOffset; x < safeWidth; x += X_STEP_WIDTH) { int mapMinX = (int) ((float) x / safeWidth * mapWidth); int mapMaxX = (int) ((float) (x + 1) / safeWidth * mapWidth); if (mapMinX != 0 && mapMaxX == mapMinX) { mapMinX = mapMaxX - 1; } int centerX = (mapMaxX + mapMinX) / 2; int centerY = (mapMaxY + mapMinY) / 2; short color = TRANSPARENT; byte visibleStatus = map.getVisibleStatus(centerX, centerY); if (visibleStatus > CommonConstants.FOG_OF_WAR_EXPLORED) { color = getSettlerForArea(map, context, mapMinX, mapMinY, mapMaxX, mapMaxY); } if (color == TRANSPARENT && (visibleStatus > CommonConstants.FOG_OF_WAR_EXPLORED || isFirstRun)) { float basecolor = ((float) visibleStatus) / CommonConstants.FOG_OF_WAR_VISIBLE; int dheight = map.getHeightAt(centerX, mapMinY) - map.getHeightAt(centerX, Math.min(mapMinY + mapLineHeight, mapHeight - 1)); basecolor *= (1 + .15f * dheight); if (basecolor >= 0) { color = getColorForArea(map, mapMinX, mapMinY, mapMaxX, mapMaxY).toShortColor(basecolor); } } if (color != TRANSPARENT) { buffer[currentline][x] = color; } } } private Color getColorForArea(IGraphicsGrid map, int mapminX, int mapminY, int mapmaxX, int mapmaxY) { int centerx = (mapmaxX + mapminX) / 2; int centery = (mapmaxY + mapminY) / 2; return map.getLandscapeTypeAt(centerx, centery).color; } private short getSettlerForArea(IGraphicsGrid map, MapDrawContext context, int mapminX, int mapminY, int mapmaxX, int mapmaxY) { SettlersMode displaySettlers = this.modeSettings.getDisplaySettlers(); OccupiedAreaMode displayOccupied = this.modeSettings.getDisplayOccupied(); boolean displayBuildings = this.modeSettings.getDisplayBuildings(); short occupiedColor = TRANSPARENT; short settlerColor = TRANSPARENT; short buildingColor = TRANSPARENT; for (int y = mapminY; y < mapmaxY && (displayOccupied != OccupiedAreaMode.NONE || displayBuildings || displaySettlers != SettlersMode.NONE); y++) { for (int x = mapminX; x < mapmaxX && (displayOccupied != OccupiedAreaMode.NONE || displayBuildings || displaySettlers != SettlersMode.NONE); x++) { boolean visible = map.getVisibleStatus(x, y) > CommonConstants.FOG_OF_WAR_EXPLORED; if (visible && displaySettlers != SettlersMode.NONE) { IMovable settler = map.getMovableAt(x, y); if (settler != null && (displaySettlers == SettlersMode.ALL || settler.getMovableType().isMoveToAble())) { settlerColor = context.getPlayerColor(settler.getPlayerId()).toShortColor(1); // don't search any more. displaySettlers = SettlersMode.NONE; } else if (displaySettlers != SettlersMode.NONE) { IMapObject object = map.getMapObjectsAt(x, y); IBuilding building = (object != null) ? (IBuilding) object.getMapObject(EMapObjectType.BUILDING) : null; if (building instanceof IBuilding.IOccupyed) { IBuilding.IOccupyed occupyed = (IBuilding.IOccupyed) building; if (occupyed.isOccupied()) { settlerColor = context.getPlayerColor(occupyed.getPlayerId()).toShortColor(1); } } } } if (visible && displayOccupied == OccupiedAreaMode.BORDERS) { if (map.isBorder(x, y)) { byte player = map.getPlayerIdAt(x, y); Color playerColor = context.getPlayerColor(player); occupiedColor = playerColor.toShortColor(1); displayOccupied = OccupiedAreaMode.NONE; } } else if (visible && displayOccupied == OccupiedAreaMode.AREA) { byte player = map.getPlayerIdAt(x, y); if (player >= 0 && !map.getLandscapeTypeAt(x, y).isBlocking) { Color playerColor = context.getPlayerColor(player); // Now add a landscape below that.... Color landscape = getColorForArea(map, mapminX, mapminY, mapmaxX, mapmaxY); playerColor = landscape.toGreyScale().overlay(playerColor); occupiedColor = playerColor.toShortColor(1); displayOccupied = OccupiedAreaMode.NONE; } } if (displayBuildings) { // TODO: Implement building shape. IMapObject object = map.getMapObjectsAt(x, y); while (object != null) { if (object.getObjectType() == EMapObjectType.BUILDING) { buildingColor = BLACK; } object = object.getNextObject(); } } } } return settlerColor != TRANSPARENT ? settlerColor : buildingColor != TRANSPARENT ? buildingColor : occupiedColor; } /** * Stops the execution of this line loader. */ public void stop() { stopped = true; } }
package jsettlers.graphics.messages; import jsettlers.common.buildings.IBuilding; import jsettlers.common.material.EMaterialType; import jsettlers.common.position.ShortPoint2D; import jsettlers.graphics.localization.Labels; /** * This is a message that states that the user was attacked by an other player. * * @author michael */ public class SimpleMessage implements Message { private final byte sender; private final ShortPoint2D pos; private final String message; private final EMessageType type; private final long time; public SimpleMessage(EMessageType type, String message, byte sender, ShortPoint2D pos) { this.type = type; this.message = message; this.sender = sender; this.pos = pos; this.time = System.currentTimeMillis(); } @Override public EMessageType getType() { return type; } @Override public long getAge() { // TODO: implement a message aging process. return System.currentTimeMillis() - this.time; } @Override public String getMessage() { return message; } @Override public byte getSender() { return sender; } @Override public ShortPoint2D getPosition() { return pos; } public static Message attacked(byte otherplayer, ShortPoint2D pos) { String message = Labels.getString("attacked"); return new SimpleMessage(EMessageType.ATTACKED, message, otherplayer, pos); } public static Message foundMinerals(EMaterialType type, ShortPoint2D pos) { String message = Labels.getString("minerals_" + type.toString()); return new SimpleMessage(EMessageType.MINERALS, message, (byte) -1, pos); } public static Message cannotFindWork(IBuilding building) { String message = Labels.getString("cannot_find_work_" + building.getBuildingType()); return new SimpleMessage(EMessageType.NOTHING_FOUND_IN_SEARCH_AREA, message, (byte) -1, building.getPos()); } }
package dr.inference.model; import cern.colt.matrix.DoubleMatrix1D; import cern.colt.matrix.DoubleMatrix2D; import cern.colt.matrix.impl.DenseDoubleMatrix2D; import dr.evolution.tree.TreeTrait; import dr.evomodel.continuous.MultivariateDiffusionModel; import dr.evomodel.tree.TreeModel; import dr.evomodel.treedatalikelihood.RateRescalingScheme; import dr.evomodel.treedatalikelihood.TreeDataLikelihood; import dr.evomodel.treedatalikelihood.continuous.MultivariateTraitDebugUtilities; import dr.evomodel.treedatalikelihood.continuous.RepeatedMeasuresTraitDataModel; import dr.evomodel.treedatalikelihood.continuous.RepeatedMeasuresTraitSimulator; import dr.math.matrixAlgebra.IllegalDimension; import dr.math.matrixAlgebra.Matrix; import dr.math.matrixAlgebra.RobustEigenDecomposition; import dr.math.matrixAlgebra.missingData.MissingOps; import dr.xml.*; import org.ejml.data.DenseMatrix64F; import org.ejml.ops.CommonOps; import java.util.Arrays; import static dr.evomodel.treedatalikelihood.preorder.AbstractRealizedContinuousTraitDelegate.REALIZED_TIP_TRAIT; /** * A Statistic class that computes the expected proportion of the variance in the data due to diffusion on the tree * versus sampling error. * * @author Gabriel Hassler */ public class VarianceProportionStatistic extends Statistic.Abstract implements VariableListener, ModelListener { public static final String PARSER_NAME = "varianceProportionStatistic"; private static final String MATRIX_RATIO = "matrixRatio"; private static final String ELEMENTWISE = "elementWise"; private static final String SYMMETRIC_DIVISION = "symmetricDivision"; private final TreeModel tree; private final MultivariateDiffusionModel diffusionModel; private final RepeatedMeasuresTraitDataModel dataModel; private final TreeDataLikelihood treeLikelihood; private DenseMatrix64F diffusionProportion; private TreeVarianceSums treeSums; private Matrix diffusionVariance; private Matrix samplingVariance; private DenseMatrix64F diffusionComponent; private DenseMatrix64F samplingComponent; private boolean treeKnown = false; private boolean varianceKnown = false; private final MatrixRatios ratio; private final int dimTrait; private final static boolean useEmpiricalVariance = true; private final static boolean forceResample = true; private final RepeatedMeasuresTraitSimulator traitSimulator; public VarianceProportionStatistic(TreeModel tree, TreeDataLikelihood treeLikelihood, RepeatedMeasuresTraitDataModel dataModel, MultivariateDiffusionModel diffusionModel, MatrixRatios ratio) { this.tree = tree; this.treeLikelihood = treeLikelihood; this.diffusionModel = diffusionModel; this.dataModel = dataModel; this.dimTrait = dataModel.getTraitDimension(); this.diffusionVariance = new Matrix(dimTrait, dimTrait); this.samplingVariance = new Matrix(dimTrait, dimTrait); this.diffusionProportion = new DenseMatrix64F(dimTrait, dimTrait); this.diffusionComponent = new DenseMatrix64F(dimTrait, dimTrait); this.samplingComponent = new DenseMatrix64F(dimTrait, dimTrait); this.treeSums = new TreeVarianceSums(0, 0); tree.addModelListener(this); if (useEmpiricalVariance && !forceResample) { dataModel.getParameter().addParameterListener(this); } else { diffusionModel.getPrecisionParameter().addParameterListener(this); dataModel.getPrecisionMatrix().addParameterListener(this); } if (forceResample) { this.traitSimulator = new RepeatedMeasuresTraitSimulator(dataModel, treeLikelihood); } else { this.traitSimulator = null; } this.ratio = ratio; } /** * a class that stores the sum of the diagonal elements and all elements of a matrix */ private class TreeVarianceSums { private double diagonalSum; private double totalSum; private TreeVarianceSums(double diagonalSum, double totalSum) { this.diagonalSum = diagonalSum; this.totalSum = totalSum; } } private enum MatrixRatios { ELEMENT_WISE { @Override void setMatrixRatio(DenseMatrix64F numeratorMatrix, DenseMatrix64F otherMatrix, DenseMatrix64F destination) { int dim = destination.numRows; for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { double n = Math.abs(numeratorMatrix.get(i, j)); double d = Math.abs(otherMatrix.get(i, j)); if (n == 0 && d == 0) { destination.set(i, j, 0); } else { destination.set(i, j, n / (n + d)); } } } } }, SYMMETRIC_DIVISION { @Override void setMatrixRatio(DenseMatrix64F numeratorMatrix, DenseMatrix64F otherMatrix, DenseMatrix64F destination) throws IllegalDimension { //TODO: implement for eigendecomposition with DensMatrix64F System.err.println(this.name() + " not yet implemented for " + SYMMETRIC_DIVISION + "."); // int dim = destination.numRows; // Matrix M1 = numeratorMatrix.add(otherMatrix); //M1 = numeratorMatrix + otherMatrix // Matrix M2 = getMatrixSqrt(M1, true); //M2 = inv(sqrt(numeratorMatrix + otherMatrix)) // Matrix M3 = M2.product(numeratorMatrix.product(M2));//M3 = inv(sqrt(numeratorMatrix + otherMatrix)) * // // numeratorMatrix * inv(sqrt(numeratorMatrix + otherMatrix)) // for (int i = 0; i < dim; i++) { // for (int j = 0; j < dim; j++) { // destination.set(i, j, M3.component(i, j)); } }; abstract void setMatrixRatio(DenseMatrix64F numeratorMatrix, DenseMatrix64F otherMatrix, DenseMatrix64F destination) throws IllegalDimension; } private void updateDiffsionProportion() throws IllegalDimension { updateVarianceComponents(); ratio.setMatrixRatio(diffusionComponent, samplingComponent, diffusionProportion); } private void updateVarianceComponents() { if (useEmpiricalVariance) { String key = REALIZED_TIP_TRAIT + "." + dataModel.getTraitName(); TreeTrait trait = treeLikelihood.getTreeTrait(key); double[] tipTraits = (double[]) trait.getTrait(treeLikelihood.getTree(), null); if (forceResample) { traitSimulator.simulateMissingData(tipTraits); } double[] data = dataModel.getParameter().getParameterValues(); int nTaxa = tree.getExternalNodeCount(); computeVariance(diffusionComponent, tipTraits, nTaxa, dimTrait); computeVariance(samplingComponent, data, nTaxa, dimTrait); CommonOps.addEquals(samplingComponent, -1, diffusionComponent); } else { double n = tree.getExternalNodeCount(); double diffusionScale = (treeSums.diagonalSum / n - treeSums.totalSum / (n * n)); double samplingScale = (n - 1) / n; for (int i = 0; i < dimTrait; i++) { diffusionComponent.set(i, i, diffusionScale * diffusionVariance.component(i, i)); samplingComponent.set(i, i, samplingScale * samplingVariance.component(i, i)); for (int j = i + 1; j < dimTrait; j++) { double diffValue = diffusionScale * diffusionVariance.component(i, j); double sampValue = samplingScale * samplingVariance.component(i, j); diffusionComponent.set(i, j, diffValue); samplingComponent.set(i, j, sampValue); diffusionComponent.set(j, i, diffValue); samplingComponent.set(j, i, sampValue); } } } } /** * recalculates the the sum of the diagonal elements and sum of all the elements of the tree variance * matrix statistic based on current parameters */ private void updateTreeSums() { double diagonalSum = MultivariateTraitDebugUtilities.getVarianceDiagonalSum(tree, treeLikelihood.getBranchRateModel(), 1.0); double offDiagonalSum = MultivariateTraitDebugUtilities.getVarianceOffDiagonalSum(tree, treeLikelihood.getBranchRateModel(), 1.0); RateRescalingScheme rescalingScheme = treeLikelihood.getDataLikelihoodDelegate().getRateRescalingScheme(); double normalization = 1.0; if (rescalingScheme == RateRescalingScheme.TREE_HEIGHT) { normalization = tree.getNodeHeight(tree.getRoot()); } else if (rescalingScheme == RateRescalingScheme.TREE_LENGTH) { //TODO: find function that returns tree length System.err.println("VarianceProportionStatistic not yet implemented for " + "traitDataLikelihood argument useTreeLength='true'."); } else if (rescalingScheme != RateRescalingScheme.NONE) { System.err.println("VarianceProportionStatistic not yet implemented for RateRescalingShceme" + rescalingScheme.getText() + "."); } treeSums.diagonalSum = diagonalSum / normalization; treeSums.totalSum = (diagonalSum + offDiagonalSum) / normalization; } private void updateSamplingVariance() { samplingVariance = dataModel.getSamplingVariance(); } private void updateDiffusionVariance() { diffusionVariance = new Matrix(diffusionModel.getPrecisionmatrix()).inverse(); } //TODO: move to difference class private void computeVariance(DenseMatrix64F matrix, double[] data, int numRows, int numCols) { double[] buffer = new double[numRows]; DenseMatrix64F sumVec = new DenseMatrix64F(numRows, 1); DenseMatrix64F matrixBuffer = new DenseMatrix64F(numCols, numCols); Arrays.fill(matrix.getData(), 0); for (int i = 0; i < numRows; i++) { int offset = numCols * i; DenseMatrix64F wrapper = MissingOps.wrap(data, offset, numCols, 1, buffer); CommonOps.multTransB(wrapper, wrapper, matrixBuffer); CommonOps.addEquals(matrix, matrixBuffer); CommonOps.addEquals(sumVec, wrapper); } CommonOps.multTransB(sumVec, sumVec, matrixBuffer); CommonOps.addEquals(matrix, -1 / numRows, matrixBuffer); } //TODO: Move method below to a different class //TODO: implement this for DenseMatrix64F rather than Matrix private static Matrix getMatrixSqrt(Matrix M, Boolean invert) { DoubleMatrix2D S = new DenseDoubleMatrix2D(M.toComponents()); RobustEigenDecomposition eigenDecomp = new RobustEigenDecomposition(S, 100); DoubleMatrix1D eigenValues = eigenDecomp.getRealEigenvalues(); int dim = eigenValues.size(); for (int i = 0; i < dim; i++) { double value = Math.sqrt(eigenValues.get(i)); if (invert) { value = 1 / value; } eigenValues.set(i, value); } DoubleMatrix2D eigenVectors = eigenDecomp.getV(); for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { eigenVectors.set(i, j, eigenVectors.get(i, j) * eigenValues.get(j)); } } DoubleMatrix2D storageMatrix = new DenseDoubleMatrix2D(dim, dim); eigenVectors.zMult(eigenDecomp.getV(), storageMatrix, 1, 0, false, true); return new Matrix(storageMatrix.toArray()); } @Override public int getDimension() { return dimTrait * dimTrait; } @Override public double getStatisticValue(int dim) { boolean needToUpdate = false; if (!treeKnown) { updateTreeSums(); treeKnown = true; needToUpdate = true; } if (!varianceKnown) { if (useEmpiricalVariance) { } else { updateSamplingVariance(); updateDiffusionVariance(); } if (!forceResample) { varianceKnown = true; } needToUpdate = true; } if (needToUpdate) { try { updateDiffsionProportion(); } catch (IllegalDimension illegalDimension) { illegalDimension.printStackTrace(); } } int d1 = dim / dimTrait; int d2 = dim - d1 * dimTrait; return diffusionProportion.get(d1, d2); } @Override public void variableChangedEvent(Variable variable, int index, Variable.ChangeType type) { assert (variable == dataModel.getSamplingPrecision() || variable == diffusionModel.getPrecisionParameter()); varianceKnown = false; } @Override public void modelChangedEvent(Model model, Object object, int index) { assert (model == tree); treeKnown = false; } //TODO: make its own class in evomodelxml public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { @Override public Object parseXMLObject(XMLObject xo) throws XMLParseException { TreeModel tree = (TreeModel) xo.getChild(TreeModel.class); RepeatedMeasuresTraitDataModel dataModel = (RepeatedMeasuresTraitDataModel) xo.getChild(RepeatedMeasuresTraitDataModel.class); MultivariateDiffusionModel diffusionModel = (MultivariateDiffusionModel) xo.getChild(MultivariateDiffusionModel.class); TreeDataLikelihood treeLikelihood = (TreeDataLikelihood) xo.getChild(TreeDataLikelihood.class); String ratioString = xo.getStringAttribute(MATRIX_RATIO); MatrixRatios ratio = null; if (ratioString.equalsIgnoreCase(ELEMENTWISE)) { ratio = MatrixRatios.ELEMENT_WISE; } else if (ratioString.equalsIgnoreCase(SYMMETRIC_DIVISION)) { ratio = MatrixRatios.SYMMETRIC_DIVISION; } else { throw new RuntimeException(PARSER_NAME + " must have attibute " + MATRIX_RATIO + " with one of the following values: " + MatrixRatios.values()); } return new VarianceProportionStatistic(tree, treeLikelihood, dataModel, diffusionModel, ratio); } private final XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ AttributeRule.newStringRule(MATRIX_RATIO, false), new ElementRule(TreeModel.class), new ElementRule(TreeDataLikelihood.class), new ElementRule(RepeatedMeasuresTraitDataModel.class), new ElementRule(MultivariateDiffusionModel.class) }; @Override public XMLSyntaxRule[] getSyntaxRules() { return rules; } @Override public String getParserDescription() { return "This element returns a statistic that computes proportion of variance due to diffusion on the tree"; } @Override public Class getReturnType() { return VarianceProportionStatistic.class; } @Override public String getParserName() { return PARSER_NAME; } }; @Override public void modelRestored(Model model) { // Do nothing } }
package com.futurice.festapp.service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class ServiceBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent ) { if (intent.getExtras() != null && intent.getBooleanExtra("com.futurice.festapp.service.FORCE", false)){ Intent myIntent = new Intent( context, FestAppService.class ); myIntent.putExtra("force", true); context.startService( myIntent ); } else{ Intent myIntent = new Intent( context, FestAppService.class ); context.startService( myIntent ); } } }
package com.intuit.karate.driver; import com.intuit.karate.FileUtils; import com.intuit.karate.Http; import com.intuit.karate.KarateException; import com.intuit.karate.LogAppender; import com.intuit.karate.Logger; import com.intuit.karate.driver.appium.AndroidDriver; import com.intuit.karate.driver.chrome.Chrome; import com.intuit.karate.driver.chrome.ChromeWebDriver; import com.intuit.karate.driver.microsoft.EdgeChromium; import com.intuit.karate.driver.microsoft.IeWebDriver; import com.intuit.karate.driver.microsoft.MsWebDriver; import com.intuit.karate.driver.firefox.GeckoWebDriver; import com.intuit.karate.driver.appium.IosDriver; import com.intuit.karate.driver.microsoft.MsEdgeDriver; import com.intuit.karate.driver.safari.SafariWebDriver; import com.intuit.karate.driver.microsoft.WinAppDriver; import com.intuit.karate.driver.playwright.PlaywrightDriver; import com.intuit.karate.core.Config; import com.intuit.karate.core.ScenarioEngine; import com.intuit.karate.shell.Command; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.Supplier; /** * * @author pthomas3 */ public class DriverOptions { public final Map<String, Object> options; public final int timeout; public final boolean start; public final boolean stop; public final String executable; public final String type; public final int port; public final String host; public final int pollAttempts; public final int pollInterval; public final boolean headless; public final boolean showProcessLog; public final boolean showDriverLog; public final Logger logger; public final LogAppender appender; public final Logger processLogger; public final Logger driverLogger; public final String uniqueName; public final File workingDir; public final String userAgent; public final String userDataDir; public final String processLogFile; public final int maxPayloadSize; public final List<String> addOptions; public final List<String> args = new ArrayList<>(); public final String webDriverUrl; public final String webDriverPath; public final Map<String, Object> webDriverSession; public final Map<String, Object> httpConfig; public final Target target; public final String beforeStart; public final String afterStop; public final String videoFile; public final boolean highlight; public final int highlightDuration; public final String attach; public final boolean screenshotOnFailure; public final String playwrightUrl; public final Map<String, Object> playwrightOptions; // mutable during a test private boolean retryEnabled; private Integer retryInterval = null; private Integer retryCount = null; private String preSubmitHash = null; private Integer timeoutOverride; public static final String SCROLL_JS_FUNCTION = "function(e){ var d = window.getComputedStyle(e).display;" + " while(d == 'none'){ e = e.parentElement; d = window.getComputedStyle(e).display }" + " e.scrollIntoView({block: 'center'}) }"; public static final String KARATE_REF_GENERATOR = "function(e){" + " if (!document._karate) document._karate = { seq: (new Date()).getTime() };" + " var ref = 'ref' + document._karate.seq++; document._karate[ref] = e; return ref }"; public boolean isRetryEnabled() { return retryEnabled; } public String getPreSubmitHash() { return preSubmitHash; } public void setPreSubmitHash(String preSubmitHash) { this.preSubmitHash = preSubmitHash; } private <T> T get(String key, T defaultValue) { T temp = (T) options.get(key); return temp == null ? defaultValue : temp; } public DriverOptions(Map<String, Object> options, LogAppender appender, int defaultPort, String defaultExecutable) { this.options = options; this.appender = appender; logger = new Logger(getClass()); logger.setAppender(appender); timeout = get("timeout", Config.DEFAULT_TIMEOUT); type = get("type", null); start = get("start", true); stop = get("stop", true); executable = get("executable", defaultExecutable); headless = get("headless", false); showProcessLog = get("showProcessLog", false); addOptions = get("addOptions", null); uniqueName = type + "_" + System.currentTimeMillis(); String packageName = getClass().getPackage().getName(); processLogger = showProcessLog ? logger : new Logger(packageName + "." + uniqueName); showDriverLog = get("showDriverLog", false); driverLogger = showDriverLog ? logger : new Logger(packageName + "." + uniqueName); if (executable != null) { if (executable.startsWith(".")) { // honor path even when we set working dir args.add(new File(executable).getAbsolutePath()); } else { args.add(executable); } } userAgent = get("userAgent", null); if (options.containsKey("userDataDir")) { String temp = get("userDataDir", null); if (temp != null) { workingDir = new File(temp); userDataDir = workingDir.getAbsolutePath(); } else { // special case allow user-specified null userDataDir = null; workingDir = null; } } else { workingDir = new File(FileUtils.getBuildDir() + File.separator + uniqueName); userDataDir = workingDir.getAbsolutePath(); } if (workingDir == null) { processLogFile = FileUtils.getBuildDir() + File.separator + uniqueName + ".log"; } else { processLogFile = workingDir.getPath() + File.separator + type + ".log"; } maxPayloadSize = get("maxPayloadSize", 4194304); target = get("target", null); host = get("host", "localhost"); webDriverUrl = get("webDriverUrl", null); webDriverPath = get("webDriverPath", null); webDriverSession = get("webDriverSession", null); httpConfig = get("httpConfig", null); beforeStart = get("beforeStart", null); afterStop = get("afterStop", null); videoFile = get("videoFile", null); pollAttempts = get("pollAttempts", 20); pollInterval = get("pollInterval", 250); highlight = get("highlight", false); highlightDuration = get("highlightDuration", Config.DEFAULT_HIGHLIGHT_DURATION); attach = get("attach", null); screenshotOnFailure = get("screenshotOnFailure", true); playwrightUrl = get("playwrightUrl", null); playwrightOptions = get("playwrightOptions", null); // do this last to ensure things like logger, start-flag, webDriverUrl etc. are set port = resolvePort(defaultPort); } private int resolvePort(int defaultPort) { if (webDriverUrl != null) { return 0; } int preferredPort = get("port", defaultPort); if (start) { int freePort = Command.getFreePort(preferredPort); if (freePort != preferredPort) { logger.warn("preferred port {} not available, will use: {}", preferredPort, freePort); } return freePort; } return preferredPort; } public Http getHttp() { Http http = Http.to(getUrlBase()); http.setAppender(driverLogger.getAppender()); if (httpConfig != null) { http.configure(httpConfig); } return http; } private String getUrlBase() { if (webDriverUrl != null) { return webDriverUrl; } String urlBase = "http://" + host + ":" + port; if (webDriverPath != null) { return urlBase + webDriverPath; } return urlBase; } public void arg(String arg) { args.add(arg); } public Command startProcess() { return startProcess(null); } public Command startProcess(Consumer<String> listener) { if (beforeStart != null) { Command.execLine(null, beforeStart); } Command command; if (target != null || !start) { command = null; } else { if (addOptions != null) { args.addAll(addOptions); } command = new Command(false, processLogger, uniqueName, processLogFile, workingDir, args.toArray(new String[args.size()])); if (listener != null) { command.setListener(listener); } command.setPollAttempts(pollAttempts); command.setPollInterval(pollInterval); command.start(); } if (command != null) { // wait for a slow booting browser / driver process command.waitForPort(host, port); if (command.isFailed()) { throw new KarateException("start failed", command.getFailureReason()); } } return command; } public static Driver start(Map<String, Object> options, Logger logger, LogAppender appender) { // TODO unify logger Target target = (Target) options.get("target"); if (target != null) { logger.debug("custom target configured, calling start()"); Map<String, Object> map = target.start(logger); logger.trace("custom target returned options: {}", map); options.putAll(map); } String type = (String) options.get("type"); if (type == null) { logger.warn("type was null, defaulting to 'chrome'"); type = "chrome"; options.put("type", type); } try { // to make troubleshooting errors easier switch (type) { case "chrome": return Chrome.start(options, appender); case "msedge": return EdgeChromium.start(options, appender); case "chromedriver": return ChromeWebDriver.start(options, appender); case "geckodriver": return GeckoWebDriver.start(options, appender); case "safaridriver": return SafariWebDriver.start(options, appender); case "msedgedriver": return MsEdgeDriver.start(options, appender); case "mswebdriver": return MsWebDriver.start(options, appender); case "iedriver": return IeWebDriver.start(options, appender); case "winappdriver": return WinAppDriver.start(options, appender); case "android": return AndroidDriver.start(options, appender); case "ios": return IosDriver.start(options, appender); case "playwright": return PlaywrightDriver.start(options, appender); default: logger.warn("unknown driver type: {}, defaulting to 'chrome'", type); options.put("type", "chrome"); return Chrome.start(options, appender); } } catch (Exception e) { String message = "driver config / start failed: " + e.getMessage() + ", options: " + options; logger.error(message, e); if (target != null) { target.stop(logger); } throw new RuntimeException(message, e); } } private Map<String, Object> getSession(String browserName) { Map<String, Object> session = webDriverSession; if (session == null) { session = new HashMap(); } Map<String, Object> capabilities = (Map) session.get("capabilities"); if (capabilities == null) { capabilities = (Map) session.get("desiredCapabilities"); } if (capabilities == null) { capabilities = new HashMap(); session.put("capabilities", capabilities); Map<String, Object> alwaysMatch = new HashMap(); capabilities.put("alwaysMatch", alwaysMatch); alwaysMatch.put("browserName", browserName); } return session; } // TODO abstract as method per implementation public Map<String, Object> getWebDriverSessionPayload() { switch (type) { case "chromedriver": return getSession("chrome"); case "geckodriver": return getSession("firefox"); case "safaridriver": return getSession("safari"); case "msedgedriver": case "mswebdriver": return getSession("edge"); case "iedriver": return getSession("internet explorer"); default: // else user has to specify full payload via webDriverSession return getSession(type); } } public static String preProcessWildCard(String locator) { boolean contains; String tag, prefix, text; int index; int pos = locator.indexOf('}'); if (pos == -1) { throw new RuntimeException("bad locator prefix: " + locator); } if (locator.charAt(1) == '^') { contains = true; prefix = locator.substring(2, pos); } else { contains = false; prefix = locator.substring(1, pos); } text = locator.substring(pos + 1); pos = prefix.indexOf(':'); if (pos != -1) { String tagTemp = prefix.substring(0, pos); tag = tagTemp.isEmpty() ? "*" : tagTemp; String indexTemp = prefix.substring(pos + 1); if (indexTemp.isEmpty()) { index = 0; } else { try { index = Integer.valueOf(indexTemp); } catch (Exception e) { throw new RuntimeException("bad locator prefix: " + locator + ", " + e.getMessage()); } } } else { tag = prefix.isEmpty() ? "*" : prefix; index = 0; } if (!tag.startsWith("/")) { tag = "//" + tag; } String xpath; if (contains) { xpath = tag + "[contains(normalize-space(text()),'" + text + "')]"; } else { xpath = tag + "[normalize-space(text())='" + text + "']"; } if (index == 0) { return xpath; } return "/(" + xpath + ")[" + index + "]"; } private static final String DOCUMENT = "document"; public static String selector(String locator) { return selector(locator, DOCUMENT); } public static String selector(String locator, String contextNode) { if (locator.startsWith("(")) { return locator; // pure js ! } if (locator.startsWith("{")) { locator = preProcessWildCard(locator); } if (locator.startsWith("/")) { // XPathResult.FIRST_ORDERED_NODE_TYPE = 9 if (locator.startsWith("/(")) { locator = locator.substring(1); // hack for wildcard with index (see preProcessWildCard last line) } return "document.evaluate(\"" + locator + "\", " + contextNode + ", null, 9, null).singleNodeValue"; } return contextNode + ".querySelector(\"" + locator + "\")"; } public void setTimeout(Integer timeout) { this.timeoutOverride = timeout; } public int getTimeout() { if (timeoutOverride != null) { return timeoutOverride; } return timeout; } public void setRetryInterval(Integer retryInterval) { this.retryInterval = retryInterval; } public int getRetryInterval() { if (retryInterval != null) { return retryInterval; } ScenarioEngine engine = ScenarioEngine.get(); if (engine == null) { return Config.DEFAULT_RETRY_INTERVAL; } else { return engine.getConfig().getRetryInterval(); } } public int getRetryCount() { if (retryCount != null) { return retryCount; } ScenarioEngine engine = ScenarioEngine.get(); if (engine == null) { return Config.DEFAULT_RETRY_COUNT; } else { return ScenarioEngine.get().getConfig().getRetryCount(); } } public <T> T retry(Supplier<T> action, Predicate<T> condition, String logDescription, boolean failWithException) { long startTime = System.currentTimeMillis(); int count = 0, max = getRetryCount(); T result; boolean success; do { if (count > 0) { logger.debug("{} - retry #{}", logDescription, count); sleep(); } result = action.get(); success = condition.test(result); } while (!success && count++ < max); if (!success) { long elapsedTime = System.currentTimeMillis() - startTime; String message = logDescription + ": failed after " + (count - 1) + " retries and " + elapsedTime + " milliseconds"; logger.warn(message); if (failWithException) { throw new RuntimeException(message); } } return result; } public static String wrapInFunctionInvoke(String text) { return "(function(){ " + text + " })()"; } private static final String HIGHLIGHT_FN = "function(e){ var old = e.getAttribute('style');" + " e.setAttribute('style', 'background: yellow; border: 2px solid red;');" + " setTimeout(function(){ e.setAttribute('style', old) }, %d) }"; private static String highlightFn(int millis) { return String.format(HIGHLIGHT_FN, millis); } public String highlight(String locator, int millis) { String e = selector(locator); String temp = "var e = " + e + "; var fun = " + highlightFn(millis) + "; fun(e)"; return wrapInFunctionInvoke(temp); } public String highlightAll(String locator, int millis) { return scriptAllSelector(locator, highlightFn(millis)); } public String optionSelector(String locator, String text) { boolean textEquals = text.startsWith("{}"); boolean textContains = text.startsWith("{^}"); String condition; if (textEquals || textContains) { text = text.substring(text.indexOf('}') + 1); condition = textContains ? "e.options[i].text.indexOf(t) !== -1" : "e.options[i].text === t"; } else { condition = "e.options[i].value === t"; } String e = selector(locator); String temp = "var e = " + e + "; var t = \"" + text + "\";" + " for (var i = 0; i < e.options.length; ++i)" + " if (" + condition + ") { e.options[i].selected = true; e.dispatchEvent(new Event('change')) }"; return wrapInFunctionInvoke(temp); } public String optionSelector(String id, int index) { String e = selector(id); String temp = "var e = " + e + "; var t = " + index + ";" + " for (var i = 0; i < e.options.length; ++i)" + " if (i === t) { e.options[i].selected = true; e.dispatchEvent(new Event('change')) }"; return wrapInFunctionInvoke(temp); } private String fun(String expression) { char first = expression.charAt(0); return (first == '_' || first == '!') ? "function(_){ return " + expression + " }" : expression; } public String scriptSelector(String locator, String expression) { return scriptSelector(locator, expression, DOCUMENT); } public String scriptSelector(String locator, String expression, String contextNode) { String temp = "var fun = " + fun(expression) + "; var e = " + selector(locator, contextNode) + "; return fun(e)"; return wrapInFunctionInvoke(temp); } public String scriptAllSelector(String locator, String expression) { return scriptAllSelector(locator, expression, DOCUMENT); } // the difference here from selector() is the use of querySelectorAll() // how the loop for XPath results has to be handled public String scriptAllSelector(String locator, String expression, String contextNode) { if (locator.startsWith("{")) { locator = preProcessWildCard(locator); } boolean isXpath = locator.startsWith("/"); String selector; if (isXpath) { // XPathResult.ORDERED_NODE_ITERATOR_TYPE = 5 selector = "document.evaluate(\"" + locator + "\", " + contextNode + ", null, 5, null)"; } else { selector = contextNode + ".querySelectorAll(\"" + locator + "\")"; } String temp = "var res = []; var fun = " + fun(expression) + "; var es = " + selector + "; "; if (isXpath) { temp = temp + "var e = null; while(e = es.iterateNext()) res.push(fun(e)); return res"; } else { temp = temp + "es.forEach(function(e){ res.push(fun(e)) }); return res"; } return wrapInFunctionInvoke(temp); } public void sleep() { sleep(getRetryInterval()); } public void sleep(int millis) { if (millis == 0) { return; } try { processLogger.trace("sleeping for millis: {}", millis); Thread.sleep(millis); } catch (Exception e) { throw new RuntimeException(e); } } public static String getPositionJs(String locator) { String temp = "var r = " + selector(locator, DOCUMENT) + ".getBoundingClientRect();" + " var dx = window.scrollX; var dy = window.scrollY;" + " return { x: r.x + dx, y: r.y + dy, width: r.width + dx, height: r.height + dy }"; return wrapInFunctionInvoke(temp); } public Map<String, Object> newMapWithSelectedKeys(Map<String, Object> map, String... keys) { Map<String, Object> out = new HashMap(keys.length); for (String key : keys) { Object o = map.get(key); if (o != null) { out.put(key, o); } } return out; } public void disableRetry() { retryEnabled = false; retryCount = null; retryInterval = null; } public void enableRetry(Integer count, Integer interval) { retryEnabled = true; retryCount = count; // can be null retryInterval = interval; // can be null } public Element waitUntil(Driver driver, String locator, String expression) { long startTime = System.currentTimeMillis(); String js = scriptSelector(locator, expression); boolean found = driver.waitUntil(js); if (!found) { long elapsedTime = System.currentTimeMillis() - startTime; throw new RuntimeException("wait failed for: " + locator + " and condition: " + expression + " after " + elapsedTime + " milliseconds"); } return DriverElement.locatorExists(driver, locator); } public String waitForUrl(Driver driver, String expected) { return retry(() -> driver.getUrl(), url -> url.contains(expected), "waitForUrl", true); } public Element waitForAny(Driver driver, String... locators) { long startTime = System.currentTimeMillis(); List<String> list = Arrays.asList(locators); Iterator<String> iterator = list.iterator(); StringBuilder sb = new StringBuilder(); while (iterator.hasNext()) { String locator = iterator.next(); String js = selector(locator); sb.append("(").append(js).append(" != null)"); if (iterator.hasNext()) { sb.append(" || "); } } boolean found = driver.waitUntil(sb.toString()); // important: un-set the retry flag disableRetry(); if (!found) { long elapsedTime = System.currentTimeMillis() - startTime; throw new RuntimeException("wait failed for: " + list + " after " + elapsedTime + " milliseconds"); } if (locators.length == 1) { return DriverElement.locatorExists(driver, locators[0]); } for (String locator : locators) { Element temp = driver.optional(locator); if (temp.isPresent()) { return temp; } } // this should never happen throw new RuntimeException("unexpected wait failure for locators: " + list); } public Element optional(Driver driver, String locator) { String js = selector(locator); String evalJs = js + " != null"; Object o = driver.script(evalJs); if (o instanceof Boolean && (Boolean) o) { return DriverElement.locatorExists(driver, locator); } else { return new MissingElement(driver, locator); } } public static String karateLocator(String karateRef) { return "(document._karate." + karateRef + ")"; } public String focusJs(String locator) { return "var e = " + selector(locator) + "; e.focus(); try { e.selectionStart = e.selectionEnd = e.value.length } catch(x) {}"; } public List<Element> findAll(Driver driver, String locator) { List<String> list = driver.scriptAll(locator, DriverOptions.KARATE_REF_GENERATOR); List<Element> elements = new ArrayList(list.size()); for (String karateRef : list) { String karateLocator = karateLocator(karateRef); elements.add(DriverElement.locatorExists(driver, karateLocator)); } return elements; } }
package com.itmill.toolkit.tests.featurebrowser; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import com.itmill.toolkit.data.Property; import com.itmill.toolkit.data.util.BeanItem; import com.itmill.toolkit.terminal.ErrorMessage; import com.itmill.toolkit.terminal.SystemError; import com.itmill.toolkit.terminal.ThemeResource; import com.itmill.toolkit.terminal.UserError; import com.itmill.toolkit.ui.AbstractComponent; import com.itmill.toolkit.ui.AbstractComponentContainer; import com.itmill.toolkit.ui.AbstractField; import com.itmill.toolkit.ui.Button; import com.itmill.toolkit.ui.Component; import com.itmill.toolkit.ui.DateField; import com.itmill.toolkit.ui.Field; import com.itmill.toolkit.ui.Form; import com.itmill.toolkit.ui.OptionGroup; import com.itmill.toolkit.ui.OrderedLayout; import com.itmill.toolkit.ui.Panel; import com.itmill.toolkit.ui.Select; import com.itmill.toolkit.ui.Table; import com.itmill.toolkit.ui.TextField; import com.itmill.toolkit.ui.Tree; import com.itmill.toolkit.ui.Window; public class PropertyPanel extends Panel implements Button.ClickListener, Property.ValueChangeListener { private Select addComponent; private final OrderedLayout formsLayout = new OrderedLayout(); private final LinkedList forms = new LinkedList(); private final Button setButton = new Button("Set", this); private final Button discardButton = new Button("Discard changes", this); private final Table allProperties = new Table(); private final Object objectToConfigure; private final BeanItem config; protected static final int COLUMNS = 3; /** Contruct new property panel for configuring given object. */ public PropertyPanel(Object objectToConfigure) { super(); getLayout().setMargin(false); // Layout setCaption("Properties"); addComponent(formsLayout); setSizeFull(); // Target object this.objectToConfigure = objectToConfigure; config = new BeanItem(objectToConfigure); // Control buttons final OrderedLayout buttons = new OrderedLayout( OrderedLayout.ORIENTATION_HORIZONTAL); buttons.setMargin(false, true, true, true); buttons.addComponent(setButton); buttons.addComponent(discardButton); addComponent(buttons); // Add default properties addBasicComponentProperties(); if (objectToConfigure instanceof Select) { addSelectProperties(); } if (objectToConfigure instanceof AbstractField && !(objectToConfigure instanceof Table || objectToConfigure instanceof Tree)) { addFieldProperties(); } if ((objectToConfigure instanceof AbstractComponentContainer)) { addComponentContainerProperties(); } // The list of all properties allProperties.addContainerProperty("Name", String.class, ""); allProperties.addContainerProperty("Type", String.class, ""); allProperties.addContainerProperty("R/W", String.class, ""); allProperties.addContainerProperty("Demo", String.class, ""); allProperties.setColumnAlignments(new String[] { Table.ALIGN_LEFT, Table.ALIGN_LEFT, Table.ALIGN_CENTER, Table.ALIGN_CENTER }); allProperties.setColumnHeaderMode(Table.COLUMN_HEADER_MODE_ID); allProperties.setPageLength(0); allProperties.setSizeFull(); updatePropertyList(); } /** Add a formful of properties to property panel */ public void addProperties(String propertySetCaption, Form properties) { // Create new panel containing the form final Panel p = new Panel(); p.setCaption(propertySetCaption); p.setStyleName(Panel.STYLE_LIGHT); p.addComponent(properties); formsLayout.addComponent(p); // Setup buffering properties.setWriteThrough(false); // TODO change this to false, and test it is suitable for FeatureBrowser // demo properties.setReadThrough(true); // Maintain property lists forms.add(properties); updatePropertyList(); } /** Recreate property list contents */ public void updatePropertyList() { allProperties.removeAllItems(); // Collect demoed properties final HashSet listed = new HashSet(); for (final Iterator i = forms.iterator(); i.hasNext();) { listed.addAll(((Form) i.next()).getItemPropertyIds()); } // Resolve all properties BeanInfo info; try { info = Introspector.getBeanInfo(objectToConfigure.getClass()); } catch (final IntrospectionException e) { throw new RuntimeException(e.toString()); } final PropertyDescriptor[] pd = info.getPropertyDescriptors(); // Fill the table for (int i = 0; i < pd.length; i++) { allProperties.addItem(new Object[] { pd[i].getName(), pd[i].getPropertyType().getName(), (pd[i].getWriteMethod() == null ? "R" : "R/W"), (listed.contains(pd[i].getName()) ? "x" : "") }, pd[i]); } } /** Add basic properties implemented most often by abstract component */ private void addBasicComponentProperties() { // Set of properties final Form set = createBeanPropertySet(new String[] { "caption", "icon", "componentError", "description", "enabled", "visible", "style", "readOnly", "immediate" }); // Icon set.replaceWithSelect("icon", new Object[] { null, new ThemeResource("icon/files/file.gif") }, new Object[] { "No icon", "Sample icon" }); // Component error Throwable sampleException; try { throw new NullPointerException("sample exception"); } catch (final NullPointerException e) { sampleException = e; } set .replaceWithSelect( "componentError", new Object[] { null, new UserError("Sample text error message."), new UserError( "<h3>Error message formatting</h3><p>Error messages can " + "contain any UIDL formatting, like: <ul><li><b>Bold" + "</b></li><li><i>Italic</i></li></ul></p>", UserError.CONTENT_UIDL, ErrorMessage.INFORMATION), new SystemError( "This is an example of exception error reposting", sampleException) }, new Object[] { "No error", "Sample text error", "Sample Formatted error", "Sample System Error" }); // Style final String currentStyle = ((Component) objectToConfigure) .getStyleName(); if (currentStyle == null) { set.replaceWithSelect("style", new Object[] { null }, new Object[] { "Default" }).setNewItemsAllowed(true); } else { set.replaceWithSelect("style", new Object[] { null, currentStyle }, new Object[] { "Default", currentStyle }) .setNewItemsAllowed(true); } // Set up descriptions set .getField("caption") .setDescription( "Component caption is the title of the component. Usage of the caption is optional and the " + "exact behavior of the propery is defined by the component. Setting caption null " + "or empty disables the caption."); set .getField("enabled") .setDescription( "Enabled property controls the usage of the component. If the component is disabled (enabled=false)," + " it can not receive any events from the terminal. In most cases it makes the usage" + " of the component easier, if the component visually looks disbled (for example is grayed), " + "when it can not be used."); set .getField("icon") .setDescription( "Icon of the component selects the main icon of the component. The usage of the icon is identical " + "to caption and in most components caption and icon are kept together. Icons can be " + "loaded from any resources (see Terminal/Resources for more information). Some components " + "contain more than just the captions icon. Those icons are controlled through their " + "own properties."); set .getField("visible") .setDescription( "Visibility property says if the component is renreded or not. Invisible components are implicitly " + "disabled, as there is no visible user interface to send event."); set .getField("description") .setDescription( "Description is designed to allow easy addition of short tooltips, like this. Like the caption," + " setting description null or empty disables the description."); set .getField("readOnly") .setDescription( "Those components that have internal state that can be written are settable to readOnly-mode," + " where the object can only be read, not written."); set .getField("componentError") .setDescription( "IT Mill Toolkit supports extensive error reporting. One part of the error reporting are component" + " errors that can be controlled by the programmer. This example only contains couple of " + "sample errors; to get the full picture, read browse ErrorMessage-interface implementors " + "API documentation."); set .getField("immediate") .setDescription( "Not all terminals can send the events immediately to server from all action. Web is the most " + "typical environment where many events (like textfield changed) are not sent to server, " + "before they are explicitly submitted. Setting immediate property true (by default this " + "is false for most components), the programmer can assure that the application is" + " notified as soon as possible about the value change in this component."); set .getField("style") .setDescription( "Themes specify the overall looks of the user interface. In addition component can have a set of " + "styles, that can be visually very different (like datefield calendar- and text-styles), " + "but contain the same logical functionality. As a rule of thumb, theme specifies if a " + "component is blue or yellow and style determines how the component is used."); // Add created fields to property panel addProperties("Component Basics", set); // Customization for Window component if (objectToConfigure instanceof Window) { disableField(set.getField("enabled"), new Boolean(true)); disableField(set.getField("visible"), new Boolean(true)); disableField(set.getField("componentError")); disableField(set.getField("icon")); } } /** Add properties for selecting */ private void addSelectProperties() { final Form set = createBeanPropertySet(new String[] { "newItemsAllowed", "lazyLoading", "multiSelect" }); addProperties("Select Properties", set); set.getField("multiSelect").setDescription( "Specified if multiple items can be selected at once."); set .getField("newItemsAllowed") .setDescription( "Select component (but not Tree or Table) can allow the user to directly " + "add new items to set of options. The new items are constrained to be " + "strings and thus feature only applies to simple lists."); /* * Button ll = (Button) set.getField("lazyLoading"); ll * .setDescription("In Ajax rendering mode select supports lazy loading * and filtering of options."); ll.addListener((ValueChangeListener) * this); ll.setImmediate(true); if (((Boolean) * ll.getValue()).booleanValue()) { * set.getField("multiSelect").setVisible(false); * set.getField("newItemsAllowed").setVisible(false); } */ if (objectToConfigure instanceof Tree || objectToConfigure instanceof Table) { set.removeItemProperty("newItemsAllowed"); set.removeItemProperty("lazyLoading"); } } /** Field special properties */ private void addFieldProperties() { // Set of properties final Form set = createBeanPropertySet(new String[] { "required" }); set.addField("focus", new Button("Focus", objectToConfigure, "focus")); set.getField("focus").setDescription( "Focus the cursor to this field. Not all " + "components and/or terminals support this feature."); addProperties("Field Features", set); } /** * Add and remove some miscellaneous example component to/from component * container */ private void addComponentContainerProperties() { final Form set = new Form(new OrderedLayout( OrderedLayout.ORIENTATION_VERTICAL)); addComponent = new Select(); addComponent.setImmediate(true); addComponent.addItem("Add component to container"); addComponent.setNullSelectionItemId("Add component to container"); addComponent.addItem("Text field"); addComponent.addItem("Option group"); addComponent.addListener(this); set.addField("component adder", addComponent); set.addField("remove all components", new Button( "Remove all components", objectToConfigure, "removeAllComponents")); addProperties("ComponentContainer Features", set); } /** Value change listener for listening selections */ public void valueChange(Property.ValueChangeEvent event) { // FIXME: navigation statistics try { FeatureUtil.debug(getApplication().getUser().toString(), "valueChange " + ((AbstractComponent) event.getProperty()) .getTag() + ", " + event.getProperty()); } catch (final Exception e) { // ignored, should never happen } // Adding components to component container if (event.getProperty() == addComponent) { final String value = (String) addComponent.getValue(); if (value != null) { // TextField component if (value.equals("Text field")) { ((AbstractComponentContainer) objectToConfigure) .addComponent(new TextField("Test field")); } // DateField time style if (value.equals("Time")) { final DateField d = new DateField("Time", new Date()); d .setDescription("This is a DateField-component with text-style"); d.setResolution(DateField.RESOLUTION_MIN); d.setStyleName("text"); ((AbstractComponentContainer) objectToConfigure) .addComponent(d); } // Date field calendar style if (value.equals("Calendar")) { final DateField c = new DateField("Calendar", new Date()); c .setDescription("DateField-component with calendar-style and day-resolution"); c.setStyleName("calendar"); c.setResolution(DateField.RESOLUTION_DAY); ((AbstractComponentContainer) objectToConfigure) .addComponent(c); } // Select option group style if (value.equals("Option group")) { final OptionGroup s = new OptionGroup("Options"); s.setDescription("Select-component with optiongroup-style"); s.addItem("Linux"); s.addItem("Windows"); s.addItem("Solaris"); s.addItem("Symbian"); ((AbstractComponentContainer) objectToConfigure) .addComponent(s); } addComponent.setValue(null); } } else if (event.getProperty() == getField("lazyLoading")) { final boolean newValue = ((Boolean) event.getProperty().getValue()) .booleanValue(); final Field multiselect = getField("multiSelect"); final Field newitems = getField("newItemsAllowed"); if (newValue) { newitems.setValue(Boolean.FALSE); newitems.setVisible(false); multiselect.setValue(Boolean.FALSE); multiselect.setVisible(false); } else { newitems.setVisible(true); multiselect.setVisible(true); } } } /** Handle all button clicks for this panel */ public void buttonClick(Button.ClickEvent event) { // FIXME: navigation statistics try { FeatureUtil.debug(getApplication().getUser().toString(), "buttonClick " + event.getButton().getTag() + ", " + event.getButton().getCaption() + ", " + event.getButton().getValue()); } catch (final Exception e) { // ignored, should never happen } // Commit all changed on all forms if (event.getButton() == setButton) { commit(); } // Discard all changed on all forms if (event.getButton() == discardButton) { for (final Iterator i = forms.iterator(); i.hasNext();) { ((Form) i.next()).discard(); } } } /** * Helper function for creating forms from array of propety names. */ protected Form createBeanPropertySet(String names[]) { final Form set = new Form(new OrderedLayout( OrderedLayout.ORIENTATION_VERTICAL)); for (int i = 0; i < names.length; i++) { final Property p = config.getItemProperty(names[i]); if (p != null) { set.addItemProperty(names[i], p); final Field f = set.getField(names[i]); if (f instanceof TextField) { if (Integer.class.equals(p.getType())) { ((TextField) f).setColumns(4); } else { ((TextField) f).setNullSettingAllowed(true); ((TextField) f).setColumns(17); } } } } return set; } /** Find a field from all forms */ public Field getField(Object propertyId) { for (final Iterator i = forms.iterator(); i.hasNext();) { final Form f = (Form) i.next(); final Field af = f.getField(propertyId); if (af != null) { return af; } } return null; } public Table getAllProperties() { return allProperties; } protected void commit() { for (final Iterator i = forms.iterator(); i.hasNext();) { ((Form) i.next()).commit(); } } private void disableField(Field field) { field.setEnabled(false); field.setReadOnly(true); } private void disableField(Field field, Object value) { field.setValue(value); disableField(field); } }
// CacheStrategy.java package loci.formats.cache; import java.util.*; import loci.formats.FormatTools; public abstract class CacheStrategy implements CacheReporter, Comparator, ICacheStrategy { // -- Constants -- /** Default cache range. */ public static final int DEFAULT_RANGE = 0; // -- Fields -- /** Length of each dimensional axis. */ protected int[] lengths; /** The order in which planes should be loaded along each axis. */ protected int[] order; /** Number of planes to cache along each axis. */ protected int[] range; /** Priority for caching each axis. Controls axis caching order. */ protected int[] priorities; /** * The list of dimensional positions to consider caching, in order of * preference based on strategy, axis priority and planar ordering. */ private int[][] positions; /** * Whether load order array needs to be recomputed * before building the next load list. */ private boolean dirty; /** List of cache event listeners. */ protected Vector listeners; // -- Constructors -- /** Constructs a cache strategy. */ public CacheStrategy(int[] lengths) { this.lengths = lengths; order = new int[lengths.length]; Arrays.fill(order, CENTERED_ORDER); range = new int[lengths.length]; Arrays.fill(range, DEFAULT_RANGE); priorities = new int[lengths.length]; Arrays.fill(priorities, NORMAL_PRIORITY); positions = getPossiblePositions(); dirty = true; listeners = new Vector(); } // -- Abstract CacheStrategy API methods -- /** * Gets positions to consider for possible inclusion in the cache, * assuming a current position at the origin (0). */ protected abstract int[][] getPossiblePositions(); // -- CacheStrategy API methods -- /** * Computes the distance from the given axis value to the * axis center, taking into account the axis ordering scheme. */ public int distance(int axis, int value) { switch (order[axis]) { case CENTERED_ORDER: if (value == 0) return 0; int vb = lengths[axis] - value; return value <= vb ? value : vb; case FORWARD_ORDER: return value; case BACKWARD_ORDER: if (value == 0) return 0; return lengths[axis] - value; default: throw new IllegalStateException("unknown order: " + order[axis]); } } // -- Internal CacheStrategy API methods -- /** Shortcut for converting N-D position to rasterized position. */ protected int raster(int[] pos) { return FormatTools.positionToRaster(lengths, pos); } /** Shortcut for converting rasterized position to N-D position. */ protected int[] pos(int raster) { return FormatTools.rasterToPosition(lengths, raster); } /** * Shortcut for converting rasterized position to N-D position, * using the given array instead of allocating a new one. */ protected int[] pos(int raster, int[] pos) { return FormatTools.rasterToPosition(lengths, raster, pos); } /** Shortcut for computing total number of positions. */ protected int length() { return FormatTools.getRasterLength(lengths); } // -- CacheReporter API methods -- /* @see CacheReporter#addCacheListener(CacheListener) */ public void addCacheListener(CacheListener l) { synchronized (listeners) { listeners.add(l); } } /* @see CacheReporter#removeCacheListener(CacheListener) */ public void removeCacheListener(CacheListener l) { synchronized (listeners) { listeners.remove(l); } } /* @see CacheReporter#getCacheListeners() */ public CacheListener[] getCacheListeners() { CacheListener[] l; synchronized (listeners) { l = new CacheListener[listeners.size()]; listeners.copyInto(l); } return l; } // -- Comparator API methods -- /** * Default comparator orders dimensional positions based on distance from the * current position, taking into account axis priorities and planar ordering. */ public int compare(Object o1, Object o2) { int[] p1 = (int[]) o1; int[] p2 = (int[]) o2; // compare sum of axis distances for each priority for (int p=MAX_PRIORITY; p>=MIN_PRIORITY; p int dist1 = 0, dist2 = 0; for (int i=0; i<p1.length; i++) { if (priorities[i] == p) { dist1 += distance(i, p1[i]); dist2 += distance(i, p2[i]); } } int diff = dist1 - dist2; if (diff != 0) return diff; } // compare number of diverging axes for each priority for (int p=MAX_PRIORITY; p>=MIN_PRIORITY; p int div1 = 0, div2 = 0; for (int i=0; i<p1.length; i++) { if (priorities[i] == p) { if (p1[i] != 0) div1++; if (p2[i] != 0) div2++; } } int diff = div1 - div2; if (diff != 0) return diff; } return 0; } // -- ICacheStrategy API methods -- /* @see ICacheStrategy#getLoadList(int[]) */ public int[][] getLoadList(int[] pos) throws CacheException { int[][] loadList = null; synchronized (positions) { if (dirty) { // reorder the positions list Arrays.sort(positions, this); dirty = false; } // count up number of load list entries int c = 0; for (int i=0; i<positions.length; i++) { int[] ipos = positions[i]; // verify position is close enough to current position boolean ok = true; for (int j=0; j<ipos.length; j++) { if (distance(j, ipos[j]) > range[j]) { ok = false; break; } } if (ok) c++; // in range } loadList = new int[c][lengths.length]; c = 0; // build load list for (int i=0; i<positions.length; i++) { int[] ipos = positions[i]; // verify position is close enough to current position boolean ok = true; for (int j=0; j<ipos.length && c<loadList.length; j++) { if (distance(j, ipos[j]) > range[j]) { ok = false; break; } int value = (pos[j] + ipos[j]) % lengths[j]; // normalize axis value loadList[c][j] = value; } if (ok) c++; // in range; lock in load list entry } } return loadList; } /* @see ICacheStrategy#getPriorities() */ public int[] getPriorities() { return priorities; } /* @see ICacheStrategy#setPriority() */ public void setPriority(int priority, int axis) { if (priority < MIN_PRIORITY || priority > MAX_PRIORITY) { throw new IllegalArgumentException( "Invalid priority for axis #" + axis + ": " + priority); } synchronized (positions) { priorities[axis] = priority; dirty = true; } notifyListeners(new CacheEvent(this, CacheEvent.PRIORITIES_CHANGED)); } /* @see ICacheStrategy#getOrder() */ public int[] getOrder() { return order; } /* @see ICacheStrategy#getOrder() */ public void setOrder(int order, int axis) { if (order != CENTERED_ORDER && order != FORWARD_ORDER && order != BACKWARD_ORDER) { throw new IllegalArgumentException( "Invalid order for axis #" + axis + ": " + order); } synchronized (positions) { this.order[axis] = order; dirty = true; } notifyListeners(new CacheEvent(this, CacheEvent.ORDER_CHANGED)); } /* @see ICacheStrategy#getRange() */ public int[] getRange() { return range; } /* @see ICacheStrategy#setRange(int, int) */ public void setRange(int num, int axis) { if (num < 0) { throw new IllegalArgumentException( "Invalid range for axis #" + axis + ": " + num); } range[axis] = num; notifyListeners(new CacheEvent(this, CacheEvent.RANGE_CHANGED)); } /* @see ICacheStrategy#getLengths() */ public int[] getLengths() { return lengths; } // -- Helper methods -- /** Informs listeners of a cache update. */ protected void notifyListeners(CacheEvent e) { synchronized (listeners) { for (int i=0; i<listeners.size(); i++) { CacheListener l = (CacheListener) listeners.elementAt(i); l.cacheUpdated(e); } } } }
package com.peterson.markovchain; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Extension of the BasicMarkovChain to provide synchronized access to the generator. * This overrides the basic structure of the generator to use a synchronized map and lists. * @author Peterson, Ryan * Created: 6/8/15 */ public class SynchronizedBasicMarkovChain extends BasicMarkovChain { /** * Constructs a synchronized version of the generator. * This provides all the basic functionality to generate * markov chains, as described in the parent class. */ public SynchronizedBasicMarkovChain() { super(true); } /** * Constructs a synchronized version of the generator using an initial set of phrases * @param phrases the initial phrases to seed the generator with */ public SynchronizedBasicMarkovChain(String... phrases) { super(true); for(String s : phrases) super.addPhrase(s); } @Override protected List<String> newList() { return Collections.synchronizedList(new ArrayList<>()); } }
package com.airbnb.lottie.utils; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PathMeasure; import android.graphics.PointF; import android.graphics.RectF; import android.os.Build; import android.provider.Settings; import androidx.annotation.Nullable; import com.airbnb.lottie.L; import com.airbnb.lottie.animation.LPaint; import com.airbnb.lottie.animation.content.TrimPathContent; import com.airbnb.lottie.animation.keyframe.FloatKeyframeAnimation; import java.io.Closeable; import java.io.InterruptedIOException; import java.net.ProtocolException; import java.net.SocketException; import java.net.UnknownHostException; import java.net.UnknownServiceException; import java.nio.channels.ClosedChannelException; import javax.net.ssl.SSLException; public final class Utils { public static final int SECOND_IN_NANOS = 1000000000; private static final PathMeasure pathMeasure = new PathMeasure(); private static final Path tempPath = new Path(); private static final Path tempPath2 = new Path(); private static final float[] points = new float[4]; private static final float INV_SQRT_2 = (float) (Math.sqrt(2) / 2.0); private static float dpScale = -1; private Utils() { } public static Path createPath(PointF startPoint, PointF endPoint, PointF cp1, PointF cp2) { Path path = new Path(); path.moveTo(startPoint.x, startPoint.y); if (cp1 != null && cp2 != null && (cp1.length() != 0 || cp2.length() != 0)) { path.cubicTo( startPoint.x + cp1.x, startPoint.y + cp1.y, endPoint.x + cp2.x, endPoint.y + cp2.y, endPoint.x, endPoint.y); } else { path.lineTo(endPoint.x, endPoint.y); } return path; } public static void closeQuietly(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (RuntimeException rethrown) { throw rethrown; } catch (Exception ignored) { } } } public static float getScale(Matrix matrix) { points[0] = 0; points[1] = 0; // Use 1/sqrt(2) so that the hypotenuse is of length 1. points[2] = INV_SQRT_2; points[3] = INV_SQRT_2; matrix.mapPoints(points); float dx = points[2] - points[0]; float dy = points[3] - points[1]; return (float) Math.hypot(dx, dy); } public static boolean hasZeroScaleAxis(Matrix matrix) { points[0] = 0; points[1] = 0; // Random numbers. The only way these should map to the same thing as 0,0 is if the scale is 0. points[2] = 37394.729378f; points[3] = 39575.2343807f; matrix.mapPoints(points); if (points[0] == points[2] || points[1] == points[3]) { return true; } return false; } public static void applyTrimPathIfNeeded(Path path, @Nullable TrimPathContent trimPath) { if (trimPath == null || trimPath.isHidden()) { return; } float start = ((FloatKeyframeAnimation) trimPath.getStart()).getFloatValue(); float end = ((FloatKeyframeAnimation) trimPath.getEnd()).getFloatValue(); float offset = ((FloatKeyframeAnimation) trimPath.getOffset()).getFloatValue(); applyTrimPathIfNeeded(path, start / 100f, end / 100f, offset / 360f); } public static void applyTrimPathIfNeeded( Path path, float startValue, float endValue, float offsetValue) { L.beginSection("applyTrimPathIfNeeded"); pathMeasure.setPath(path, false); float length = pathMeasure.getLength(); if (startValue == 1f && endValue == 0f) { L.endSection("applyTrimPathIfNeeded"); return; } if (length < 1f || Math.abs(endValue - startValue - 1) < .01) { L.endSection("applyTrimPathIfNeeded"); return; } float start = length * startValue; float end = length * endValue; float newStart = Math.min(start, end); float newEnd = Math.max(start, end); float offset = offsetValue * length; newStart += offset; newEnd += offset; // If the trim path has rotated around the path, we need to shift it back. if (newStart >= length && newEnd >= length) { newStart = MiscUtils.floorMod(newStart, length); newEnd = MiscUtils.floorMod(newEnd, length); } if (newStart < 0) { newStart = MiscUtils.floorMod(newStart, length); } if (newEnd < 0) { newEnd = MiscUtils.floorMod(newEnd, length); } // If the start and end are equals, return an empty path. if (newStart == newEnd) { path.reset(); L.endSection("applyTrimPathIfNeeded"); return; } if (newStart >= newEnd) { newStart -= length; } tempPath.reset(); pathMeasure.getSegment( newStart, newEnd, tempPath, true); if (newEnd > length) { tempPath2.reset(); pathMeasure.getSegment( 0, newEnd % length, tempPath2, true); tempPath.addPath(tempPath2); } else if (newStart < 0) { tempPath2.reset(); pathMeasure.getSegment( length + newStart, length, tempPath2, true); tempPath.addPath(tempPath2); } path.set(tempPath); L.endSection("applyTrimPathIfNeeded"); } @SuppressWarnings("SameParameterValue") public static boolean isAtLeastVersion(int major, int minor, int patch, int minMajor, int minMinor, int minPatch) { if (major < minMajor) { return false; } else if (major > minMajor) { return true; } if (minor < minMinor) { return false; } else if (minor > minMinor) { return true; } return patch >= minPatch; } public static int hashFor(float a, float b, float c, float d) { int result = 17; if (a != 0) { result = (int) (31 * result * a); } if (b != 0) { result = (int) (31 * result * b); } if (c != 0) { result = (int) (31 * result * c); } if (d != 0) { result = (int) (31 * result * d); } return result; } public static float dpScale() { if (dpScale == -1) { dpScale = Resources.getSystem().getDisplayMetrics().density; } return dpScale; } public static float getAnimationScale(Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { return Settings.Global.getFloat(context.getContentResolver(), Settings.Global.ANIMATOR_DURATION_SCALE, 1.0f); } else { //noinspection deprecation return Settings.System.getFloat(context.getContentResolver(), Settings.System.ANIMATOR_DURATION_SCALE, 1.0f); } } /** * Resize the bitmap to exactly the same size as the specified dimension, changing the aspect ratio if needed. * Returns the original bitmap if the dimensions already match. */ public static Bitmap resizeBitmapIfNeeded(Bitmap bitmap, int width, int height) { if (bitmap.getWidth() == width && bitmap.getHeight() == height) { return bitmap; } Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, width, height, true); bitmap.recycle(); return resizedBitmap; } public static boolean isNetworkException(Throwable e) { return e instanceof SocketException || e instanceof ClosedChannelException || e instanceof InterruptedIOException || e instanceof ProtocolException || e instanceof SSLException || e instanceof UnknownHostException || e instanceof UnknownServiceException; } public static void saveLayerCompat(Canvas canvas, RectF rect, Paint paint) { saveLayerCompat(canvas, rect, paint, Canvas.ALL_SAVE_FLAG); } public static void saveLayerCompat(Canvas canvas, RectF rect, Paint paint, int flag) { L.beginSection("Utils#saveLayer"); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { // This method was deprecated in API level 26 and not recommended since 22, but its // 2-parameter replacement is only available starting at API level 21. canvas.saveLayer(rect, paint, flag); } else { canvas.saveLayer(rect, paint); } L.endSection("Utils#saveLayer"); } /** * For testing purposes only. DO NOT USE IN PRODUCTION. */ public static Bitmap renderPath(Path path) { RectF bounds = new RectF(); path.computeBounds(bounds, false); Bitmap bitmap = Bitmap.createBitmap((int) bounds.right, (int) bounds.bottom, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); Paint paint = new LPaint(); paint.setAntiAlias(true); paint.setColor(Color.BLUE); canvas.drawPath(path, paint); return bitmap; } }
package org.kaazing.robot.lang.ast; import static java.lang.String.format; import static org.kaazing.robot.lang.ast.util.AstUtil.equivalent; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import org.kaazing.robot.lang.ast.value.AstValue; public class AstWriteConfigNode extends AstCommandNode { private String type; private Map<String, AstValue> namesByName; private Map<String, AstValue> valuesByName; public AstWriteConfigNode() { this.namesByName = new LinkedHashMap<String, AstValue>(); this.valuesByName = new LinkedHashMap<String, AstValue>(); } public void setType(String type) { this.type = type; } public String getType() { return type; } public void setName(String name, AstValue value) { namesByName.put(name, value); } public AstValue getName(String name) { return namesByName.get(name); } public void setValue(String name, AstValue value) { valuesByName.put(name, value); } public AstValue getValue(String name) { return valuesByName.get(name); } public void addValue(AstValue value) { String name = format("value#%d", valuesByName.size()); valuesByName.put(name, value); } public Collection<AstValue> getValues() { return valuesByName.values(); } public AstValue getValue() { switch (valuesByName.size()) { case 0: return null; case 1: return valuesByName.values().iterator().next(); default: throw new IllegalStateException("Multiple values available, yet assuming only one value"); } } @Override public <R, P> R accept(Visitor<R, P> visitor, P parameter) throws Exception { return visitor.visit(this, parameter); } @Override protected int hashTo() { int hashCode = getClass().hashCode(); if (type != null) { hashCode <<= 4; hashCode ^= type.hashCode(); } if (valuesByName != null) { hashCode <<= 4; hashCode ^= valuesByName.hashCode(); } return hashCode; } @Override protected boolean equalTo(AstRegion that) { return that instanceof AstWriteConfigNode && equalTo((AstWriteConfigNode) that); } protected boolean equalTo(AstWriteConfigNode that) { return equivalent(this.type, that.type) && equivalent(this.valuesByName, that.valuesByName); } @Override protected void describe(StringBuilder buf) { super.describe(buf); buf.append("write ").append(type); for (AstValue name : namesByName.values()) { buf.append(' ').append(name); } for (AstValue value : valuesByName.values()) { buf.append(' ').append(value); } buf.append('\n'); } }
package com.ralitski.util.math.graph.search; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.PriorityQueue; import com.ralitski.util.math.graph.Edge; import com.ralitski.util.math.graph.Graph; import com.ralitski.util.math.graph.Node; public class GraphSearchGreedy implements GraphSearch { private boolean stopOnEnd; public GraphSearchGreedy() { this(true); } public GraphSearchGreedy(boolean stopOnEnd) { this.stopOnEnd = stopOnEnd; } @Override public LinkedList<Node> getPath(Graph graph, Node start, Node end) { PriorityQueue<DijkstraNode> frontier = new PriorityQueue<DijkstraNode>(); DijkstraNode dStart = new DijkstraNode(start, 0); frontier.add(dStart); Map<Node, Node> sources = new HashMap<Node, Node>(); sources.put(start, null); //stitch together graph and flow directions while(!frontier.isEmpty()) { DijkstraNode current = frontier.poll(); if(stopOnEnd && current.node.equals(end)) { break; } for(Edge e : graph.getConnected(current.node)) { Node next = e.getEnd(); DijkstraNode dNext = new DijkstraNode(next, getCost(graph, next, end)); if(!sources.containsKey(next)) { frontier.add(dNext); sources.put(next, current.node); } } } //construct path Node current = end; LinkedList<Node> path = new LinkedList<Node>(); path.add(current); while(!current.equals(start)) { current = sources.get(current); if(current == null) { System.out.println("No path"); return null; } path.add(current); } return path; } public float getCost(Graph g, Node node, Node end) { return Edge.distance(node, end); } private class DijkstraNode implements Comparable<DijkstraNode> { private Node node; private float cost; public DijkstraNode(Node n, float cost) { node = n; this.cost = cost; } public int compareTo(DijkstraNode n) { return (int)(cost - n.cost); } public boolean equals(Object o) { return super.equals(o) ? true : o instanceof DijkstraNode ? ((DijkstraNode)o).node.equals(node) : node.equals(o); } public String toString() { return "[" + node.toString() + ", " + cost + "]"; } } }
package org.languagetool.server; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.sun.net.httpserver.HttpServer; import org.jetbrains.annotations.Nullable; import org.languagetool.JLanguageTool; import org.languagetool.Language; import org.languagetool.Languages; import java.io.IOException; import java.util.*; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static org.languagetool.server.HTTPServerConfig.DEFAULT_PORT; /** * Super class for HTTP and HTTPS server. * * @since 2.0 */ abstract class Server { protected abstract String getProtocol(); protected static final Set<String> DEFAULT_ALLOWED_IPS = new HashSet<>(Arrays.asList( "0:0:0:0:0:0:0:1", // Suse Linux IPv6 stuff "0:0:0:0:0:0:0:1%0", // some(?) Mac OS X "127.0.0.1" )); protected int port; protected String host; protected HttpServer server; protected LanguageToolHttpHandler httpHandler; private boolean isRunning; /** * Start the server. */ public void run() { String hostName = host != null ? host : "localhost"; System.out.println("Starting LanguageTool " + JLanguageTool.VERSION + " (build date: " + JLanguageTool.BUILD_DATE + ") server on " + getProtocol() + "://" + hostName + ":" + port + "..."); server.start(); isRunning = true; System.out.println("Server started"); } /** * Stop the server. Once stopped, a server cannot be used again. */ public void stop() { if (httpHandler != null) { httpHandler.shutdown(); } if (server != null) { System.out.println("Stopping server"); server.stop(0); isRunning = false; System.out.println("Server stopped"); } } /** * @return whether the server is running * @since 2.0 */ public boolean isRunning() { return isRunning; } @Nullable protected RequestLimiter getRequestLimiterOrNull(HTTPServerConfig config) { int requestLimit = config.getRequestLimit(); int requestLimitInBytes = config.getRequestLimitInBytes(); int requestLimitPeriodInSeconds = config.getRequestLimitPeriodInSeconds(); if ((requestLimit > 0 || requestLimitInBytes > 0) && requestLimitPeriodInSeconds > 0) { return new RequestLimiter(requestLimit, requestLimitInBytes, requestLimitPeriodInSeconds); } return null; } @Nullable protected ErrorRequestLimiter getErrorRequestLimiterOrNull(HTTPServerConfig config) { int requestLimit = config.getTimeoutRequestLimit(); int requestLimitPeriodInSeconds = config.getRequestLimitPeriodInSeconds(); if (requestLimit > 0 && requestLimitPeriodInSeconds > 0) { return new ErrorRequestLimiter(requestLimit, requestLimitPeriodInSeconds); } return null; } protected static boolean usageRequested(String[] args) { return args.length == 1 && (args[0].equals("-h") || args[0].equals("--help")); } protected static void printCommonConfigFileOptions() { System.out.println(" 'mode' - 'LanguageTool' or 'AfterTheDeadline' (DEPRECATED) for emulation of After the Deadline output (optional)"); System.out.println(" 'afterTheDeadlineLanguage' - language code like 'en' or 'en-GB' (required if mode is 'AfterTheDeadline') - DEPRECATED"); System.out.println(" 'maxTextLength' - maximum text length, longer texts will cause an error (optional)"); System.out.println(" 'maxTextHardLength' - maximum text length, applies even to users with a special secret 'token' parameter (optional)"); System.out.println(" 'secretTokenKey' - secret JWT token key, if set by user and valid, maxTextLength can be increased by the user (optional)"); System.out.println(" 'maxCheckTimeMillis' - maximum time in milliseconds allowed per check (optional)"); System.out.println(" 'maxErrorsPerWordRate' - checking will stop with error if there are more rules matches per word (optional)"); System.out.println(" 'maxSpellingSuggestions' - only this many spelling errors will have suggestions for performance reasons (optional,\n" + " affects Hunspell-based languages only)"); System.out.println(" 'maxCheckThreads' - maximum number of threads working in parallel (optional)"); System.out.println(" 'cacheSize' - size of internal cache in number of sentences (optional, default: 0)"); System.out.println(" 'requestLimit' - maximum number of requests per requestLimitPeriodInSeconds (optional)"); System.out.println(" 'requestLimitInBytes' - maximum aggregated size of requests per requestLimitPeriodInSeconds (optional)"); System.out.println(" 'timeoutRequestLimit' - maximum number of timeout request (optional)"); System.out.println(" 'requestLimitPeriodInSeconds' - time period to which requestLimit and timeoutRequestLimit applies (optional)"); System.out.println(" 'languageModel' - a directory with '1grams', '2grams', '3grams' sub directories which contain a Lucene index"); System.out.println(" each with ngram occurrence counts; activates the confusion rule if supported (optional)"); System.out.println(" 'word2vecModel' - a directory with word2vec data (optional), see"); System.out.println(" https://github.com/languagetool-org/languagetool/blob/master/languagetool-standalone/CHANGES.md#word2vec"); System.out.println(" 'maxWorkQueueSize' - reject request if request queue gets larger than this (optional)"); System.out.println(" 'rulesFile' - a file containing rules configuration, such as .langugagetool.cfg (optional)"); System.out.println(" 'warmUp' - set to 'true' to warm up server at start, i.e. run a short check with all languages (optional)"); System.out.println(" 'blockedReferrers' - a comma-separated list of HTTP referrers that are blocked and will not be served (optional)"); } protected static void printCommonOptions() { System.out.println(" --port, -p PRT port to bind to, defaults to " + DEFAULT_PORT + " if not specified"); System.out.println(" --public allow this server process to be connected from anywhere; if not set,"); System.out.println(" it can only be connected from the computer it was started on"); System.out.println(" --allow-origin ORIGIN set the Access-Control-Allow-Origin header in the HTTP response,"); System.out.println(" used for direct (non-proxy) JavaScript-based access from browsers;"); System.out.println(" example: --allow-origin \"*\""); System.out.println(" --verbose, -v in case of exceptions, log the input text (up to 500 characters)"); System.out.println(" --languageModel a directory with '1grams', '2grams', '3grams' sub directories (per language)"); System.out.println(" which contain a Lucene index (optional, overwrites 'languageModel'"); System.out.println(" parameter in properties files)"); System.out.println(" --word2vecModel a directory with word2vec data (optional), see"); System.out.println(" https://github.com/languagetool-org/languagetool/blob/master/languagetool-standalone/CHANGES.md#word2vec"); } protected static void checkForNonRootUser() { if ("root".equals(System.getProperty("user.name"))) { System.out.println("****************************************************************************************************"); System.out.println("*** WARNING: this process is running as root - please do not run it as root for security reasons ***"); System.out.println("****************************************************************************************************"); } } protected ThreadPoolExecutor getExecutorService(LinkedBlockingQueue<Runnable> workQueue, HTTPServerConfig config) { int threadPoolSize = config.getMaxCheckThreads(); System.out.println("Setting up thread pool with " + threadPoolSize + " threads"); return new StoppingThreadPoolExecutor(threadPoolSize, workQueue); } /** * Check a tiny text with all languages and all variants, so that e.g. static caches * get initialized. This helps getting a slightly better performance when real * texts get checked. */ protected void warmUp() { List<Language> languages = Languages.get(); System.out.println("Running warm up with all " + languages.size() + " languages/variants:"); for (int i = 1; i <= 2; i++) { long startTime = System.currentTimeMillis(); for (Language language : languages) { System.out.print(language.getLocaleWithCountryAndVariant() + " "); JLanguageTool lt = new JLanguageTool(language); try { lt.check("test"); } catch (IOException e) { throw new RuntimeException(e); } } long endTime = System.currentTimeMillis(); float runTime = (endTime-startTime)/1000.0f; System.out.printf(Locale.ENGLISH, "\nRun #" + i + " took %.2fs\n", runTime); } System.out.println("Warm up finished"); } static class StoppingThreadPoolExecutor extends ThreadPoolExecutor { StoppingThreadPoolExecutor(int threadPoolSize, LinkedBlockingQueue<Runnable> workQueue) { super(threadPoolSize, threadPoolSize, 0L, TimeUnit.MILLISECONDS, workQueue, new ThreadFactoryBuilder().setNameFormat("lt-server-thread-%d").build()); } @Override protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); if (t != null && t instanceof OutOfMemoryError) { // we prefer to stop instead of being in an unstable state: //noinspection CallToPrintStackTrace t.printStackTrace(); System.exit(1); } } } }
package com.vaadin.demo.sampler.features.form; import java.io.Serializable; import java.util.Arrays; import java.util.Date; import java.util.UUID; import com.vaadin.data.Item; import com.vaadin.data.Validator; import com.vaadin.data.util.BeanItem; import com.vaadin.data.validator.StringLengthValidator; import com.vaadin.demo.sampler.ExampleUtil; import com.vaadin.ui.Button; import com.vaadin.ui.ComboBox; import com.vaadin.ui.Component; import com.vaadin.ui.DefaultFieldFactory; import com.vaadin.ui.Field; import com.vaadin.ui.Form; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.TextField; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.Window; import com.vaadin.ui.Button.ClickEvent; @SuppressWarnings("serial") public class FormPojoExample extends VerticalLayout { // the 'POJO' we're editing Person person; public FormPojoExample() { person = new Person(); // a person POJO BeanItem personItem = new BeanItem(person); // item from POJO // Create the Form final Form personForm = new Form(); personForm.setWriteThrough(false); // we want explicit 'apply' personForm.setInvalidCommitted(false); // no invalid values in datamodel // FieldFactory for customizing the fields and adding validators personForm.setFormFieldFactory(new PersonFieldFactory()); personForm.setItemDataSource(personItem); // bind to POJO via BeanItem // Determines which properties are shown, and in which order: personForm.setVisibleItemProperties(Arrays.asList(new String[] { "firstName", "lastName", "countryCode", "password", "birthdate", "shoesize", "uuid" })); // Add form to layout addComponent(personForm); // The cancel / apply buttons HorizontalLayout buttons = new HorizontalLayout(); buttons.setSpacing(true); Button discardChanges = new Button("Discard changes", new Button.ClickListener() { public void buttonClick(ClickEvent event) { personForm.discard(); } }); discardChanges.setStyleName(Button.STYLE_LINK); buttons.addComponent(discardChanges); Button apply = new Button("Apply", new Button.ClickListener() { public void buttonClick(ClickEvent event) { try { personForm.commit(); } catch (Exception e) { // Ingnored, we'll let the Form handle the errors } } }); buttons.addComponent(apply); personForm.getLayout().addComponent(buttons); // button for showing the internal state of the POJO Button showPojoState = new Button("Show POJO internal state", new Button.ClickListener() { public void buttonClick(ClickEvent event) { showPojoState(); } }); addComponent(showPojoState); } private void showPojoState() { Window.Notification n = new Window.Notification("POJO state", Window.Notification.TYPE_TRAY_NOTIFICATION); n.setPosition(Window.Notification.POSITION_CENTERED); n.setDescription("First name: " + person.getFirstName() + "<br/>Last name: " + person.getLastName() + "<br/>Country: " + person.getCountryCode() + "<br/>Birthdate: " + person.getBirthdate() + "<br/>Shoe size: " + +person.getShoesize() + "<br/>Password: " + person.getPassword() + "<br/>UUID: " + person.getUuid()); getWindow().showNotification(n); } private class PersonFieldFactory extends DefaultFieldFactory { final ComboBox countries = new ComboBox("Country"); public PersonFieldFactory() { countries.setWidth("30em"); countries.setContainerDataSource(ExampleUtil.getISO3166Container()); countries .setItemCaptionPropertyId(ExampleUtil.iso3166_PROPERTY_NAME); countries.setItemIconPropertyId(ExampleUtil.iso3166_PROPERTY_FLAG); countries.setFilteringMode(ComboBox.FILTERINGMODE_STARTSWITH); } @Override public Field createField(Item item, Object propertyId, Component uiContext) { if ("countryCode".equals(propertyId)) { // filtering ComboBox w/ country names return countries; } Field f = super.createField(item, propertyId, uiContext); if ("firstName".equals(propertyId)) { TextField tf = (TextField) f; tf.setRequired(true); tf.setRequiredError("Please enter a First Name"); tf.setWidth("15em"); tf.addValidator(new StringLengthValidator( "First Name must be 3-25 characters", 3, 25, false)); } else if ("lastName".equals(propertyId)) { TextField tf = (TextField) f; tf.setRequired(true); tf.setRequiredError("Please enter a Last Name"); tf.setWidth("20em"); tf.addValidator(new StringLengthValidator( "Last Name must be 3-50 characters", 3, 50, false)); } else if ("password".equals(propertyId)) { TextField tf = (TextField) f; tf.setSecret(true); tf.setRequired(true); tf.setRequiredError("Please enter a password"); tf.setWidth("10em"); tf.addValidator(new StringLengthValidator( "Password must be 6-20 characters", 6, 20, false)); } else if ("shoesize".equals(propertyId)) { TextField tf = (TextField) f; tf.addValidator(new IntegerValidator( "Shoe size must be an Integer")); tf.setWidth("2em"); } else if ("uuid".equals(propertyId)) { TextField tf = (TextField) f; tf.setWidth("20em"); } return f; } } public class Person implements Serializable { private String firstName = ""; private String lastName = ""; private Date birthdate; private int shoesize = 42; private String password = ""; private UUID uuid; private String countryCode = ""; public Person() { uuid = UUID.fromString("3856c3da-ea56-4717-9f58-85f6c5f560a5"); } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Date getBirthdate() { return birthdate; } public void setBirthdate(Date birthdate) { this.birthdate = birthdate; } public int getShoesize() { return shoesize; } public void setShoesize(int shoesize) { this.shoesize = shoesize; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public UUID getUuid() { return uuid; } public String getCountryCode() { return countryCode; } public void setCountryCode(String countryCode) { this.countryCode = countryCode; } } public class IntegerValidator implements Validator { private String message; public IntegerValidator(String message) { this.message = message; } public boolean isValid(Object value) { if (value == null || !(value instanceof String)) { return false; } try { Integer.parseInt((String) value); } catch (Exception e) { return false; } return true; } public void validate(Object value) throws InvalidValueException { if (!isValid(value)) { throw new InvalidValueException(message); } } } }
package com.vaadin.terminal.gwt.client.ui; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import com.google.gwt.animation.client.Animation; import com.google.gwt.core.client.Duration; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.dom.client.Node; import com.google.gwt.dom.client.NodeList; import com.google.gwt.dom.client.Style; import com.google.gwt.dom.client.Touch; import com.google.gwt.event.dom.client.ScrollHandler; import com.google.gwt.event.dom.client.TouchStartEvent; import com.google.gwt.event.dom.client.TouchStartHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Event.NativePreviewEvent; import com.google.gwt.user.client.Event.NativePreviewHandler; import com.google.gwt.user.client.ui.Widget; import com.vaadin.terminal.gwt.client.BrowserInfo; import com.vaadin.terminal.gwt.client.VConsole; public class TouchScrollDelegate implements NativePreviewHandler { private static final double FRICTION = 0.002; private static final double DECELERATION = 0.002; private static final int MAX_DURATION = 1500; private int origY; private HashSet<Element> scrollableElements; private Element scrolledElement; private int origScrollTop; private HandlerRegistration handlerRegistration; private double lastAnimatedTranslateY; private int lastClientY; private int deltaScrollPos; private boolean transitionOn = false; private int finalScrollTop; private ArrayList<Element> layers; private boolean moved; private ScrollHandler scrollHandler; private static TouchScrollDelegate activeScrollDelegate; private static final boolean androidWithBrokenScrollTop = BrowserInfo.get() .isAndroidWithBrokenScrollTop(); public static class TouchScrollHandler implements TouchStartHandler { private final TouchScrollDelegate delegate; private final boolean requiresDelegate = BrowserInfo.get() .requiresTouchScrollDelegate(); public TouchScrollHandler(Widget widget, Element... scrollables) { if (requiresDelegate) { VConsole.log("REQUIRES DELEGATE"); delegate = new TouchScrollDelegate(); widget.addDomHandler(this, TouchStartEvent.getType()); } else { VConsole.log("DOES NOT REQUIRE DELEGATE"); delegate = null; } VConsole.log(BrowserInfo.getBrowserString()); BrowserInfo bi = BrowserInfo.get(); VConsole.log("Is Android: " + bi.isAndroid()); VConsole.log("Is Android with broken scrolltop: " + bi.isAndroidWithBrokenScrollTop()); VConsole.log("Is IOS: " + bi.isIOS()); VConsole.log("Is Webkit: " + bi.isWebkit()); for (Element scrollable : scrollables) { addElement(scrollable); } } public void onTouchStart(TouchStartEvent event) { assert delegate != null; delegate.onTouchStart(event); } public void debug(Element e) { VConsole.log("Classes: " + e.getClassName() + " overflow: " + e.getStyle().getProperty("overflow") + " w-o-s: " + e.getStyle().getProperty("-webkit-overflow-scrolling")); } public void addElement(Element scrollable) { scrollable.addClassName("v-scrollable"); scrollable.getStyle().setProperty("-webkit-overflow-scrolling", "touch"); scrollable.getStyle().setProperty("overflow-y", "auto"); scrollable.getStyle().setProperty("overflow-x", "hidden"); if (requiresDelegate) { delegate.scrollableElements.add(scrollable); } VConsole.log("Added scrollable: " + scrollable.getClassName()); } public void removeElement(Element scrollable) { scrollable.removeClassName("v-scrollable"); if (requiresDelegate) { delegate.scrollableElements.remove(scrollable); } } public void setElements(Element... scrollables) { if (requiresDelegate) { delegate.scrollableElements.clear(); } for (Element e : scrollables) { addElement(e); } } } public static TouchScrollHandler enableTouchScrolling(Widget widget, Element... scrollables) { return new TouchScrollHandler(widget, scrollables); } public TouchScrollDelegate(Element... elements) { scrollableElements = new HashSet<Element>(Arrays.asList(elements)); } public void setScrollHandler(ScrollHandler scrollHandler) { this.scrollHandler = scrollHandler; } public static TouchScrollDelegate getActiveScrollDelegate() { return activeScrollDelegate; } /** * Has user moved the touch. * * @return */ public boolean isMoved() { return moved; } /** * Forces the scroll delegate to cancels scrolling process. Can be called by * users if they e.g. decide to handle touch event by themselves after all * (e.g. a pause after touch start before moving touch -> interpreted as * long touch/click or drag start). */ public void stopScrolling() { handlerRegistration.removeHandler(); handlerRegistration = null; if (moved) { moveTransformationToScrolloffset(); } else { activeScrollDelegate = null; } } public void onTouchStart(TouchStartEvent event) { if (activeScrollDelegate == null && event.getTouches().length() == 1) { NativeEvent nativeEvent = event.getNativeEvent(); doTouchStart(nativeEvent); } else { /* * Touch scroll is currenly on (possibly bouncing). Ignore. */ } } private void doTouchStart(NativeEvent nativeEvent) { if (transitionOn) { momentum.cancel(); } Touch touch = nativeEvent.getTouches().get(0); if (detectScrolledElement(touch)) { VConsole.log("TouchDelegate takes over"); nativeEvent.stopPropagation(); handlerRegistration = Event.addNativePreviewHandler(this); activeScrollDelegate = this; origY = touch.getClientY(); yPositions[0] = origY; eventTimeStamps[0] = getTimeStamp(); nextEvent = 1; origScrollTop = getScrollTop(); VConsole.log("ST" + origScrollTop); moved = false; // event.preventDefault(); // event.stopPropagation(); } } private int getScrollTop() { if (androidWithBrokenScrollTop) { if (scrolledElement.getPropertyJSO("_vScrollTop") != null) { return scrolledElement.getPropertyInt("_vScrollTop"); } return 0; } return scrolledElement.getScrollTop(); } private void onTransitionEnd() { if (finalScrollTop < 0) { animateToScrollPosition(0, finalScrollTop); finalScrollTop = 0; } else if (finalScrollTop > getMaxFinalY()) { animateToScrollPosition(getMaxFinalY(), finalScrollTop); finalScrollTop = getMaxFinalY(); } else { moveTransformationToScrolloffset(); } } private void animateToScrollPosition(int to, int from) { int dist = Math.abs(to - from); int time = getAnimationTimeForDistance(dist); if (time <= 0) { time = 1; // get animation and transition end event } VConsole.log("Animate " + time + " " + from + " " + to); int translateTo = -to + origScrollTop; int fromY = -from + origScrollTop; if (androidWithBrokenScrollTop) { fromY -= origScrollTop; translateTo -= origScrollTop; } translateTo(time, fromY, translateTo); } private int getAnimationTimeForDistance(int dist) { return 350; // 350ms seems to work quite fine for all distances // if (dist < 0) { // dist = -dist; // return MAX_DURATION * dist / (scrolledElement.getClientHeight() * 3); } /** * Called at the end of scrolling. Moves possible translate values to * scrolltop, causing onscroll event. */ private void moveTransformationToScrolloffset() { if (androidWithBrokenScrollTop) { scrolledElement.setPropertyInt("_vScrollTop", finalScrollTop); if (scrollHandler != null) { scrollHandler.onScroll(null); } } else { for (Element el : layers) { Style style = el.getStyle(); style.setProperty("webkitTransform", "translate3d(0,0,0)"); } scrolledElement.setScrollTop(finalScrollTop); } activeScrollDelegate = null; handlerRegistration.removeHandler(); handlerRegistration = null; } /** * Detects if a touch happens on a predefined element and the element has * something to scroll. * * @param touch * @return */ private boolean detectScrolledElement(Touch touch) { Element target = touch.getTarget().cast(); for (Element el : scrollableElements) { if (el.isOrHasChild(target) && el.getScrollHeight() > el.getClientHeight()) { scrolledElement = el; layers = getElements(scrolledElement); return true; } } return false; } public static ArrayList<Element> getElements(Element scrolledElement2) { NodeList<Node> childNodes = scrolledElement2.getChildNodes(); ArrayList<Element> l = new ArrayList<Element>(); for (int i = 0; i < childNodes.getLength(); i++) { Node item = childNodes.getItem(i); if (item.getNodeType() == Node.ELEMENT_NODE) { l.add((Element) item); } } return l; } private void onTouchMove(NativeEvent event) { if (!moved) { double l = (getTimeStamp() - eventTimeStamps[0]); VConsole.log(l + " ms from start to move"); } boolean handleMove = readPositionAndSpeed(event); if (handleMove) { int deltaScrollTop = origY - lastClientY; int finalPos = origScrollTop + deltaScrollTop; if (finalPos > getMaxFinalY()) { // spring effect at the end int overscroll = (deltaScrollTop + origScrollTop) - getMaxFinalY(); overscroll = overscroll / 2; if (overscroll > getMaxOverScroll()) { overscroll = getMaxOverScroll(); } deltaScrollTop = getMaxFinalY() + overscroll - origScrollTop; } else if (finalPos < 0) { // spring effect at the beginning int overscroll = finalPos / 2; if (-overscroll > getMaxOverScroll()) { overscroll = -getMaxOverScroll(); } deltaScrollTop = overscroll - origScrollTop; } quickSetScrollPosition(0, deltaScrollTop); moved = true; event.preventDefault(); event.stopPropagation(); } } private void quickSetScrollPosition(int deltaX, int deltaY) { deltaScrollPos = deltaY; if (androidWithBrokenScrollTop) { deltaY += origScrollTop; translateTo(-deltaY); } else { translateTo(-deltaScrollPos); } } private static final int EVENTS_FOR_SPEED_CALC = 3; public static final int SIGNIFICANT_MOVE_THRESHOLD = 3; private int[] yPositions = new int[EVENTS_FOR_SPEED_CALC]; private double[] eventTimeStamps = new double[EVENTS_FOR_SPEED_CALC]; private int nextEvent = 0; private Animation momentum; /** * * @param event * @return */ private boolean readPositionAndSpeed(NativeEvent event) { Touch touch = event.getChangedTouches().get(0); lastClientY = touch.getClientY(); int eventIndx = nextEvent++; eventIndx = eventIndx % EVENTS_FOR_SPEED_CALC; eventTimeStamps[eventIndx] = getTimeStamp(); yPositions[eventIndx] = lastClientY; return isMovedSignificantly(); } private boolean isMovedSignificantly() { return moved ? moved : Math.abs(origY - lastClientY) >= SIGNIFICANT_MOVE_THRESHOLD; } private void onTouchEnd(NativeEvent event) { if (!moved) { activeScrollDelegate = null; handlerRegistration.removeHandler(); handlerRegistration = null; return; } int currentY = origScrollTop + deltaScrollPos; int maxFinalY = getMaxFinalY(); int pixelsToMove; int finalY; int duration = -1; if (currentY > maxFinalY) { // we are over the max final pos, animate to end pixelsToMove = maxFinalY - currentY; finalY = maxFinalY; } else if (currentY < 0) { // we are below the max final pos, animate to beginning pixelsToMove = -currentY; finalY = 0; } else { double pixelsPerMs = calculateSpeed(); // we are currently within scrollable area, calculate pixels that // we'll move due to momentum VConsole.log("pxPerMs" + pixelsPerMs); pixelsToMove = (int) (0.5 * pixelsPerMs * pixelsPerMs / FRICTION); if (pixelsPerMs < 0) { pixelsToMove = -pixelsToMove; } // VConsole.log("pixels to move" + pixelsToMove); finalY = currentY + pixelsToMove; if (finalY > maxFinalY + getMaxOverScroll()) { // VConsole.log("To max overscroll"); finalY = getMaxFinalY() + getMaxOverScroll(); int fixedPixelsToMove = finalY - currentY; pixelsToMove = fixedPixelsToMove; } else if (finalY < 0 - getMaxOverScroll()) { // VConsole.log("to min overscroll"); finalY = -getMaxOverScroll(); int fixedPixelsToMove = finalY - currentY; pixelsToMove = fixedPixelsToMove; } else { duration = (int) (Math.abs(pixelsPerMs / DECELERATION)); } } if (duration == -1) { // did not keep in side borders or was outside borders, calculate // a good enough duration based on pixelsToBeMoved. duration = getAnimationTimeForDistance(pixelsToMove); } if (duration > MAX_DURATION) { VConsole.log("Max animation time. " + duration); duration = MAX_DURATION; } finalScrollTop = finalY; if (Math.abs(pixelsToMove) < 3 || duration < 20) { VConsole.log("Small 'momentum' " + pixelsToMove + " | " + duration + " Skipping animation,"); moveTransformationToScrolloffset(); return; } int translateTo = -finalY + origScrollTop; int fromY = -currentY + origScrollTop; if (androidWithBrokenScrollTop) { fromY -= origScrollTop; translateTo -= origScrollTop; } translateTo(duration, fromY, translateTo); } private double calculateSpeed() { if (nextEvent < EVENTS_FOR_SPEED_CALC) { VConsole.log("Not enough data for speed calculation"); // not enough data for decent speed calculation, no momentum :-( return 0; } int idx = nextEvent % EVENTS_FOR_SPEED_CALC; final int firstPos = yPositions[idx]; final double firstTs = eventTimeStamps[idx]; idx += EVENTS_FOR_SPEED_CALC; idx idx = idx % EVENTS_FOR_SPEED_CALC; final int lastPos = yPositions[idx]; final double lastTs = eventTimeStamps[idx]; // speed as in change of scrolltop == -speedOfTouchPos return (firstPos - lastPos) / (lastTs - firstTs); } /** * Note positive scrolltop moves layer up, positive translate moves layer * down. */ private void translateTo(double translateY) { for (Element el : layers) { Style style = el.getStyle(); style.setProperty("webkitTransform", "translate3d(0px," + translateY + "px,0px)"); } } /** * Note positive scrolltop moves layer up, positive translate moves layer * down. * * @param duration */ private void translateTo(int duration, final int fromY, final int finalY) { if (duration > 0) { transitionOn = true; momentum = new Animation() { @Override protected void onUpdate(double progress) { lastAnimatedTranslateY = (fromY + (finalY - fromY) * progress); translateTo(lastAnimatedTranslateY); } @Override protected double interpolate(double progress) { return 1 + Math.pow(progress - 1, 3); } @Override protected void onComplete() { super.onComplete(); transitionOn = false; onTransitionEnd(); } @Override protected void onCancel() { int delta = (int) (finalY - lastAnimatedTranslateY); finalScrollTop -= delta; moveTransformationToScrolloffset(); transitionOn = false; } }; momentum.run(duration); } } private int getMaxOverScroll() { return androidWithBrokenScrollTop ? 0 : scrolledElement .getClientHeight() / 3; } private int getMaxFinalY() { return scrolledElement.getScrollHeight() - scrolledElement.getClientHeight(); } public void onPreviewNativeEvent(NativePreviewEvent event) { int typeInt = event.getTypeInt(); if (transitionOn) { /* * TODO allow starting new events. See issue in onTouchStart */ event.cancel(); if (typeInt == Event.ONTOUCHSTART) { doTouchStart(event.getNativeEvent()); } return; } switch (typeInt) { case Event.ONTOUCHMOVE: if (!event.isCanceled()) { onTouchMove(event.getNativeEvent()); if (moved) { event.cancel(); } } break; case Event.ONTOUCHEND: case Event.ONTOUCHCANCEL: if (!event.isCanceled()) { if (moved) { event.cancel(); } onTouchEnd(event.getNativeEvent()); } break; case Event.ONMOUSEMOVE: if (moved) { // no debug message, mobile safari generates these for some // compatibility purposes. event.cancel(); } break; default: VConsole.log("Non touch event:" + event.getNativeEvent().getType()); event.cancel(); break; } } /** * long calcucation are not very efficient in GWT, so this helper method * returns timestamp in double. * * @return */ public static double getTimeStamp() { return Duration.currentTimeMillis(); } }
package com.example.asm.resources; import android.annotation.SuppressLint; import android.content.DialogInterface; import android.os.Build; import android.support.v7.app.ActionBar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; public class full_char_list extends AppCompatActivity { private boolean mVisible; private Menu menu_bar; private View gifts; private View spheres; private View disciplines; private Spinner spinner_gd; private Spinner spinner_al; private Spinner spinner_cl; private ArrayAdapter<CharSequence> adapter_gd; private character char_o; private TextView attr_helper; private TextView abl_helper; private TextView bkg_helper; private TextView sph_helper; private TextView dis_helper; private TextView gft_helper; private TextView wp_show_helper; private final List<String> g_discs = new ArrayList<>(); private final String[] discs = { "animalism", "auspex", "celerity", "chimerstry", "daimoinon", "dementation", "dominate", "fortitude", "melpominee", "obfuscate", "obtenebration", "potence", "presence", "protean", "quietus", "serpentis", "temporis", "thanatosis", "vicissitude", "alchemistry", "conveyance", "enchantment", "healing", "hellfire", "weathercraft" }; private final String[] resources = { "rage", "faith", "wp" }; @SuppressWarnings({"UnusedParameters", "unused"}) public void switch_screen(View view) { if (mVisible) { hide(); } else { show(); } } private void hide() { ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.hide(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); } mVisible = false; } @SuppressLint("InlinedApi") private void show() { getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.show(); } mVisible = true; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.full_char_list); mVisible = true; char_o = (character) getIntent().getSerializableExtra("CHAR"); String c_name = char_o.char_name; TextView name = (TextView) findViewById(R.id.charlist_char_name); name.setText( String.format(Locale.getDefault(), "Имя игрока: %s", c_name) ); String cr_name = char_o.chronic_name; TextView chronic = (TextView) findViewById(R.id.charlist_chronic_name); chronic.setText( String.format(Locale.getDefault(), "Хроника: %s", cr_name) ); gifts = findViewById(R.id.gifts); spheres = findViewById(R.id.spheres); disciplines = findViewById(R.id.disciplines); // list for gods spinner_gd = (Spinner) findViewById(R.id.charlist_gods); // list for alignment spinner_al = (Spinner) findViewById(R.id.charlist_alignment); // list for classes spinner_cl = (Spinner) findViewById(R.id.charlist_class); attr_helper = (TextView) findViewById(R.id.attr_show_helper); abl_helper = (TextView) findViewById(R.id.abl_show_helper); bkg_helper = (TextView) findViewById(R.id.bkg_show_helper); sph_helper = (TextView) findViewById(R.id.sph_show_helper); dis_helper = (TextView) findViewById(R.id.dis_show_helper); gft_helper = (TextView) findViewById(R.id.gft_show_helper); wp_show_helper = (TextView) findViewById(R.id.wp_show_helper); fill_map(); update_helpers(); spinner_al.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { char_o.alignment = spinner_al.getSelectedItem().toString(); fix_gods_list( spinner_al.getSelectedItem().toString() ); } @Override public void onNothingSelected(AdapterView<?> parentView) { // your code here } }); spinner_gd.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { char_o.god = spinner_gd.getSelectedItem().toString(); show_god_disciplines( spinner_gd.getSelectedItem().toString() ); } @Override public void onNothingSelected(AdapterView<?> parentView) { // your code here } }); spinner_cl.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { String c_class = spinner_cl.getSelectedItem().toString(); char_o.class_name = c_class; select_class( c_class ); } @Override public void onNothingSelected(AdapterView<?> parentView) { // your code here } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.action_bar_menu, menu); menu_bar = menu; return true; } private void select_class( String c_class ) { switch (c_class) { case "Воин": show_sp("rage"); init_sp_points( "rage", 1 ); gifts.setVisibility(View.VISIBLE); spheres.setVisibility(View.GONE); disciplines.setVisibility(View.GONE); spinner_gd.setVisibility(View.GONE); findViewById( R.id.enlightenment ).setVisibility(View.GONE); findViewById( R.id.concentration ).setVisibility(View.GONE); if ( char_o.Generated == 0 ) { if (char_o.tal_abl.get("enlightenment") == 1) { set_range("abl", "enlightenment", 0); unset_upper_range("abl", "enlightenment", 0); char_o.return_m_point("tal_abl"); } if (char_o.kng_abl.get("religion") == 1) { set_range("abl", "religion", 0); unset_upper_range("abl", "religion", 0); char_o.return_m_point("kng_abl"); } update_helpers(); } break; case "Маг": show_sp("wp"); gifts.setVisibility(View.GONE); spheres.setVisibility(View.VISIBLE); disciplines.setVisibility(View.GONE); spinner_gd.setVisibility(View.GONE); findViewById( R.id.enlightenment ).setVisibility(View.VISIBLE); findViewById( R.id.concentration ).setVisibility(View.VISIBLE); if ( char_o.Generated == 0 ) { init_sp_points( "wp", 1 ); if (char_o.tal_abl.get("enlightenment") == 0) { set_range("abl", "enlightenment", 1); unset_upper_range("abl", "enlightenment", 1); char_o.delay_charge("enlightenment", 1); } if (char_o.kng_abl.get("religion") == 1) { set_range("abl", "religion", 0); unset_upper_range("abl", "religion", 0); char_o.return_m_point("kng_abl"); } update_helpers(); } break; case "Жрец": show_sp("faith"); init_sp_points( "faith", (char_o.kng_abl.get("religion") * 2) ); gifts.setVisibility(View.GONE); spheres.setVisibility(View.GONE); disciplines.setVisibility(View.VISIBLE); spinner_gd.setVisibility(View.VISIBLE); findViewById( R.id.enlightenment ).setVisibility(View.GONE); findViewById( R.id.concentration ).setVisibility(View.GONE); if ( char_o.Generated == 0 ) { if (char_o.kng_abl.get("religion") == 0) { set_range("abl", "religion", 1); unset_upper_range("abl", "religion", 1); char_o.delay_charge("religion", 1); } if (char_o.tal_abl.get("enlightenment") == 1) { set_range("abl", "enlightenment", 0); unset_upper_range("abl", "enlightenment", 0); char_o.return_m_point("tal_abl"); } update_helpers(); } break; } } private void init_sp_points( String res, Integer num ) { switch (res) { case "rage": if (char_o.sp_resources.get(res) == 0) { char_o.sp_resources.put(res, num); set_free_range(res, num); unset_free_upper_range(res, num); } break; case "wp": if (char_o.sp_resources.get("perm_" + res) == 0) { char_o.sp_resources.put("perm_" + res, num); set_range("button", res, 1); unset_upper_range("button", res, 1); } break; case "faith": char_o.sp_resources.put("perm_" + res, num); set_range("button", res, num); unset_upper_range("button", res, num); break; } reset_parameter( res ); } private void update_helpers() { if ( char_o.Generated == 0 ) { attr_helper.setText(Arrays.toString(char_o.attr)); abl_helper.setText(Arrays.toString(char_o.abl)); bkg_helper.setText(String.format(Locale.getDefault(), " [%d]", char_o.bkg_gen_points)); sph_helper.setText(String.format(Locale.getDefault(), " [%d]", char_o.class_feature_gen_points)); dis_helper.setText(String.format(Locale.getDefault(), " [%d]", char_o.class_feature_gen_points)); gft_helper.setText(String.format(Locale.getDefault(), " [%d]", char_o.class_feature_gen_points)); } else if ( char_o.Generated == 1 ) { attr_helper.setText(String.format(Locale.getDefault(), "Очков [%d], цена 5", char_o.free_points)); abl_helper.setText(String.format(Locale.getDefault(), "Очков [%d], цена 2", char_o.free_points)); bkg_helper.setText(String.format(Locale.getDefault(), "Очков [%d], цена 1", char_o.free_points)); sph_helper.setText(String.format(Locale.getDefault(), "Очков [%d], цена 7", char_o.free_points)); dis_helper.setText(String.format(Locale.getDefault(), "Очков [%d], цена 7", char_o.free_points)); gft_helper.setText(String.format(Locale.getDefault(), "Очков [%d], цена 7", char_o.free_points)); wp_show_helper.setText(String.format(Locale.getDefault(), "Очков [%d], цена 2", char_o.free_points)); } } private void show_sp( String resource ) { String id_ref; int resID; CheckBox res; View sp_view; for ( String r : resources ) { id_ref = String.format(Locale.getDefault(), "checkBox_%s", r); resID = getResources().getIdentifier(id_ref, "id", getPackageName()); res = (CheckBox) findViewById(resID); id_ref = String.format(Locale.getDefault(), "sp_%s", r); resID = getResources().getIdentifier(id_ref, "id", getPackageName()); sp_view = findViewById(resID); if ( r.equals(resource) ) { sp_view.setVisibility(View.VISIBLE); res.setChecked(false); } else { sp_view.setVisibility(View.GONE); res.setChecked(true); } } } @SuppressWarnings("unused") public void radio_button_clicked(View view) { String IdAsString = view.getResources().getResourceName(view.getId()); Pattern p = Pattern.compile("_(\\p{Lower}+)_(\\p{Lower}+)(\\d+)$"); Matcher m = p.matcher(IdAsString); String group; String name; Integer number; if( m.find() ){ group = m.group(1); name = m.group(2); number = Integer.parseInt(m.group(3)); } else { throw new RuntimeException( "Can't fine resource and value in " + IdAsString ); } if ( char_o.Generated == 0 ) { if ( group.equals("button") ) { return ; } number = char_o.save_new_values( group, name, number ); if ( number > 0 ) { set_range(group, name, number); } unset_upper_range( group, name, number ); if ( char_o.class_name.equals("Жрец") ) { if ( name.equals("religion") ) { init_sp_points( "faith", (char_o.kng_abl.get("religion") * 2) ); } } generation_complete(); switch (group) { case "attr": attr_helper.setText(Arrays.toString(char_o.attr)); break; case "abl": abl_helper.setText(Arrays.toString(char_o.abl)); break; case "bkg": bkg_helper.setText(String.format(Locale.getDefault(), " [%d]", char_o.bkg_gen_points)); break; case "sph": sph_helper.setText(String.format(Locale.getDefault(), " [%d]", char_o.class_feature_gen_points)); break; case "dis": dis_helper.setText(String.format(Locale.getDefault(), " [%d]", char_o.class_feature_gen_points)); break; case "gft": gft_helper.setText(String.format(Locale.getDefault(), " [%d]", char_o.class_feature_gen_points)); break; } } else if ( char_o.Generated == 1 ) { number = char_o.save_fp_values( group, name, number ); set_range( group, name, number ); unset_upper_range( group, name, number ); update_helpers(); fp_complete(); } update_summary( group, name ); } private void generation_complete() { if ( ! char_o.check_gen_points() ) { AlertDialog.Builder builder = new AlertDialog.Builder(full_char_list.this); builder.setTitle(R.string.generation); builder.setMessage(R.string.go_to_free); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { finish_gen_points(); } }); builder.setNegativeButton(R.string.cancel, null); builder.show(); } } private void finish_gen_points() { char_o.Generated = 1; wp_show_helper.setVisibility(View.VISIBLE); update_helpers(); char_o.store_values(); lock_unlock_names(); } private void fp_complete() { if ( char_o.free_points == 0 ) { AlertDialog.Builder builder = new AlertDialog.Builder(full_char_list.this); builder.setTitle(R.string.generation); builder.setMessage(R.string.finish_gen); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { finish_fp_points(); } }); builder.setNegativeButton(R.string.cancel, null); builder.show(); } } private void finish_fp_points() { char_o.Generated = 2; attr_helper.setVisibility(View.GONE); abl_helper.setVisibility(View.GONE); bkg_helper.setVisibility(View.GONE); sph_helper.setVisibility(View.GONE); dis_helper.setVisibility(View.GONE); gft_helper.setVisibility(View.GONE); char_o.store_values(); lock_unlock_names(); } private void update_summary( String group, String name ) { if ( group.equals("attr") ) { if (name.equals("strength")) { Integer atk = char_o.phis_attr.get("strength") + char_o.tal_abl.get("brawl"); TextView atk_v = (TextView) findViewById(R.id.atk_hands); atk_v.setText(getResources().getString(R.string.atk_hands) + atk ); Integer atk_s = char_o.phis_attr.get("strength") + char_o.skl_abl.get("melee"); Integer atk_d = char_o.phis_attr.get("dexterity") + char_o.skl_abl.get("melee"); atk_v = (TextView) findViewById(R.id.atk_melee); atk_v.setText(getResources().getString(R.string.atk_melee) + atk_s + "/" + atk_d); } else if (name.equals("dexterity")) { Integer atk_s = char_o.phis_attr.get("strength") + char_o.skl_abl.get("melee"); Integer atk_d = char_o.phis_attr.get("dexterity") + char_o.skl_abl.get("melee"); TextView atk_v = (TextView) findViewById(R.id.atk_melee); atk_v.setText(getResources().getString(R.string.atk_melee) + atk_s + "/" + atk_d); atk_d = char_o.phis_attr.get("dexterity") + char_o.skl_abl.get("firearms"); atk_v = (TextView) findViewById(R.id.atk_range); atk_v.setText(getResources().getString(R.string.atk_range) + atk_d); atk_d = char_o.phis_attr.get("dexterity") + char_o.tal_abl.get("athletics"); atk_v = (TextView) findViewById(R.id.atk_throw); atk_v.setText(getResources().getString(R.string.atk_throw) + atk_d); atk_d = char_o.phis_attr.get("dexterity"); if (char_o.phis_attr.get("dexterity") > char_o.men_attr.get("wits")) { atk_d = char_o.men_attr.get("wits"); } atk_v = (TextView) findViewById(R.id.def); atk_v.setText(getResources().getString(R.string.def) + atk_d); atk_d = char_o.phis_attr.get("dexterity") + char_o.men_attr.get("wits"); atk_v = (TextView) findViewById(R.id.init); atk_v.setText(getResources().getString(R.string.init) + atk_d); } else if (name.equals("wits")) { Integer atk_d = char_o.phis_attr.get("dexterity"); if (char_o.phis_attr.get("dexterity") > char_o.men_attr.get("wits")) { atk_d = char_o.men_attr.get("wits"); } TextView atk_v = (TextView) findViewById(R.id.def); atk_v.setText(getResources().getString(R.string.def) + atk_d); atk_d = char_o.phis_attr.get("dexterity") + char_o.men_attr.get("wits"); atk_v = (TextView) findViewById(R.id.init); atk_v.setText(getResources().getString(R.string.init) + atk_d); } } else if ( group.equals("abl") ) { if (name.equals("brawl")) { Integer atk = char_o.phis_attr.get("strength") + char_o.tal_abl.get("brawl"); TextView atk_v = (TextView) findViewById(R.id.atk_hands); atk_v.setText(getResources().getString(R.string.atk_hands) + atk); } else if (name.equals("melee")) { Integer atk_s = char_o.phis_attr.get("strength") + char_o.skl_abl.get("melee"); Integer atk_d = char_o.phis_attr.get("dexterity") + char_o.skl_abl.get("melee"); TextView atk_v = (TextView) findViewById(R.id.atk_melee); atk_v.setText(getResources().getString(R.string.atk_melee) + atk_s + "/" + atk_d); } else if (name.equals("firearms")) { Integer atk_d = char_o.phis_attr.get("dexterity") + char_o.skl_abl.get("firearms"); TextView atk_v = (TextView) findViewById(R.id.atk_range); atk_v.setText(getResources().getString(R.string.atk_range) + atk_d); } else if (name.equals("athletics")) { Integer atk_d = char_o.phis_attr.get("dexterity") + char_o.tal_abl.get("athletics"); TextView atk_v = (TextView) findViewById(R.id.atk_throw); atk_v.setText(getResources().getString(R.string.atk_throw) + atk_d); } } } private void set_range( String group, String name, Integer number ) { for ( Integer i = 1; i <= number; i++ ){ mark_dots( group, name, i, R.drawable.ic_fiber_manual_record_black_24dp ); } } private void unset_upper_range( String group, String name, Integer number ) { Integer limit = 5; if ( group.equals("button") ) { limit = 10; } for ( Integer i = (number + 1); i <= limit; i++ ){ mark_dots( group, name, i, R.drawable.ic_radio_button_unchecked_black_24dp ); } } private void mark_dots( String group, String name, Integer number, int pic ) { if ( number > 0 ) { String id_ref = String.format(Locale.getDefault(), "rb_%s_%s%d", group, name, number); int resID = getResources().getIdentifier(id_ref, "id", getPackageName()); ImageView img = (ImageView) findViewById(resID); assert img != null; img.setImageResource(pic); } } private void fix_gods_list( String algmnt ) { switch (algmnt) { case "Законопослушный-Добрый": adapter_gd = ArrayAdapter.createFromResource(this, R.array.gods_lg_array, android.R.layout.simple_spinner_item); break; case "Нейтральный-Добрый": adapter_gd = ArrayAdapter.createFromResource(this, R.array.gods_ng_array, android.R.layout.simple_spinner_item); break; case "Хаотичный-Добрый": adapter_gd = ArrayAdapter.createFromResource(this, R.array.gods_cg_array, android.R.layout.simple_spinner_item); break; case "Законопослушный-Нейтральный": adapter_gd = ArrayAdapter.createFromResource(this, R.array.gods_ln_array, android.R.layout.simple_spinner_item); break; case "Нейтральный": adapter_gd = ArrayAdapter.createFromResource(this, R.array.gods_nn_array, android.R.layout.simple_spinner_item); break; case "Хаотичный-Нейтральный": adapter_gd = ArrayAdapter.createFromResource(this, R.array.gods_cn_array, android.R.layout.simple_spinner_item); break; case "Законопослушный-Злой": adapter_gd = ArrayAdapter.createFromResource(this, R.array.gods_le_array, android.R.layout.simple_spinner_item); break; case "Нейтральный-Злой": adapter_gd = ArrayAdapter.createFromResource(this, R.array.gods_ne_array, android.R.layout.simple_spinner_item); break; case "Хаотичный-Злой": adapter_gd = ArrayAdapter.createFromResource(this, R.array.gods_ce_array, android.R.layout.simple_spinner_item); break; } if ( spinner_gd.getAdapter() == null ) { spinner_gd.setAdapter(adapter_gd); } ArrayList<String> new_list = new ArrayList<>(); for (int i = 0; i < adapter_gd.getCount(); i++) { new_list.add(adapter_gd.getItem(i).toString()); } ArrayList<String> old_list = new ArrayList<>(); for (int i = 0; i < spinner_gd.getAdapter().getCount(); i++) { old_list.add(spinner_gd.getAdapter().getItem(i).toString()); } if (!old_list.toString().equals(new_list.toString())) { spinner_gd.setAdapter(adapter_gd); } } private void show_god_disciplines( String god_name ) { for (String d: discs) { if ( d.equals("alchemistry") ) { d = "dis_alchemistry"; } int resID = getResources().getIdentifier(d, "id", getPackageName()); View disc = findViewById(resID); disc.setVisibility(View.GONE); } g_discs.clear(); switch (god_name) { case "Акади": g_discs.add("celerity"); g_discs.add("conveyance"); g_discs.add("weathercraft"); break; case "Грумбар": g_discs.add("fortitude"); g_discs.add("temporis"); break; case "Истишия": g_discs.add("potence"); g_discs.add("alchemistry"); g_discs.add("melpominee"); break; case "Келемвор": g_discs.add("conveyance"); g_discs.add("auspex"); g_discs.add("temporis"); break; case "Коссут": g_discs.add("potence"); g_discs.add("hellfire"); g_discs.add("dominate"); break; case "Латандер": g_discs.add("healing"); g_discs.add("potence"); g_discs.add("presence"); break; case "Мистра": g_discs.add("hellfire"); g_discs.add("alchemistry"); g_discs.add("enchantment"); break; case "Огма": g_discs.add("conveyance"); g_discs.add("alchemistry"); g_discs.add("enchantment"); break; case "Сайрик": g_discs.add("dominate"); g_discs.add("chimerstry"); g_discs.add("dementation"); break; case "Суне": g_discs.add("presence"); g_discs.add("healing"); g_discs.add("celerity"); break; case "Сильванус": g_discs.add("animalism"); g_discs.add("protean"); g_discs.add("serpentis"); break; case "Талос": g_discs.add("hellfire"); g_discs.add("weathercraft"); g_discs.add("dominate"); break; case "Темпус": g_discs.add("potence"); g_discs.add("healing"); g_discs.add("fortitude"); break; case "Тир": g_discs.add("auspex"); g_discs.add("fortitude"); break; case "Чонти": g_discs.add("weathercraft"); g_discs.add("healing"); g_discs.add("animalism"); break; case "Шар": g_discs.add("dominate"); g_discs.add("obtenebration"); g_discs.add("obfuscate"); break; case "Бэйн": g_discs.add("quietus"); g_discs.add("dominate"); g_discs.add("daimoinon"); break; } display_discs(); } private void display_discs () { for( String d: g_discs ) { if ( d.equals("alchemistry") ) { d = "dis_alchemistry"; } int resID = getResources().getIdentifier(d, "id", getPackageName()); View disc = findViewById(resID); disc.setVisibility(View.VISIBLE); } } private void fill_map() { Integer pos; // alignment ArrayAdapter<CharSequence> adapter_al = ArrayAdapter.createFromResource(this, R.array.alignments_array, android.R.layout.simple_spinner_item); adapter_al.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner_al.setAdapter(adapter_al); pos = adapter_al.getPosition( char_o.alignment ); spinner_al.setSelection(pos); // class ArrayAdapter<CharSequence> adapter_cl = ArrayAdapter.createFromResource(this, R.array.classes_array, android.R.layout.simple_spinner_item); adapter_cl.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner_cl.setAdapter(adapter_cl); pos = adapter_cl.getPosition( char_o.class_name ); spinner_cl.setSelection(pos); // god if ( char_o.class_name.equals("Жрец") ) { fix_gods_list(char_o.alignment); pos = adapter_gd.getPosition(char_o.god); spinner_gd.setSelection(pos); } Integer val; // attributes for ( String resource : char_o.phis_attr.keySet() ) { val = char_o.phis_attr.get(resource); set_range( "attr", resource, val ); unset_upper_range( "attr", resource, val ); update_summary( "attr", resource ); } for ( String resource : char_o.soc_attr.keySet() ) { val = char_o.soc_attr.get(resource); set_range( "attr", resource, val ); unset_upper_range( "attr", resource, val ); } for ( String resource : char_o.men_attr.keySet() ) { val = char_o.men_attr.get(resource); set_range( "attr", resource, val ); unset_upper_range( "attr", resource, val ); update_summary( "attr", resource ); } // abilities for ( String resource : char_o.tal_abl.keySet() ) { val = char_o.tal_abl.get(resource); set_range( "abl", resource, val ); unset_upper_range( "abl", resource, val ); update_summary( "abl", resource ); } for ( String resource : char_o.skl_abl.keySet() ) { val = char_o.skl_abl.get(resource); set_range( "abl", resource, val ); unset_upper_range( "abl", resource, val ); update_summary( "abl", resource ); } for ( String resource : char_o.kng_abl.keySet() ) { val = char_o.kng_abl.get(resource); set_range( "abl", resource, val ); unset_upper_range( "abl", resource, val ); } // backgrounds for ( String resource : char_o.bkg.keySet() ) { val = char_o.bkg.get(resource); set_range( "bkg", resource, val ); unset_upper_range( "bkg", resource, val ); } // class features for ( String resource : char_o.sph.keySet() ) { val = char_o.sph.get(resource); set_range( "sph", resource, val ); unset_upper_range( "sph", resource, val ); } for ( String resource : char_o.gft.keySet() ) { val = char_o.gft.get(resource); set_range( "gft", resource, val ); unset_upper_range( "gft", resource, val ); } for ( String resource : char_o.dis.keySet() ) { val = char_o.dis.get(resource); set_range( "dis", resource, val ); unset_upper_range( "dis", resource, val ); } // special parameters Pattern p = Pattern.compile("perm_(\\p{Lower}+)"); Matcher m; String res; for ( String resource : char_o.sp_resources.keySet() ) { val = char_o.sp_resources.get(resource); m = p.matcher(resource); if (m.find()) { res = m.group(1); set_range( "button", res, val ); unset_upper_range( "button", res, val ); } else { set_free_range( resource, val ); unset_free_upper_range( resource, val ); } } lock_unlock_names(); set_health_pen(); } private void lock_unlock_names() { if ( char_o.Generated == 1 ) { spinner_al.setVisibility(View.GONE); spinner_cl.setVisibility(View.GONE); spinner_gd.setVisibility(View.GONE); TextView al = (TextView) findViewById(R.id.txt_charlist_alignment); al.setText(String.format(Locale.getDefault(), "Мировоззрение: %s", char_o.alignment)); al.setVisibility(View.VISIBLE); TextView cl = (TextView) findViewById(R.id.txt_charlist_class); cl.setText(String.format(Locale.getDefault(), "Класс: %s", char_o.class_name)); cl.setVisibility(View.VISIBLE); if (char_o.class_name.equals("Жрец")) { TextView gd = (TextView) findViewById(R.id.txt_charlist_gods); gd.setText(String.format(Locale.getDefault(), "Бог: %s", char_o.god)); gd.setVisibility(View.VISIBLE); } } else { spinner_al.setVisibility(View.VISIBLE); spinner_cl.setVisibility(View.VISIBLE); spinner_gd.setVisibility(View.VISIBLE); TextView al = (TextView) findViewById(R.id.txt_charlist_alignment); al.setVisibility(View.GONE); TextView cl = (TextView) findViewById(R.id.txt_charlist_class); cl.setVisibility(View.GONE); if (char_o.class_name.equals("Жрец")) { TextView gd = (TextView) findViewById(R.id.txt_charlist_gods); gd.setVisibility(View.GONE); } } } private void mark_checkboxes( String name, int id, int pic ) { String id_ref = String.format(Locale.getDefault(), "image_%s%d", name, id); int resID = getResources().getIdentifier(id_ref, "id", getPackageName()); ImageView img = (ImageView) findViewById(resID); assert img != null; img.setImageResource(pic); } private void set_free_range( String name, int id ) { while ( id > 0 ) { mark_checkboxes( name, id, R.drawable.ic_check_box_black_24dp ); id } } private void unset_free_upper_range( String name, int id ) { Integer limit = 10; if ( name.equals("health") ) { limit = 14; } id++; while( id <= limit ) { mark_checkboxes( name, id, R.drawable.ic_crop_din_black_24dp ); id++; } } @SuppressWarnings("unused") public void plus_button(View view) { String IdAsString = view.getResources().getResourceName(view.getId()); Pattern p = Pattern.compile("/(\\p{Lower}+)_"); Matcher m = p.matcher(IdAsString); String special_resource; if( m.find() ){ special_resource = m.group(1); } else { throw new RuntimeException( "Can't fine resource in " + IdAsString ); } Integer sp_value = char_o.sp_resources.get( special_resource ); if ( special_resource.equals("health") ) { sp_value++; if ( sp_value > 14 ) { return ; } char_o.sp_resources.put(special_resource, sp_value); mark_checkboxes( special_resource, sp_value, R.drawable.ic_check_box_black_24dp ); set_health_pen(); return ; } else if ( special_resource.equals("rage") ) { sp_value += 1; char_o.sp_resources.put(special_resource, sp_value); mark_checkboxes( special_resource, sp_value, R.drawable.ic_check_box_black_24dp ); return ; } Integer limit = char_o.sp_resources.get( "perm_" + special_resource ); if ( (special_resource.equals("faith")) || (sp_value < limit) ) { sp_value++; char_o.sp_resources.put(special_resource, sp_value); mark_checkboxes( special_resource, sp_value, R.drawable.ic_check_box_black_24dp ); } } @SuppressWarnings("unused") public void minus_button(View view) { String IdAsString = view.getResources().getResourceName(view.getId()); Pattern p = Pattern.compile("/(\\p{Lower}+)_"); Matcher m = p.matcher(IdAsString); String special_resource; if( m.find() ){ special_resource = m.group(1); } else { throw new RuntimeException( "Can't fine resource in " + IdAsString ); } Integer sp_value = char_o.sp_resources.get( special_resource ); if ( special_resource.equals("health") ) { if ( sp_value == 0 ) { return ; } mark_checkboxes( special_resource, sp_value, R.drawable.ic_crop_din_black_24dp ); sp_value char_o.sp_resources.put(special_resource, sp_value); set_health_pen(); return ; } if ( sp_value > 0 ) { mark_checkboxes( special_resource, sp_value, R.drawable.ic_crop_din_black_24dp ); sp_value char_o.sp_resources.put(special_resource, sp_value); } } private void set_health_pen() { TextView t = (TextView)findViewById(R.id.special_limit_health); assert t != null; t.setTextColor( Color.RED ); Integer pen = char_o.get_health_pen(); switch (pen) { case 0: t.setTextColor(Color.parseColor("#33b5e5")); t.setText(R.string.char_0); break; case 1: t.setText(R.string.char_m_1); break; case 2: t.setText(R.string.char_m_2); break; case 5: t.setText(R.string.char_m_5); break; case 10: t.setText(R.string.char_m_10); break; } } @SuppressWarnings("unused") public void reset_button(View view) { String IdAsString = view.getResources().getResourceName(view.getId()); Pattern p = Pattern.compile("/(\\p{Lower}+)_"); Matcher m = p.matcher(IdAsString); String special_resource; if( m.find() ) { special_resource = m.group(1); } else { throw new RuntimeException( "Can't fine resource in " + IdAsString ); } reset_parameter(special_resource); if ( special_resource.equals("health") ) { TextView t = (TextView)findViewById(R.id.special_limit_health); assert t != null; t.setTextColor( Color.parseColor("#33b5e5") ); t.setText( "0" ); } } private void reset_parameter ( String name ) { Integer sp_value = char_o.sp_resources.get(name); switch (name) { case "health": while (sp_value > 0) { mark_checkboxes(name, sp_value, R.drawable.ic_crop_din_black_24dp); sp_value } char_o.sp_resources.put(name, 0); break; case "rage": for (Integer i = 1; i <= 10; i++) { mark_checkboxes(name, i, R.drawable.ic_crop_din_black_24dp); } if (char_o.class_name.equals("Воин")) { char_o.sp_resources.put(name, 1); mark_checkboxes(name, 1, R.drawable.ic_check_box_black_24dp); } break; default: Integer perm_val = char_o.sp_resources.get("perm_" + name); char_o.sp_resources.put(name, perm_val); for (Integer i = 1; i <= perm_val; i++) { mark_checkboxes(name, i, R.drawable.ic_check_box_black_24dp); } perm_val++; for (Integer i = perm_val; i <= 10; i++) { mark_checkboxes(name, i, R.drawable.ic_crop_din_black_24dp); } break; } } @SuppressWarnings("unused") public void onCheckboxClicked_sp_resources(View view) { boolean checked = ((CheckBox) view).isChecked(); String IdAsString = view.getResources().getResourceName(view.getId()); Pattern p = Pattern.compile("_(\\p{Lower}+)$"); Matcher m = p.matcher(IdAsString); String special_resource; if( m.find() ){ special_resource = m.group(1); } else { throw new RuntimeException( "Can't find resource name in " + IdAsString ); } String id_ref = String.format(Locale.getDefault(), "sp_%s", special_resource); int resID = getResources().getIdentifier(id_ref, "id", getPackageName()); View sp_view = findViewById(resID); if( checked ){ assert sp_view != null; sp_view.setVisibility(View.GONE); } else { assert sp_view != null; sp_view.setVisibility(View.VISIBLE); } } @SuppressWarnings({"UnusedParameters", "unused"}) public void save_char(MenuItem item) { Context context = this; char_o.flush( context ); } @SuppressWarnings({"UnusedParameters", "unused"}) public void run_load_screen(MenuItem item) { Intent intent = new Intent(this, load_char.class); startActivity(intent); finish(); } @SuppressWarnings({"UnusedParameters", "unused"}) public void new_char(MenuItem item) { Intent intent = new Intent(this, enter_name.class); startActivity(intent); finish(); } @SuppressWarnings("unused") public void run_hide_zero(MenuItem item) { item.setVisible(false); MenuItem show_params = menu_bar.findItem(R.id.action_show_zero); show_params.setVisible(true); for ( String param : char_o.tal_abl.keySet() ) { if ( param.equals("gen_points") ) { continue; } if ( char_o.tal_abl.get(param) == 0 ) { display_param(param, View.GONE); } } for ( String param : char_o.skl_abl.keySet() ) { if ( param.equals("gen_points") ) { continue; } if ( char_o.skl_abl.get(param) == 0 ) { display_param(param, View.GONE); } } for ( String param : char_o.kng_abl.keySet() ) { if ( param.equals("gen_points") ) { continue; } if ( char_o.kng_abl.get(param) == 0 ) { display_param(param, View.GONE); } } for ( String param : char_o.bkg.keySet() ) { if ( char_o.bkg.get(param) == 0 ) { display_param(param, View.GONE); } } if ( char_o.class_name.equals("Маг") ) { for (String param : char_o.sph.keySet()) { if (char_o.sph.get(param) == 0) { display_param(param, View.GONE); } } } if ( char_o.class_name.equals("Жрец") ) { for (String param : g_discs) { if (char_o.dis.get(param) == 0) { if ( param.equals("alchemistry") ) { param = "dis_alchemistry"; } display_param(param, View.GONE); } } } if ( char_o.class_name.equals("Воин") ) { for (String param : char_o.gft.keySet()) { if (char_o.gft.get(param) == 0) { display_param(param, View.GONE); } } } } private void display_param( String param, Integer vis ) { int resID = getResources().getIdentifier(param, "id", getPackageName()); View w_param = findViewById(resID); w_param.setVisibility(vis); } @SuppressWarnings("unused") public void run_show_zero(MenuItem item) { item.setVisible(false); MenuItem hide_params = menu_bar.findItem(R.id.action_hide_zero); hide_params.setVisible(true); for ( String param : char_o.tal_abl.keySet() ) { if ( param.equals("gen_points") ) { continue; } if ( param.equals("enlightenment") && !char_o.class_name.equals("Маг") ){ continue; } if ( char_o.tal_abl.get(param) == 0 ) { display_param(param, View.VISIBLE); } } for ( String param : char_o.skl_abl.keySet() ) { if ( param.equals("gen_points") ) { continue; } if ( param.equals("concentration") && !char_o.class_name.equals("Маг") ){ continue; } if ( char_o.skl_abl.get(param) == 0 ) { display_param(param, View.VISIBLE); } } for ( String param : char_o.kng_abl.keySet() ) { if ( param.equals("gen_points") ) { continue; } if ( char_o.kng_abl.get(param) == 0 ) { display_param(param, View.VISIBLE); } } for ( String param : char_o.bkg.keySet() ) { if ( char_o.bkg.get(param) == 0 ) { display_param(param, View.VISIBLE); } } if ( char_o.class_name.equals("Маг") ) { for (String param : char_o.sph.keySet()) { if (char_o.sph.get(param) == 0) { display_param(param, View.VISIBLE); } } } if ( char_o.class_name.equals("Жрец") ) { display_discs(); } if ( char_o.class_name.equals("Воин") ) { for (String param : char_o.gft.keySet()) { if (char_o.gft.get(param) == 0) { display_param(param, View.VISIBLE); } } } } }
package dyvil.tools.compiler.transform; import dyvil.tools.parsing.lexer.Tokens; public class DyvilKeywords { public static final int ABSTRACT = Tokens.KEYWORD | 0x00010000; public static final int AS = Tokens.KEYWORD | 0x00020000; public static final int BREAK = Tokens.KEYWORD | 0x00030000; public static final int CASE = Tokens.KEYWORD | 0x00040000; public static final int CATCH = Tokens.KEYWORD | 0x00050000; public static final int CLASS = Tokens.KEYWORD | 0x00060000; public static final int CONST = Tokens.KEYWORD | 0x00070000; public static final int CONTINUE = Tokens.KEYWORD | 0x00080000; public static final int DO = Tokens.KEYWORD | 0x00090000; public static final int ELSE = Tokens.KEYWORD | 0x000A0000; public static final int ENUM = Tokens.KEYWORD | 0x000B0000; public static final int EXTENDS = Tokens.KEYWORD | 0x000C0000; public static final int EXTENSION = Tokens.KEYWORD | 0x000D0000; public static final int FALSE = Tokens.KEYWORD | 0x000E0000; public static final int FINAL = Tokens.KEYWORD | 0x000F0000; public static final int FINALLY = Tokens.KEYWORD | 0x00100000; public static final int FOR = Tokens.KEYWORD | 0x00110000; public static final int FUNCTIONAL = Tokens.KEYWORD | 0x00120000; public static final int GOTO = Tokens.KEYWORD | 0x00130000; public static final int HEADER = Tokens.KEYWORD | 0x00140000; public static final int IF = Tokens.KEYWORD | 0x00150000; public static final int IMPLEMENTS = Tokens.KEYWORD | 0x00160000; public static final int IMPLICIT = Tokens.KEYWORD | 0x00170000; public static final int IMPORT = Tokens.KEYWORD | 0x00180000; public static final int INCLUDE = Tokens.KEYWORD | 0x00190000; public static final int INLINE = Tokens.KEYWORD | 0x001A0000; public static final int INFIX = Tokens.KEYWORD | 0x001B0000; public static final int INTERFACE = Tokens.KEYWORD | 0x001C0000; public static final int INTERNAL = Tokens.KEYWORD | 0x001D0000; public static final int IS = Tokens.KEYWORD | 0x001E0000; public static final int LAZY = Tokens.KEYWORD | 0x001F0000; public static final int MACRO = Tokens.KEYWORD | 0x00200000; public static final int MATCH = Tokens.KEYWORD | 0x00210000; public static final int NEW = Tokens.KEYWORD | 0x00220000; public static final int NIL = Tokens.KEYWORD | 0x00230000; public static final int NULL = Tokens.KEYWORD | 0x00240000; public static final int OBJECT = Tokens.KEYWORD | 0x00250000; public static final int OVERRIDE = Tokens.KEYWORD | 0x00260000; public static final int OPERATOR = Tokens.KEYWORD | 0x00270000; public static final int PACKAGE = Tokens.KEYWORD | 0x00280000; public static final int POSTFIX = Tokens.KEYWORD | 0x00290000; public static final int PREFIX = Tokens.KEYWORD | 0x002A0000; public static final int PRIVATE = Tokens.KEYWORD | 0x002B0000; public static final int PROTECTED = Tokens.KEYWORD | 0x002C0000; public static final int PUBLIC = Tokens.KEYWORD | 0x002D0000; public static final int RETURN = Tokens.KEYWORD | 0x002E0000; public static final int SEALED = Tokens.KEYWORD | 0x002F0000; public static final int STATIC = Tokens.KEYWORD | 0x00300000; public static final int SUPER = Tokens.KEYWORD | 0x00310000; public static final int SYNCHRONIZED = Tokens.KEYWORD | 0x00320000; public static final int THIS = Tokens.KEYWORD | 0x00330000; public static final int THROW = Tokens.KEYWORD | 0x00340000; public static final int THROWS = Tokens.KEYWORD | 0x00350000; public static final int TRAIT = Tokens.KEYWORD | 0x00360000; public static final int TRUE = Tokens.KEYWORD | 0x00370000; public static final int TRY = Tokens.KEYWORD | 0x00380000; public static final int TYPE = Tokens.KEYWORD | 0x00390000; public static final int USING = Tokens.KEYWORD | 0x003A0000; public static final int VAR = Tokens.KEYWORD | 0x003B0000; public static final int WHERE = Tokens.KEYWORD | 0x003C0000; public static final int WHILE = Tokens.KEYWORD | 0x003D0000; public static int getKeywordType(String s) { switch (s) { case "abstract": return ABSTRACT; case "as": return AS; case "break": return BREAK; case "case": return CASE; case "catch": return CATCH; case "class": return CLASS; case "const": return CONST; case "continue": return CONTINUE; case "do": return DO; case "else": return ELSE; case "enum": return ENUM; case "extends": return EXTENDS; case "extension": return EXTENSION; case "false": return FALSE; case "final": return FINAL; case "finally": return FINALLY; case "for": return FOR; case "functional": return FUNCTIONAL; case "goto": return GOTO; case "header": return HEADER; case "if": return IF; case "implements": return IMPLEMENTS; case "implicit": return IMPLICIT; case "import": return IMPORT; case "include": return INCLUDE; case "inline": return INLINE; case "infix": return INFIX; case "interface": return INTERFACE; case "internal": return INTERNAL; case "is": return IS; case "lazy": return LAZY; case "macro": return MACRO; case "match": return MATCH; case "new": return NEW; case "nil": return NIL; case "null": return NULL; case "object": return OBJECT; case "operator": return OPERATOR; case "override": return OVERRIDE; case "package": return PACKAGE; case "postfix": return POSTFIX; case "prefix": return PREFIX; case "private": return PRIVATE; case "protected": return PROTECTED; case "public": return PUBLIC; case "return": return RETURN; case "sealed": return SEALED; case "static": return STATIC; case "super": return SUPER; case "synchronized": return SYNCHRONIZED; case "this": return THIS; case "throw": return THROW; case "throws": return THROWS; case "trait": return TRAIT; case "true": return TRUE; case "try": return TRY; case "type": return TYPE; case "using": return USING; case "var": return VAR; case "where": return WHERE; case "while": return WHILE; } return 0; } public static String keywordToString(int type) { switch (type) { case ABSTRACT: return "abstract"; case AS: return "as"; case BREAK: return "break"; case CASE: return "case"; case CATCH: return "catch"; case CLASS: return "class"; case CONST: return "const"; case CONTINUE: return "continue"; case DO: return "do"; case ELSE: return "else"; case ENUM: return "enum"; case EXTENDS: return "extends"; case EXTENSION: return "extension"; case FALSE: return "false"; case FINAL: return "final"; case FINALLY: return "finally"; case FOR: return "for"; case FUNCTIONAL: return "functional"; case GOTO: return "goto"; case HEADER: return "header"; case IF: return "if"; case IMPLEMENTS: return "implements"; case IMPLICIT: return "implicit"; case IMPORT: return "import"; case INCLUDE: return "include"; case INLINE: return "inline"; case INFIX: return "infix"; case INTERFACE: return "interface"; case INTERNAL: return "internal"; case IS: return "is"; case LAZY: return "lazy"; case MACRO: return "macro"; case MATCH: return "match"; case NEW: return "new"; case NIL: return "nil"; case NULL: return "null"; case OBJECT: return "object"; case OPERATOR: return "operator"; case OVERRIDE: return "override"; case PACKAGE: return "package"; case POSTFIX: return "postfix"; case PREFIX: return "prefix"; case PRIVATE: return "private"; case PROTECTED: return "protected"; case PUBLIC: return "public"; case RETURN: return "return"; case SEALED: return "sealed"; case STATIC: return "static"; case SUPER: return "super"; case SYNCHRONIZED: return "synchronized"; case THIS: return "this"; case THROW: return "throw"; case THROWS: return "throws"; case TRAIT: return "trait"; case TRUE: return "true"; case TRY: return "try"; case TYPE: return "type"; case USING: return "using"; case VAR: return "var"; case WHERE: return "where"; case WHILE: return "while"; } return null; } }
package org.voltdb; import java.io.IOException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.nio.ByteBuffer; import java.util.Vector; import org.hsqldb_voltpatches.FunctionForVoltDB; import org.voltcore.logging.VoltLogger; import org.voltcore.utils.CoreUtils; import org.voltdb.catalog.CatalogMap; import org.voltdb.catalog.Function; import org.voltdb.common.Constants; import org.voltdb.types.GeographyPointValue; import org.voltdb.types.GeographyValue; import org.voltdb.types.TimestampType; import org.voltdb.types.VoltDecimalHelper; import org.voltdb.utils.SerializationHelper; import org.voltdb.utils.JavaBuiltInFunctions; import org.voltdb.compiler.statements.CreateFunction; import com.google_voltpatches.common.collect.ImmutableMap; /** * This is the Java class that manages the UDF class instances, and also the invocation logics. */ public class UserDefinedFunctionManager { private static VoltLogger m_logger = new VoltLogger("UDF"); static final String ORGVOLTDB_FUNCCNAME_ERROR_FMT = "VoltDB does not support function classes with package names " + "that are prefixed with \"org.voltdb\". Please use a different " + "package name and retry. The class name was %s."; static final String UNABLETOLOAD_ERROR_FMT = "VoltDB was unable to load a function (%s) which was expected to be " + "in the catalog jarfile and will now exit."; ImmutableMap<Integer, UserDefinedScalarFunctionRunner> m_udfs = ImmutableMap.of(); ImmutableMap<Integer, UserDefinedAggregateFunctionRunner> m_udafs = ImmutableMap.of(); public UserDefinedScalarFunctionRunner getFunctionRunnerById(int functionId) { return m_udfs.get(functionId); } public UserDefinedAggregateFunctionRunner getAggregateFunctionRunnerById(int functionId) { return m_udafs.get(functionId); } // Load all the UDFs recorded in the catalog. Instantiate and register them in the system. public void loadFunctions(CatalogContext catalogContext) { final CatalogMap<Function> catalogFunctions = catalogContext.database.getFunctions(); // Remove obsolete tokens (scalar) for (UserDefinedScalarFunctionRunner runner : m_udfs.values()) { // The function that the current UserDefinedScalarFunctionRunner is referring to // does not exist in the catalog anymore, we need to remove its token. if (catalogFunctions.get(runner.m_functionName) == null) { FunctionForVoltDB.deregisterUserDefinedFunction(runner.m_functionName); } } // Remove obsolete tokens (aggregate) for (UserDefinedAggregateFunctionRunner runner : m_udafs.values()) { // The function that the current UserDefinedAggregateFunctionRunner is referring to // does not exist in the catalog anymore, we need to remove its token. if (catalogFunctions.get(runner.m_functionName) == null) { FunctionForVoltDB.deregisterUserDefinedFunction(runner.m_functionName); } } // Build new UDF runners ImmutableMap.Builder<Integer, UserDefinedScalarFunctionRunner> builder = ImmutableMap.<Integer, UserDefinedScalarFunctionRunner>builder(); ImmutableMap.Builder<Integer, UserDefinedAggregateFunctionRunner> builderAgg = ImmutableMap.<Integer, UserDefinedAggregateFunctionRunner>builder(); for (final Function catalogFunction : catalogFunctions) { final String className = catalogFunction.getClassname(); Class<?> funcClass = null; try { funcClass = catalogContext.classForProcedureOrUDF(className); } catch (final ClassNotFoundException e) { if (className.startsWith("org.voltdb.")) { String msg = String.format(ORGVOLTDB_FUNCCNAME_ERROR_FMT, className); VoltDB.crashLocalVoltDB(msg, false, null); } else { String msg = String.format(UNABLETOLOAD_ERROR_FMT, className); VoltDB.crashLocalVoltDB(msg, false, null); } } Object funcInstance = null; try { funcInstance = funcClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(String.format("Error instantiating function \"%s\"", className), e); } assert(funcInstance != null); if (catalogFunction.getMethodname() == null) { // no_method_here -> aggregate function builderAgg.put(catalogFunction.getFunctionid(), new UserDefinedAggregateFunctionRunner(catalogFunction, funcClass)); } else { // There is a methodName -> scalar function builder.put(catalogFunction.getFunctionid(), new UserDefinedScalarFunctionRunner(catalogFunction, funcInstance)); } } loadBuiltInJavaFunctions(builder); m_udfs = builder.build(); m_udafs = builderAgg.build(); } private void loadBuiltInJavaFunctions(ImmutableMap.Builder<Integer, UserDefinedScalarFunctionRunner> builder) { // define the function objects String[] functionNames = {"format_timestamp"}; for (String functionName : functionNames) { int functionID = FunctionForVoltDB.getFunctionID(functionName); builder.put(functionID, new UserDefinedScalarFunctionRunner(functionName, functionID, functionName, new JavaBuiltInFunctions())); } } public static class UserDefinedFunctionRunner { static final int VAR_LEN_SIZE = Integer.SIZE/8; public static byte[] readVarbinary(ByteBuffer buffer) { // Sanity check the size against the remaining buffer size. if (VAR_LEN_SIZE > buffer.remaining()) { throw new RuntimeException(String.format( "Can't read varbinary size as %d byte integer " + "from buffer with %d bytes remaining.", VAR_LEN_SIZE, buffer.remaining())); } final int len = buffer.getInt(); if (len == VoltTable.NULL_STRING_INDICATOR) { return null; } if (len < 0) { throw new RuntimeException("Invalid object length."); } byte[] data = new byte[len]; buffer.get(data); return data; } public static Object getValueFromBuffer(ByteBuffer buffer, VoltType type) { switch (type) { case TINYINT: return buffer.get(); case SMALLINT: return buffer.getShort(); case INTEGER: return buffer.getInt(); case BIGINT: return buffer.getLong(); case FLOAT: return buffer.getDouble(); case STRING: byte[] stringAsBytes = readVarbinary(buffer); if (stringAsBytes == null) { return null; } return new String(stringAsBytes, VoltTable.ROWDATA_ENCODING); case VARBINARY: return readVarbinary(buffer); case TIMESTAMP: long timestampValue = buffer.getLong(); if (timestampValue == Long.MIN_VALUE) { return null; } return new TimestampType(timestampValue); case DECIMAL: return VoltDecimalHelper.deserializeBigDecimal(buffer); case GEOGRAPHY_POINT: return GeographyPointValue.unflattenFromBuffer(buffer); case GEOGRAPHY: byte[] geographyValueBytes = readVarbinary(buffer); if (geographyValueBytes == null) { return null; } return GeographyValue.unflattenFromBuffer(ByteBuffer.wrap(geographyValueBytes)); default: throw new RuntimeException("Cannot read from VoltDB UDF buffer."); } } public static void writeValueToBuffer(ByteBuffer buffer, VoltType type, Object value) throws IOException { buffer.put(type.getValue()); if (VoltType.isVoltNullValue(value)) { value = type.getNullValue(); if (value == VoltType.NULL_TIMESTAMP) { buffer.putLong(VoltType.NULL_BIGINT); // corresponds to EE value.h isNull() return; } else if (value == VoltType.NULL_STRING_OR_VARBINARY) { buffer.putInt(VoltType.NULL_STRING_LENGTH); return; } else if (value == VoltType.NULL_DECIMAL) { VoltDecimalHelper.serializeNull(buffer); return; } else if (value == VoltType.NULL_POINT) { GeographyPointValue.serializeNull(buffer); return; } else if (value == VoltType.NULL_GEOGRAPHY) { buffer.putInt(VoltType.NULL_STRING_LENGTH); return; } } switch (type) { case TINYINT: buffer.put((Byte)value); break; case SMALLINT: buffer.putShort((Short)value); break; case INTEGER: buffer.putInt((Integer) value); break; case BIGINT: buffer.putLong((Long) value); break; case FLOAT: buffer.putDouble(((Double) value).doubleValue()); break; case STRING: byte[] stringAsBytes = ((String)value).getBytes(Constants.UTF8ENCODING); SerializationHelper.writeVarbinary(stringAsBytes, buffer); break; case VARBINARY: if (value instanceof byte[]) { SerializationHelper.writeVarbinary(((byte[])value), buffer); } else if (value instanceof Byte[]) { SerializationHelper.writeVarbinary(((Byte[])value), buffer); } break; case TIMESTAMP: buffer.putLong(((TimestampType)value).getTime()); break; case DECIMAL: VoltDecimalHelper.serializeBigDecimal((BigDecimal)value, buffer); break; case GEOGRAPHY_POINT: GeographyPointValue geoValue = (GeographyPointValue)value; geoValue.flattenToBuffer(buffer); break; case GEOGRAPHY: GeographyValue gv = (GeographyValue)value; buffer.putInt(gv.getLengthInBytes()); gv.flattenToBuffer(buffer); break; default: throw new RuntimeException("Cannot write to VoltDB UDF buffer."); } } } /** * This class maintains the necessary information for each UDAF including the class instance * and the method ID for the UDAF implementation. We run UDAFs from this runner. * @author russelhu * */ public static class UserDefinedAggregateFunctionRunner extends UserDefinedFunctionRunner { final String m_functionName; final int m_functionId; final String m_className; Method m_startMethod; Method m_assembleMethod; Method m_combineMethod; Method m_endMethod; Class<?> m_funcClass; Method[] m_functionMethods; Vector<Object> m_functionInstances; final VoltType[] m_paramTypes; final boolean[] m_boxUpByteArray; final VoltType m_returnType; final int m_paramCount; public UserDefinedAggregateFunctionRunner(Function catalogFunction, Class<?> funcClass) { this(catalogFunction.getFunctionname(), catalogFunction.getFunctionid(), catalogFunction.getClassname(), funcClass); } public UserDefinedAggregateFunctionRunner(String functionName, int functionId, String className, Class<?> funcClass) { m_functionName = functionName; m_functionId = functionId; m_className = className; m_funcClass = funcClass; initFunctionMethods(); m_functionInstances = new Vector<Object>(); m_startMethod = initFunctionMethod("start"); m_assembleMethod = initFunctionMethod("assemble"); m_combineMethod = initFunctionMethod("combine"); m_endMethod = initFunctionMethod("end"); Class<?>[] paramTypeClasses = m_assembleMethod.getParameterTypes(); m_paramCount = paramTypeClasses.length; m_paramTypes = new VoltType[m_paramCount]; m_boxUpByteArray = new boolean[m_paramCount]; for (int i = 0; i < m_paramCount; i++) { m_paramTypes[i] = VoltType.typeFromClass(paramTypeClasses[i]); m_boxUpByteArray[i] = paramTypeClasses[i] == Byte[].class; } m_returnType = VoltType.typeFromClass(m_endMethod.getReturnType()); m_logger.debug(String.format("The user-defined function manager is defining aggregate function %s (ID = %s)", m_functionName, m_functionId)); // We register the token again when initializing the user-defined function manager because // in a cluster setting the token may only be registered on the node where the CREATE FUNCTION DDL // is executed. We uses a static map in FunctionDescriptor to maintain the token list. FunctionForVoltDB.registerTokenForUDF(m_functionName, m_functionId, m_returnType, m_paramTypes, true); } private void initFunctionMethods() { try { Object functionInstance = m_funcClass.newInstance(); m_functionMethods = functionInstance.getClass().getDeclaredMethods(); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(String.format("Error instantiating function \"%s\"", m_className), e); } } private void addFunctionInstance() { try { Object tempFunctionInstance = m_funcClass.newInstance(); m_functionInstances.add(tempFunctionInstance); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(String.format("Error instantiating function \"%s\"", m_className), e); } } private Method initFunctionMethod(String methodName) { Method temp_method = null; for (final Method m : m_functionMethods) { if (m.getName().equals(methodName)) { if (!Modifier.isPublic(m.getModifiers())) { continue; } if (Modifier.isStatic(m.getModifiers())) { continue; } // The return type of start|assemble|combine function should be void if (!methodName.equals("end")) { if (!m.getReturnType().equals(Void.TYPE)) { continue; } // If the start method has at least one parameter, this is not the start // method we're looking for if (methodName.equals("start") && m.getParameterCount() > 0) { continue; } // We only support one parameter for the assemble method currently. // If we can support more parameters in the future, we need to delete this check if (methodName.equals("assemble")) { // If the number of parameter is not one, this is not a correct assemble method if (m.getParameterCount() != 1) { continue; } // This assemble method has exactly one parameter // However, this parameter's type is not one of the allowed types if (!CreateFunction.isAllowedDataType(m.getParameterTypes()[0])) { continue; } } // The combine method can have one and only one parameter which is the // same type as the current class if (methodName.equals("combine") && m.getParameterCount() > 0) { if (m.getParameterCount() != 1) { continue; } else if (m.getParameterTypes()[0] != m_funcClass) { continue; } } } // However, the return type for the end function cannot be void else { if (m.getReturnType().equals(Void.TYPE)) { continue; } // If the end method has at least one parameter, this is not the end // method we're looking for if (m.getParameterCount() > 0 || !CreateFunction.isAllowedDataType(m.getReturnType())) { continue; } } temp_method = m; break; } } if (temp_method == null) { throw new RuntimeException( String.format("Error loading function %s: cannot find the %s() method.", m_functionName, methodName)); } else { return temp_method; } } public void start() throws Throwable { addFunctionInstance(); m_startMethod.invoke(m_functionInstances.lastElement()); } public void assemble(ByteBuffer udfBuffer, int udafIndex) throws Throwable { Object[] paramsIn = new Object[m_paramCount]; for (int i = 0; i < m_paramCount; i++) { paramsIn[i] = getValueFromBuffer(udfBuffer, m_paramTypes[i]); if (m_boxUpByteArray[i]) { paramsIn[i] = SerializationHelper.boxUpByteArray((byte[])paramsIn[i]); } } m_assembleMethod.invoke(m_functionInstances.get(udafIndex), paramsIn); } public void combine(Object other, int udafIndex) throws Throwable { m_combineMethod.invoke(m_functionInstances.get(udafIndex), other); } public Object end(int udafIndex) throws Throwable { Object result = m_endMethod.invoke(m_functionInstances.get(udafIndex)); if (udafIndex == m_functionInstances.size() - 1) { m_functionInstances.clear(); } return result; } public VoltType getReturnType() { return m_returnType; } public Object getFunctionInstance(int udafIndex) { return m_functionInstances.get(udafIndex); } public void clearFunctionInstance(int udafIndex) { if (udafIndex == m_functionInstances.size() - 1) { m_functionInstances.clear(); } } } /** * This class maintains the necessary information for each UDF including the class instance and * the method ID for the UDF implementation. We run UDFs from this runner. */ public static class UserDefinedScalarFunctionRunner extends UserDefinedFunctionRunner { final String m_functionName; final int m_functionId; final Object m_functionInstance; Method m_functionMethod; final VoltType[] m_paramTypes; final boolean[] m_boxUpByteArray; final VoltType m_returnType; final int m_paramCount; public UserDefinedScalarFunctionRunner(Function catalogFunction, Object funcInstance) { this(catalogFunction.getFunctionname(), catalogFunction.getFunctionid(), catalogFunction.getMethodname(), funcInstance); } public UserDefinedScalarFunctionRunner(String functionName, int functionId, String methodName, Object funcInstance) { m_functionName = functionName; m_functionId = functionId; m_functionInstance = funcInstance; m_functionMethod = null; initFunctionMethod(methodName); Class<?>[] paramTypeClasses = m_functionMethod.getParameterTypes(); m_paramCount = paramTypeClasses.length; m_paramTypes = new VoltType[m_paramCount]; m_boxUpByteArray = new boolean[m_paramCount]; for (int i = 0; i < m_paramCount; i++) { m_paramTypes[i] = VoltType.typeFromClass(paramTypeClasses[i]); m_boxUpByteArray[i] = paramTypeClasses[i] == Byte[].class; } m_returnType = VoltType.typeFromClass(m_functionMethod.getReturnType()); m_logger.debug(String.format("The user-defined function manager is defining function %s (ID = %s)", m_functionName, m_functionId)); // We register the token again when initializing the user-defined function manager because // in a cluster setting the token may only be registered on the node where the CREATE FUNCTION DDL // is executed. We uses a static map in FunctionDescriptor to maintain the token list. FunctionForVoltDB.registerTokenForUDF(m_functionName, m_functionId, m_returnType, m_paramTypes, false); } private void initFunctionMethod(String methodName) { for (final Method m : m_functionInstance.getClass().getDeclaredMethods()) { if (m.getName().equals(methodName)) { if (! Modifier.isPublic(m.getModifiers())) { continue; } if (Modifier.isStatic(m.getModifiers())) { continue; } if (m.getReturnType().equals(Void.TYPE)) { continue; } m_functionMethod = m; break; } } if (m_functionMethod == null) { throw new RuntimeException( String.format("Error loading function %s: cannot find the %s() method.", m_functionName, methodName)); } } public Object call(ByteBuffer udfBuffer) throws Throwable { Object[] paramsIn = new Object[m_paramCount]; for (int i = 0; i < m_paramCount; i++) { paramsIn[i] = getValueFromBuffer(udfBuffer, m_paramTypes[i]); if (m_boxUpByteArray[i]) { paramsIn[i] = SerializationHelper.boxUpByteArray((byte[])paramsIn[i]); } } return m_functionMethod.invoke(m_functionInstance, paramsIn); } public VoltType getReturnType() { return m_returnType; } public String getFunctionName() { return m_functionName; } } }
package org.voltdb.compiler; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.hsqldb_voltpatches.HSQLInterface; import org.voltcore.logging.VoltLogger; import org.voltdb.ProcInfo; import org.voltdb.ProcInfoData; import org.voltdb.SQLStmt; import org.voltdb.VoltDB; import org.voltdb.VoltProcedure; import org.voltdb.VoltTable; import org.voltdb.VoltType; import org.voltdb.VoltTypeException; import org.voltdb.catalog.Catalog; import org.voltdb.catalog.CatalogMap; import org.voltdb.catalog.Column; import org.voltdb.catalog.Database; import org.voltdb.catalog.Group; import org.voltdb.catalog.GroupRef; import org.voltdb.catalog.ProcParameter; import org.voltdb.catalog.Procedure; import org.voltdb.catalog.Statement; import org.voltdb.catalog.StmtParameter; import org.voltdb.catalog.Table; import org.voltdb.compiler.VoltCompiler.ProcedureDescriptor; import org.voltdb.compiler.VoltCompiler.VoltCompilerException; import org.voltdb.compilereport.ProcedureAnnotation; import org.voltdb.expressions.AbstractExpression; import org.voltdb.expressions.ParameterValueExpression; import org.voltdb.groovy.GroovyCodeBlockConstants; import org.voltdb.groovy.GroovyScriptProcedureDelegate; import org.voltdb.planner.StatementPartitioning; import org.voltdb.types.QueryType; import org.voltdb.utils.CatalogUtil; import org.voltdb.utils.InMemoryJarfile; import com.google_voltpatches.common.collect.ImmutableMap; import groovy.lang.Closure; /** * Compiles stored procedures into a given catalog, * invoking the StatementCompiler as needed. */ public abstract class ProcedureCompiler implements GroovyCodeBlockConstants { static void compile(VoltCompiler compiler, HSQLInterface hsql, DatabaseEstimates estimates, Catalog catalog, Database db, ProcedureDescriptor procedureDescriptor, InMemoryJarfile jarOutput) throws VoltCompiler.VoltCompilerException { assert(compiler != null); assert(hsql != null); assert(estimates != null); if (procedureDescriptor.m_singleStmt == null) { compileJavaProcedure(compiler, hsql, estimates, catalog, db, procedureDescriptor, jarOutput); } else { compileSingleStmtProcedure(compiler, hsql, estimates, catalog, db, procedureDescriptor); } } public static Map<String, SQLStmt> getValidSQLStmts(VoltCompiler compiler, String procName, Class<?> procClass, Object procInstance, boolean withPrivate) throws VoltCompilerException { Map<String, SQLStmt> retval = new HashMap<String, SQLStmt>(); Field[] fields = procClass.getDeclaredFields(); for (Field f : fields) { // skip non SQL fields if (f.getType() != SQLStmt.class) continue; int modifiers = f.getModifiers(); // skip private fields if asked (usually a superclass) if (Modifier.isPrivate(modifiers) && (!withPrivate)) continue; // don't allow non-final SQLStmts if (Modifier.isFinal(modifiers) == false) { String msg = "Procedure " + procName + " contains a non-final SQLStmt field."; if (procClass.getSimpleName().equals(procName) == false) { msg = "Superclass " + procClass.getSimpleName() + " of procedure " + procName + " contains a non-final SQLStmt field."; } if (compiler != null) throw compiler.new VoltCompilerException(msg); else new VoltLogger("HOST").warn(msg); } f.setAccessible(true); SQLStmt stmt = null; try { stmt = (SQLStmt) f.get(procInstance); } // this exception handling here comes from other parts of the code // it's weird, but seems rather hard to hit catch (Exception e) { e.printStackTrace(); continue; } retval.put(f.getName(), stmt); } Class<?> superClass = procClass.getSuperclass(); if (superClass != null) { Map<String, SQLStmt> superStmts = getValidSQLStmts(compiler, procName, superClass, procInstance, false); for (Entry<String, SQLStmt> e : superStmts.entrySet()) { if (retval.containsKey(e.getKey()) == false) retval.put(e.getKey(), e.getValue()); } } return retval; } /** * Return a language visitor that, when run, it returns a map consisting of field names and their * assigned objects * * @param compiler volt compiler instance * @return a {@link Language.Visitor} */ static Language.CheckedExceptionVisitor<Map<String,Object>, Class<?>, VoltCompilerException> procedureIntrospector(final VoltCompiler compiler) { return new Language.CheckedExceptionVisitor<Map<String,Object>, Class<?>, VoltCompilerException>() { @Override public Map<String, Object> visitJava(Class<?> p) throws VoltCompilerException { // get the short name of the class (no package) String shortName = deriveShortProcedureName(p.getName()); VoltProcedure procInstance; try { procInstance = (VoltProcedure)p.newInstance(); } catch (InstantiationException e) { throw new RuntimeException("Error instantiating procedure \"%s\"" + p.getName(), e); } catch (IllegalAccessException e) { throw new RuntimeException("Error instantiating procedure \"%s\"" + p.getName(), e); } Map<String, SQLStmt> stmtMap = getValidSQLStmts(compiler, p.getSimpleName(), p, procInstance, true); ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder(); builder.putAll(stmtMap); // find the run() method and get the params Method procMethod = null; Method[] methods = p.getDeclaredMethods(); for (final Method m : methods) { String name = m.getName(); if (name.equals("run")) { assert (m.getDeclaringClass() == p); // if not null, then we've got more than one run method if (procMethod != null) { String msg = "Procedure: " + shortName + " has multiple public run(...) methods. "; msg += "Only a single run(...) method is supported."; throw compiler.new VoltCompilerException(msg); } if (Modifier.isPublic(m.getModifiers())) { // found it! procMethod = m; } else { compiler.addWarn("Procedure: " + shortName + " has non-public run(...) method."); } } } if (procMethod == null) { String msg = "Procedure: " + shortName + " has no run(...) method."; throw compiler.new VoltCompilerException(msg); } // check the return type of the run method if ((procMethod.getReturnType() != VoltTable[].class) && (procMethod.getReturnType() != VoltTable.class) && (procMethod.getReturnType() != long.class) && (procMethod.getReturnType() != Long.class)) { String msg = "Procedure: " + shortName + " has run(...) method that doesn't return long, Long, VoltTable or VoltTable[]."; throw compiler.new VoltCompilerException(msg); } builder.put("@run",procMethod); return builder.build(); } @Override public Map<String,Object> visitGroovy(Class<?> p) throws VoltCompilerException { GroovyScriptProcedureDelegate scripDelegate; try { scripDelegate = new GroovyScriptProcedureDelegate(p); } catch (GroovyScriptProcedureDelegate.SetupException tupex) { throw compiler.new VoltCompilerException(tupex.getMessage()); } return scripDelegate.getIntrospectedFields(); } }; }; final static Language.Visitor<Class<?>[], Map<String,Object>> procedureEntryPointParametersTypeExtractor = new Language.SimpleVisitor<Class<?>[], Map<String,Object>>() { @Override public Class<?>[] visitJava(Map<String, Object> p) { Method procMethod = (Method)p.get("@run"); return procMethod.getParameterTypes(); } @Override public Class<?>[] visitGroovy(Map<String, Object> p) { @SuppressWarnings("unchecked") Closure<Object> transactOn = (Closure<Object>)p.get(GVY_PROCEDURE_ENTRY_CLOSURE); // closure with no parameters has an object as the default parameter Class<?> [] parameterTypes = transactOn.getParameterTypes(); if ( parameterTypes.length == 1 && parameterTypes[0] == Object.class) { return new Class<?>[0]; } return transactOn.getParameterTypes(); } }; /** * get the short name of the class (no package) * @param className fully qualified (or not) class name * @return short name of the class (no package) */ static String deriveShortProcedureName( String className) { if( className == null || className.trim().isEmpty()) { return null; } String[] parts = className.split("\\."); String shortName = parts[parts.length - 1]; return shortName; } static void compileJavaProcedure(VoltCompiler compiler, HSQLInterface hsql, DatabaseEstimates estimates, Catalog catalog, Database db, ProcedureDescriptor procedureDescriptor, InMemoryJarfile jarOutput) throws VoltCompiler.VoltCompilerException { final String className = procedureDescriptor.m_className; final Language lang = procedureDescriptor.m_language; // Load the class given the class name Class<?> procClass = procedureDescriptor.m_class; // get the short name of the class (no package) String shortName = deriveShortProcedureName(className); // add an entry to the catalog final Procedure procedure = db.getProcedures().add(shortName); for (String groupName : procedureDescriptor.m_authGroups) { final Group group = db.getGroups().get(groupName); if (group == null) { throw compiler.new VoltCompilerException("Procedure " + className + " allows access by a role " + groupName + " that does not exist"); } final GroupRef groupRef = procedure.getAuthgroups().add(groupName); groupRef.setGroup(group); } procedure.setClassname(className); // sysprocs don't use the procedure compiler procedure.setSystemproc(false); procedure.setDefaultproc(procedureDescriptor.m_builtInStmt); procedure.setHasjava(true); procedure.setLanguage(lang.name()); ProcedureAnnotation pa = (ProcedureAnnotation) procedure.getAnnotation(); if (pa == null) { pa = new ProcedureAnnotation(); procedure.setAnnotation(pa); } if (procedureDescriptor.m_scriptImpl != null) { // This is a Groovy or other Java derived procedure and we need to add an annotation with // the script to the Procedure element in the Catalog pa.scriptImpl = procedureDescriptor.m_scriptImpl; } // get the annotation // first try to get one that has been passed from the compiler ProcInfoData info = compiler.getProcInfoOverride(shortName); // check if partition info was set in ddl ProcInfoData ddlInfo = null; if (procedureDescriptor.m_partitionString != null && ! procedureDescriptor.m_partitionString.trim().isEmpty()) { ddlInfo = new ProcInfoData(); ddlInfo.partitionInfo = procedureDescriptor.m_partitionString; ddlInfo.singlePartition = true; } // then check for the usual one in the class itself // and create a ProcInfo.Data instance for it if (info == null) { info = new ProcInfoData(); ProcInfo annotationInfo = procClass.getAnnotation(ProcInfo.class); // error out if partition info is present in both ddl and annotation if (annotationInfo != null) { if (ddlInfo != null) { String msg = "Procedure: " + shortName + " has partition properties defined both in "; msg += "class \"" + className + "\" and in the schema defintion file(s)"; throw compiler.new VoltCompilerException(msg); } // Prevent AutoGenerated DDL from including PARTITION PROCEDURE for this procedure. pa.classAnnotated = true; info.partitionInfo = annotationInfo.partitionInfo(); info.singlePartition = annotationInfo.singlePartition(); } else if (ddlInfo != null) { info = ddlInfo; } } else { pa.classAnnotated = true; } assert(info != null); // make sure multi-partition implies no partitoning info if (info.singlePartition == false) { if ((info.partitionInfo != null) && (info.partitionInfo.length() > 0)) { String msg = "Procedure: " + shortName + " is annotated as multi-partition"; msg += " but partitionInfo has non-empty value: \"" + info.partitionInfo + "\""; throw compiler.new VoltCompilerException(msg); } } // track if there are any writer statements and/or sequential scans and/or an overlooked common partitioning parameter boolean procHasWriteStmts = false; boolean procHasSeqScans = false; // procWantsCommonPartitioning == true but commonPartitionExpression == null signifies a proc // for which the planner was requested to attempt to find an SP plan, but that was not possible // -- it had a replicated write or it had one or more partitioned reads that were not all // filtered by the same partition key value -- so it was planned as an MP proc. boolean procWantsCommonPartitioning = true; AbstractExpression commonPartitionExpression = null; String exampleSPstatement = null; Object exampleSPvalue = null; // iterate through the fields and get valid sql statements Map<String, Object> fields = lang.accept(procedureIntrospector(compiler), procClass); // determine if proc is read or read-write by checking if the proc contains any write sql stmts boolean readWrite = false; for (Object field : fields.values()) { if (!(field instanceof SQLStmt)) continue; SQLStmt stmt = (SQLStmt)field; QueryType qtype = QueryType.getFromSQL(stmt.getText()); if (!qtype.isReadOnly()) { readWrite = true; break; } } // default to FASTER determinism mode, which may favor non-deterministic plans // but if it's a read-write proc, use a SAFER planning mode wrt determinism. final DeterminismMode detMode = readWrite ? DeterminismMode.SAFER : DeterminismMode.FASTER; for (Entry<String, Object> entry : fields.entrySet()) { if (!(entry.getValue() instanceof SQLStmt)) continue; String stmtName = entry.getKey(); SQLStmt stmt = (SQLStmt)entry.getValue(); // add the statement to the catalog Statement catalogStmt = procedure.getStatements().add(stmtName); // compile the statement StatementPartitioning partitioning = info.singlePartition ? StatementPartitioning.forceSP() : StatementPartitioning.forceMP(); boolean cacheHit = StatementCompiler.compileFromSqlTextAndUpdateCatalog(compiler, hsql, catalog, db, estimates, catalogStmt, stmt.getText(), stmt.getJoinOrder(), detMode, partitioning); // if this was a cache hit or specified single, don't worry about figuring out more partitioning if (partitioning.wasSpecifiedAsSingle() || cacheHit) { procWantsCommonPartitioning = false; // Don't try to infer what's already been asserted. // The planner does not currently attempt to second-guess a plan declared as single-partition, maybe some day. // In theory, the PartitioningForStatement would confirm the use of (only) a parameter as a partition key -- // or if the partition key was determined to be some other constant (expression?) it might display an informational // message that the passed parameter is assumed to be equal to the hard-coded partition key constant (expression). // Validate any inferred statement partitioning given the statement's possible usage, until a contradiction is found. } else if (procWantsCommonPartitioning) { // Only consider statements that are capable of running SP with a partitioning parameter that does not seem to // conflict with the partitioning of prior statements. if (partitioning.getCountOfIndependentlyPartitionedTables() == 1) { AbstractExpression statementPartitionExpression = partitioning.singlePartitioningExpressionForReport(); if (statementPartitionExpression != null) { if (commonPartitionExpression == null) { commonPartitionExpression = statementPartitionExpression; exampleSPstatement = stmt.getText(); exampleSPvalue = partitioning.getInferredPartitioningValue(); } else if (commonPartitionExpression.equals(statementPartitionExpression) || (statementPartitionExpression instanceof ParameterValueExpression && commonPartitionExpression instanceof ParameterValueExpression)) { // Any constant used for partitioning would have to be the same for all statements, but // any statement parameter used for partitioning MIGHT come from the same proc parameter as // any other statement's parameter used for partitioning. } else { procWantsCommonPartitioning = false; // appears to be different partitioning for different statements } } else { // There is a statement with a partitioned table whose partitioning column is // not equality filtered with a constant or param. Abandon all hope. procWantsCommonPartitioning = false; } // Usually, replicated-only statements in a mix with others have no effect on the MP/SP decision } else if (partitioning.getCountOfPartitionedTables() == 0) { // but SP is strictly forbidden for DML, to maintain the consistency of the replicated data. if (partitioning.getIsReplicatedTableDML()) { procWantsCommonPartitioning = false; } } else { // There is a statement with a partitioned table whose partitioning column is // not equality filtered with a constant or param. Abandon all hope. procWantsCommonPartitioning = false; } } // if a single stmt is not read only, then the proc is not read only if (catalogStmt.getReadonly() == false) { procHasWriteStmts = true; } if (catalogStmt.getSeqscancount() > 0) { procHasSeqScans = true; } } // MIGHT the planner have uncovered an overlooked opportunity to run all statements SP? if (procWantsCommonPartitioning && (commonPartitionExpression != null)) { String msg = null; if (commonPartitionExpression instanceof ParameterValueExpression) { msg = "This procedure might benefit from an @ProcInfo annotation designating parameter " + ((ParameterValueExpression) commonPartitionExpression).getParameterIndex() + " of statement '" + exampleSPstatement + "'"; } else { String valueDescription = null; if (exampleSPvalue == null) { // Statements partitioned on a runtime constant. This is likely to be cryptic, but hopefully gets the idea across. valueDescription = "of " + commonPartitionExpression.explain(""); } else { valueDescription = exampleSPvalue.toString(); // A simple constant value COULD have been a parameter. } msg = "This procedure might benefit from an @ProcInfo annotation referencing an added parameter passed the value " + valueDescription; } compiler.addInfo(msg); } // set the read onlyness of a proc procedure.setReadonly(procHasWriteStmts == false); procedure.setHasseqscans(procHasSeqScans); checkForDeterminismWarnings(compiler, shortName, procedure, procHasWriteStmts); // set procedure parameter types CatalogMap<ProcParameter> params = procedure.getParameters(); Class<?>[] paramTypes = lang.accept(procedureEntryPointParametersTypeExtractor, fields); for (int i = 0; i < paramTypes.length; i++) { Class<?> cls = paramTypes[i]; ProcParameter param = params.add(String.valueOf(i)); param.setIndex(i); // handle the case where the param is an array if (cls.isArray()) { param.setIsarray(true); cls = cls.getComponentType(); } else param.setIsarray(false); // boxed types are not supported parameters at this time if ((cls == Long.class) || (cls == Integer.class) || (cls == Short.class) || (cls == Byte.class) || (cls == Double.class) || (cls == Character.class) || (cls == Boolean.class)) { String msg = "Procedure: " + shortName + " has a parameter with a boxed type: "; msg += cls.getSimpleName(); msg += ". Replace this parameter with the corresponding primitive type and the procedure may compile."; throw compiler.new VoltCompilerException(msg); } else if ((cls == Float.class) || (cls == float.class)) { String msg = "Procedure: " + shortName + " has a parameter with type: "; msg += cls.getSimpleName(); msg += ". Replace this parameter type with double and the procedure may compile."; throw compiler.new VoltCompilerException(msg); } VoltType type; try { type = VoltType.typeFromClass(cls); } catch (VoltTypeException e) { // handle the case where the type is invalid String msg = "Procedure: " + shortName + " has a parameter with invalid type: "; msg += cls.getSimpleName(); throw compiler.new VoltCompilerException(msg); } catch (RuntimeException e) { String msg = "Procedure: " + shortName + " unexpectedly failed a check on a parameter of type: "; msg += cls.getSimpleName(); msg += " with error: "; msg += e.toString(); throw compiler.new VoltCompilerException(msg); } param.setType(type.getValue()); } // parse the procinfo procedure.setSinglepartition(info.singlePartition); if (info.singlePartition) { parsePartitionInfo(compiler, db, procedure, info.partitionInfo); if (procedure.getPartitionparameter() >= paramTypes.length) { String msg = "PartitionInfo parameter not a valid parameter for procedure: " + procedure.getClassname(); throw compiler.new VoltCompilerException(msg); } // check the type of partition parameter meets our high standards Class<?> partitionType = paramTypes[procedure.getPartitionparameter()]; Class<?>[] validPartitionClzzes = { Long.class, Integer.class, Short.class, Byte.class, long.class, int.class, short.class, byte.class, String.class, byte[].class }; boolean found = false; for (Class<?> candidate : validPartitionClzzes) { if (partitionType == candidate) found = true; } if (!found) { String msg = "PartitionInfo parameter must be a String or Number for procedure: " + procedure.getClassname(); throw compiler.new VoltCompilerException(msg); } VoltType columnType = VoltType.get((byte)procedure.getPartitioncolumn().getType()); VoltType paramType = VoltType.typeFromClass(partitionType); if ( ! columnType.canExactlyRepresentAnyValueOf(paramType)) { String msg = "Type mismatch between partition column and partition parameter for procedure " + procedure.getClassname() + " may cause overflow or loss of precision.\nPartition column is type " + columnType + " and partition parameter is type " + paramType; throw compiler.new VoltCompilerException(msg); } else if ( ! paramType.canExactlyRepresentAnyValueOf(columnType)) { String msg = "Type mismatch between partition column and partition parameter for procedure " + procedure.getClassname() + " does not allow the full range of partition key values.\nPartition column is type " + columnType + " and partition parameter is type " + paramType; compiler.addWarn(msg); } } // put the compiled code for this procedure into the jarfile // need to find the outermost ancestor class for the procedure in the event // that it's actually an inner (or inner inner...) class. // addClassToJar recursively adds all the children, which should include this // class Class<?> ancestor = procClass; while (ancestor.getEnclosingClass() != null) { ancestor = ancestor.getEnclosingClass(); } compiler.addClassToJar(jarOutput, ancestor); } private static void checkForDeterminismWarnings(VoltCompiler compiler, String shortName, final Procedure procedure, boolean procHasWriteStmts) { for (Statement catalogStmt : procedure.getStatements()) { if (catalogStmt.getIscontentdeterministic() == false) { String potentialErrMsg = "Procedure " + shortName + " has a statement with a non-deterministic result - statement: \"" + catalogStmt.getSqltext() + "\" , reason: " + catalogStmt.getNondeterminismdetail(); compiler.addWarn(potentialErrMsg); } else if (catalogStmt.getIsorderdeterministic() == false) { String warnMsg; if (procHasWriteStmts) { String rwPotentialErrMsg = "Procedure " + shortName + " is RW and has a statement whose result has a non-deterministic ordering - statement: \"" + catalogStmt.getSqltext() + "\", reason: " + catalogStmt.getNondeterminismdetail(); warnMsg = rwPotentialErrMsg; } else { warnMsg = "Procedure " + shortName + " has a statement with a non-deterministic result - statement: \"" + catalogStmt.getSqltext() + "\", reason: " + catalogStmt.getNondeterminismdetail(); } compiler.addWarn(warnMsg); } } } static void compileSingleStmtProcedure(VoltCompiler compiler, HSQLInterface hsql, DatabaseEstimates estimates, Catalog catalog, Database db, ProcedureDescriptor procedureDescriptor) throws VoltCompiler.VoltCompilerException { final String className = procedureDescriptor.m_className; if (className.indexOf('@') != -1) { throw compiler.new VoltCompilerException("User procedure names can't contain \"@\"."); } // get the short name of the class (no package if a user procedure) // use the Table.<builtin> name (allowing the period) if builtin. String shortName = className; if (procedureDescriptor.m_builtInStmt == false) { String[] parts = className.split("\\."); shortName = parts[parts.length - 1]; } // add an entry to the catalog (using the full className) final Procedure procedure = db.getProcedures().add(shortName); for (String groupName : procedureDescriptor.m_authGroups) { final Group group = db.getGroups().get(groupName); if (group == null) { throw compiler.new VoltCompilerException("Procedure " + className + " allows access by a role " + groupName + " that does not exist"); } final GroupRef groupRef = procedure.getAuthgroups().add(groupName); groupRef.setGroup(group); } procedure.setClassname(className); // sysprocs don't use the procedure compiler procedure.setSystemproc(false); procedure.setDefaultproc(procedureDescriptor.m_builtInStmt); procedure.setHasjava(false); // get the annotation // first try to get one that has been passed from the compiler ProcInfoData info = compiler.getProcInfoOverride(shortName); // then check for the usual one in the class itself // and create a ProcInfo.Data instance for it if (info == null) { info = new ProcInfoData(); if (procedureDescriptor.m_partitionString != null) { info.partitionInfo = procedureDescriptor.m_partitionString; info.singlePartition = true; } } assert(info != null); // ADD THE STATEMENT // add the statement to the catalog Statement catalogStmt = procedure.getStatements().add(VoltDB.ANON_STMT_NAME); // compile the statement StatementPartitioning partitioning = info.singlePartition ? StatementPartitioning.forceSP() : StatementPartitioning.forceMP(); // default to FASTER detmode because stmt procs can't feed read output into writes StatementCompiler.compileFromSqlTextAndUpdateCatalog(compiler, hsql, catalog, db, estimates, catalogStmt, procedureDescriptor.m_singleStmt, procedureDescriptor.m_joinOrder, DeterminismMode.FASTER, partitioning); // if the single stmt is not read only, then the proc is not read only boolean procHasWriteStmts = (catalogStmt.getReadonly() == false); // set the read onlyness of a proc procedure.setReadonly(procHasWriteStmts == false); int seqs = catalogStmt.getSeqscancount(); procedure.setHasseqscans(seqs > 0); // set procedure parameter types CatalogMap<ProcParameter> params = procedure.getParameters(); CatalogMap<StmtParameter> stmtParams = catalogStmt.getParameters(); // set the procedure parameter types from the statement parameter types int paramCount = 0; for (StmtParameter stmtParam : CatalogUtil.getSortedCatalogItems(stmtParams, "index")) { // name each parameter "param1", "param2", etc... ProcParameter procParam = params.add("param" + String.valueOf(paramCount)); procParam.setIndex(stmtParam.getIndex()); procParam.setIsarray(stmtParam.getIsarray()); procParam.setType(stmtParam.getJavatype()); paramCount++; } // parse the procinfo procedure.setSinglepartition(info.singlePartition); if (info.singlePartition) { parsePartitionInfo(compiler, db, procedure, info.partitionInfo); if (procedure.getPartitionparameter() >= params.size()) { String msg = "PartitionInfo parameter not a valid parameter for procedure: " + procedure.getClassname(); throw compiler.new VoltCompilerException(msg); } // TODO: The planner does not currently validate that a single-statement plan declared as single-partition correctly uses // the designated parameter as a partitioning filter, maybe some day. // In theory, the PartitioningForStatement would confirm the use of (only) a parameter as a partition key -- // or if the partition key was determined to be some other hard-coded constant (expression?) it might display a warning // message that the passed parameter is assumed to be equal to that constant (expression). } else { if (partitioning.getCountOfIndependentlyPartitionedTables() == 1) { AbstractExpression statementPartitionExpression = partitioning.singlePartitioningExpressionForReport(); if (statementPartitionExpression != null) { // The planner has uncovered an overlooked opportunity to run the statement SP. String msg = "This procedure " + shortName + " would benefit from being partitioned, by "; String tableName = "tableName", partitionColumnName = "partitionColumnName"; try { assert(partitioning.getFullColumnName() != null); String array[] = partitioning.getFullColumnName().split("\\."); tableName = array[0]; partitionColumnName = array[1]; } catch(Exception ex) { } if (statementPartitionExpression instanceof ParameterValueExpression) { paramCount = ((ParameterValueExpression) statementPartitionExpression).getParameterIndex(); } else { String valueDescription = null; Object partitionValue = partitioning.getInferredPartitioningValue(); if (partitionValue == null) { // Statement partitioned on a runtime constant. This is likely to be cryptic, but hopefully gets the idea across. valueDescription = "of " + statementPartitionExpression.explain(""); } else { valueDescription = partitionValue.toString(); // A simple constant value COULD have been a parameter. } msg += "adding a parameter to be passed the value " + valueDescription + " and "; } msg += "adding a 'PARTITION ON TABLE " + tableName + " COLUMN " + partitionColumnName + " PARAMETER " + paramCount + "' clause to the " + "CREATE PROCEDURE statement. or using a separate PARTITION PROCEDURE statement"; compiler.addWarn(msg); } } } } /** * Determine which parameter is the partition indicator */ static void parsePartitionInfo(VoltCompiler compiler, Database db, Procedure procedure, String info) throws VoltCompilerException { assert(procedure.getSinglepartition() == true); // check this isn't empty if (info.length() == 0) { String msg = "Missing or Truncated PartitionInfo in attribute for procedure: " + procedure.getClassname(); throw compiler.new VoltCompilerException(msg); } // split on the colon String[] parts = info.split(":"); // if the colon doesn't split well, we have a problem if (parts.length != 2) { String msg = "Possibly invalid PartitionInfo in attribute for procedure: " + procedure.getClassname(); throw compiler.new VoltCompilerException(msg); } // relabel the parts for code readability String columnInfo = parts[0].trim(); int paramIndex = Integer.parseInt(parts[1].trim()); int paramCount = procedure.getParameters().size(); if ((paramIndex < 0) || (paramIndex >= paramCount)) { String msg = "PartitionInfo specifies invalid parameter index for procedure: " + procedure.getClassname(); throw compiler.new VoltCompilerException(msg); } // locate the parameter procedure.setPartitionparameter(paramIndex); // split the columninfo parts = columnInfo.split("\\."); if (parts.length != 2) { String msg = "Possibly invalid PartitionInfo in attribute for procedure: " + procedure.getClassname(); throw compiler.new VoltCompilerException(msg); } // relabel the parts for code readability String tableName = parts[0].trim(); String columnName = parts[1].trim(); // locate the partition column CatalogMap<Table> tables = db.getTables(); for (Table table : tables) { if (table.getTypeName().equalsIgnoreCase(tableName)) { CatalogMap<Column> columns = table.getColumns(); Column partitionColumn = table.getPartitioncolumn(); if (partitionColumn == null) { String msg = String.format("PartitionInfo for procedure %s references table %s which has no partition column (may be replicated).", procedure.getClassname(), table.getTypeName()); throw compiler.new VoltCompilerException(msg); } for (Column column : columns) { if (column.getTypeName().equalsIgnoreCase(columnName)) { if (partitionColumn.getTypeName().equals(column.getTypeName())) { procedure.setPartitioncolumn(column); procedure.setPartitiontable(table); return; } else { String msg = "PartitionInfo for procedure " + procedure.getClassname() + " refers to a column in schema which is not a partition key."; throw compiler.new VoltCompilerException(msg); } } } } } String msg = "PartitionInfo for procedure " + procedure.getClassname() + " refers to a column in schema which can't be found."; throw compiler.new VoltCompilerException(msg); } }
package de.mrapp.android.dialog; import java.util.Locale; import android.annotation.TargetApi; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnMultiChoiceClickListener; import android.content.res.TypedArray; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.os.Build; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import de.mrapp.android.dialog.listener.OnClickListenerWrapper; import de.mrapp.android.dialog.listener.OnItemClickListenerWrapper; import de.mrapp.android.dialog.listener.OnMultiChoiceClickListenerWrapper; /** * A builder, which allows to create dialogs, which are designed according to * Android 5.0's Material Design guidelines even on pre-Lollipop devices. Such a * dialog consists of a title, a message and up to three buttons. Furthermore * the dialog can be used to show list items. It is possible to customize the * color of the dialog's title and button texts and the title as well as the * dialog's content can be replaced by a custom view. * * @author Michael Rapp * * @since 1.0.0 */ public class MaterialDialogBuilder extends AlertDialog.Builder { /** * The context, which is used by the builder. */ private Context context; private CharSequence title; private CharSequence message; private Drawable icon; private int titleColor; private int buttonTextColor; private boolean stackButtons; private CharSequence negativeButtonText; private CharSequence neutralButtonText; private CharSequence positiveButtonText; private OnClickListener negativeButtonListener; private OnClickListener neutralButtonListener; private OnClickListener positiveButtonListener; private ListAdapter listAdapter; private int listViewChoiceMode; private OnClickListener listViewSingleChoiceListener; private OnMultiChoiceClickListener listViewMultiChoiceListener; private OnItemSelectedListener listViewItemSelectedListener; private boolean[] checkedListItems; private View customView; private int customViewId; private View customTitleView; /** * Inflates the dialog's layout. * * @return The root view of the layout, which has been inflated, as an * instance of the class {@link View} */ private View inflateLayout() { View root = View.inflate(context, R.layout.material_dialog, null); super.setView(root); return root; } /** * Inflates the dialog's title view, which may either be the default view or * a custom view, if one has been set before. * * @param root * The root view of the dialog's layout as an instance of the * class {@link View} * @return The parent view of the title view, which has been inflated, as an * instance of the class {@link ViewGroup} */ private ViewGroup inflateTitleView(final View root) { ViewGroup titleContainer = (ViewGroup) root .findViewById(R.id.title_container); if (customTitleView != null) { titleContainer.setVisibility(View.VISIBLE); titleContainer.addView(customTitleView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } else { View.inflate(context, R.layout.material_dialog_title, titleContainer); } initializeTitle(titleContainer); return titleContainer; } /** * Initializes the dialog's title and icon. * * @param titleContainer * The parent view of the title view as an instance of the class * {@link ViewGroup} */ private void initializeTitle(final ViewGroup titleContainer) { TextView titleTextView = (TextView) titleContainer .findViewById(android.R.id.title); if (titleTextView != null) { if (!TextUtils.isEmpty(title) || icon != null) { titleContainer.setVisibility(View.VISIBLE); titleTextView.setText(title); if (titleColor != 0) { titleTextView.setTextColor(titleColor); } if (icon != null) { titleTextView.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null); } } } } /** * Initializes the dialog's message. * * @param root * The root view of the dialog's layout as an instance of the * class {@link View} * @param titleContainer * The parent view of the title view as an instance of the class * {@link ViewGroup} * @return The text view, which is used to show the dialog's message, as an * instance of the class {@link TextView} */ private TextView initializeMessage(final View root, final ViewGroup titleContainer) { TextView messageTextView = (TextView) root .findViewById(android.R.id.message); if (!TextUtils.isEmpty(message)) { showMessageTextView(titleContainer, messageTextView); messageTextView.setText(message); } return messageTextView; } /** * Shows the text view, which is used to show the dialog's message. * * @param titleContainer * The parent view of the title view as an instance of the class * {@link ViewGroup} * @param messageTextView * The text view, which is used to show the dialog's message, as * an instance of the class {@link TextView} */ private void showMessageTextView(final ViewGroup titleContainer, final TextView messageTextView) { messageTextView.setVisibility(View.VISIBLE); LinearLayout.LayoutParams layoutParams = (LayoutParams) titleContainer .getLayoutParams(); layoutParams.bottomMargin = context.getResources() .getDimensionPixelSize(R.dimen.dialog_content_spacing); titleContainer.setLayoutParams(layoutParams); } /** * Inflates the dialog's content view, which may either be the default view * or a custom view, if one has been set before. * * @param root * The root view of the dialog's layout as an instance of the * class {@link View} * @param titleContainer * The parent view of the title view as an instance of the class * {@link ViewGroup} * @param messageTextView * The text view, which is used to show the dialog's message, as * an instance of the class {@link TextView} * @param dialog * The dialog, whose content view should be inflated, as an * instance of the class {@link AlertDialog} */ private void inflateContentView(final View root, final ViewGroup titleContainer, final TextView messageTextView, final AlertDialog dialog) { ViewGroup contentContainer = (ViewGroup) root .findViewById(R.id.content_container); if (customView != null) { showContentContainer(contentContainer, titleContainer, messageTextView); contentContainer.addView(customView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } else if (customViewId != 0) { showContentContainer(contentContainer, titleContainer, messageTextView); View.inflate(context, customViewId, contentContainer); } else { View.inflate(context, R.layout.material_dialog_list_view, contentContainer); } initializeContent(contentContainer, titleContainer, messageTextView, dialog); } /** * Initializes the dialog's content. The content view is shown if a custom * content view has been specified or if any list items have been set. * * @param contentContainer * The parent view of the the content view as an instance of the * clas {@link ViewGroup} * @param titleContainer * The parent view of the title view as an instance of the class * {@link ViewGroup} * @param messageTextView * The text view, which is used to show the dialog's message, as * an instance of the class {@link TextView} * @param dialog * The dialog, whose content should be initialized, as an * instance of the class {@link AlertDialog} */ private void initializeContent(final ViewGroup contentContainer, final ViewGroup titleContainer, final TextView messageTextView, final AlertDialog dialog) { ListView listView = (ListView) contentContainer .findViewById(android.R.id.list); if (listAdapter != null && !listAdapter.isEmpty() && listView != null) { showContentContainer(contentContainer, titleContainer, messageTextView); listView.setChoiceMode(listViewChoiceMode); listView.setAdapter(listAdapter); initializeListViewListener(dialog, listView); initializeListViewCheckedItems(listView); } } /** * Initializes the listener, which should be notified, when the selection of * a list item of the dialog has been changed. * * @param dialog * The dialog, the list items belong to, as an instance of the * class {@link AlertDialog} * @param listView * The list view, which is used to show the list items, as an * instance of the class {@link ListView} */ private void initializeListViewListener(final AlertDialog dialog, final ListView listView) { if (listViewChoiceMode == ListView.CHOICE_MODE_NONE) { listView.setOnItemClickListener(new OnItemClickListenerWrapper( listViewSingleChoiceListener, dialog, AlertDialog.BUTTON_POSITIVE)); } else if (listViewChoiceMode == ListView.CHOICE_MODE_SINGLE) { listView.setOnItemClickListener(new OnItemClickListenerWrapper( listViewSingleChoiceListener, dialog, 0)); } else if (listViewChoiceMode == ListView.CHOICE_MODE_MULTIPLE) { listView.setOnItemClickListener(new OnMultiChoiceClickListenerWrapper( listViewMultiChoiceListener, dialog, 0)); } if (listViewItemSelectedListener != null) { listView.setOnItemSelectedListener(listViewItemSelectedListener); } } /** * Initializes the list items, which are selected by default. * * @param listView * The list view, which is used to show the list items, as an * instance of the class {@link ListView} */ private void initializeListViewCheckedItems(final ListView listView) { if (checkedListItems != null) { for (int i = 0; i < checkedListItems.length; i++) { listView.setItemChecked(i, checkedListItems[i]); } } } /** * Shows the parent view of the dialog's content view. * * @param contentContainer * The parent view of the the content view as an instance of the * clas {@link ViewGroup} * @param titleContainer * The parent view of the title view as an instance of the class * {@link ViewGroup} * @param messageTextView * The text view, which is used to show the dialog's message, as * an instance of the class {@link TextView} */ private void showContentContainer(final ViewGroup contentContainer, final ViewGroup titleContainer, final TextView messageTextView) { contentContainer.setVisibility(View.VISIBLE); int contentSpacing = context.getResources().getDimensionPixelSize( R.dimen.dialog_content_spacing); LinearLayout.LayoutParams titleLayoutParams = (LayoutParams) titleContainer .getLayoutParams(); titleLayoutParams.bottomMargin = contentSpacing; titleContainer.setLayoutParams(titleLayoutParams); LinearLayout.LayoutParams messageLayoutParams = (LayoutParams) messageTextView .getLayoutParams(); messageLayoutParams.bottomMargin = contentSpacing; messageTextView.setLayoutParams(messageLayoutParams); } /** * Inflates the button bar, which contains the dialog's buttons. * * @param root * The root view of the dialog's layout as an instance of the * class {@link View} * @param dialog * The dialog, the buttons belong to, as an instance of the class * {@link AlertDialog} */ private void inflateButtonBar(final View root, final AlertDialog dialog) { ViewGroup buttonBarContainer = (ViewGroup) root .findViewById(R.id.button_bar_container); if (stackButtons) { View.inflate(context, R.layout.stacked_button_bar, buttonBarContainer); } else { View.inflate(context, R.layout.horizontal_button_bar, buttonBarContainer); } initializeButtonBar(root, buttonBarContainer, dialog); } /** * Initializes the button bar, which contains the dialog's buttons. * * @param root * The root view of the dialog's layout as an instance of the * class {@link View} * @param buttonBarContainer * The parent view of the button bar, which contains the dialog's * buttons, as an instance of the class {@link ViewGroup} * @param dialog * The dialog, the buttons belong to, as an instance of the class * {@link AlertDialog} */ private void initializeButtonBar(final View root, final ViewGroup buttonBarContainer, final AlertDialog dialog) { Button negativeButton = addNegativeButton(buttonBarContainer, dialog); Button neutralButton = addNeutralButton(buttonBarContainer, dialog); Button positiveButton = addPositiveButton(buttonBarContainer, dialog); if (negativeButton != null || neutralButton != null || positiveButton != null) { showButtonBarContainer(root, buttonBarContainer); } } /** * Shows the parent view of the button bar, which contains the dialog's * buttons. * * @param root * The root view of the dialog's layout as an instance of the * class {@link View} * @param buttonBarContainer * The parent view of the button bar, which contains the dialog's * buttons, as an instance of the class {@link ViewGroup} */ private void showButtonBarContainer(final View root, final View buttonBarContainer) { View contentRoot = root.findViewById(R.id.content_root); buttonBarContainer.setVisibility(View.VISIBLE); int paddingLeft = context.getResources().getDimensionPixelSize( R.dimen.dialog_content_padding_left); int paddingTop = context.getResources().getDimensionPixelSize( R.dimen.dialog_content_padding_top); int paddingRight = context.getResources().getDimensionPixelSize( R.dimen.dialog_content_padding_right); int paddingBottom = context.getResources().getDimensionPixelSize( R.dimen.dialog_content_padding_bottom); contentRoot.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom); } /** * Adds a negative button to the dialog, if an appropriate button text has * been set before. * * @param root * The root view of the dialog's layout as an instance of the * class {@link View} * @param dialog * The dialog, the button should belong to, as an instance of the * class {@link AlertDialog} * @return The button, which has been added to the dialog, as an instance of * the class {@link Button} or null, if no button has been added */ private Button addNegativeButton(final View root, final AlertDialog dialog) { if (!TextUtils.isEmpty(negativeButtonText)) { Button negativeButton = (Button) root .findViewById(android.R.id.button1); negativeButton.setText(negativeButtonText.toString().toUpperCase( Locale.getDefault())); OnClickListenerWrapper onClickListener = new OnClickListenerWrapper( negativeButtonListener, dialog, AlertDialog.BUTTON_NEGATIVE); negativeButton.setOnClickListener(onClickListener); negativeButton.setVisibility(View.VISIBLE); if (buttonTextColor != 0) { negativeButton.setTextColor(buttonTextColor); } return negativeButton; } return null; } /** * Adds a neutral button to the dialog, if an appropriate button text has * been set before. * * @param root * The root view of the dialog's layout as an instance of the * class {@link View} * @param dialog * The dialog, the button should belong to, as an instance of the * class {@link AlertDialog} * @return The button, which has been added to the dialog, as an instance of * the class {@link Button} or null, if no button has been added */ private Button addNeutralButton(final View root, final AlertDialog dialog) { if (!TextUtils.isEmpty(neutralButtonText)) { Button neutralButton = (Button) root .findViewById(android.R.id.button2); neutralButton.setText(neutralButtonText.toString().toUpperCase( Locale.getDefault())); OnClickListenerWrapper onClickListener = new OnClickListenerWrapper( neutralButtonListener, dialog, AlertDialog.BUTTON_NEUTRAL); neutralButton.setOnClickListener(onClickListener); neutralButton.setVisibility(View.VISIBLE); if (buttonTextColor != 0) { neutralButton.setTextColor(buttonTextColor); } return neutralButton; } return null; } /** * Adds a positive button to the dialog, if an appropriate button text has * been set before. * * @param root * The root view of the dialog's layout as an instance of the * class {@link View} * @param dialog * The dialog, the button should belong to, as an instance of the * class {@link AlertDialog} * @return The button, which has been added to the dialog, as an instance of * the class {@link Button} or null, if no button has been added */ private Button addPositiveButton(final View root, final AlertDialog dialog) { if (!TextUtils.isEmpty(positiveButtonText)) { Button positiveButton = (Button) root .findViewById(android.R.id.button3); positiveButton.setText(positiveButtonText.toString().toUpperCase( Locale.getDefault())); OnClickListenerWrapper onClickListener = new OnClickListenerWrapper( positiveButtonListener, dialog, AlertDialog.BUTTON_POSITIVE); positiveButton.setOnClickListener(onClickListener); positiveButton.setVisibility(View.VISIBLE); if (buttonTextColor != 0) { positiveButton.setTextColor(buttonTextColor); } return positiveButton; } return null; } /** * Creates a new builder, which allows to create dialogs, which are designed * according to Android 5.0's Material Design guidelines even on * pre-Lollipop devices. * * @param context * The context, which should be used by the builder, as an * instance of the class {@link Context} */ public MaterialDialogBuilder(final Context context) { super(context); this.context = context; } public final MaterialDialogBuilder setTitleColor(final int color) { this.titleColor = color; return this; } public final MaterialDialogBuilder setButtonTextColor(final int color) { this.buttonTextColor = color; return this; } public final MaterialDialogBuilder stackButtons(final boolean stackButtons) { this.stackButtons = stackButtons; return this; } @Override public final MaterialDialogBuilder setTitle(final CharSequence title) { this.title = title; return this; } @Override public final MaterialDialogBuilder setTitle(final int resourceId) { return setTitle(context.getText(resourceId)); } @Override public final MaterialDialogBuilder setMessage(final CharSequence message) { this.message = message; return this; } @Override public final MaterialDialogBuilder setMessage(final int resourceId) { return setMessage(context.getText(resourceId)); } @Override public final MaterialDialogBuilder setIcon(final Drawable icon) { this.icon = icon; return this; } @Override public final MaterialDialogBuilder setIcon(final int resourceId) { return setIcon(context.getResources().getDrawable(resourceId)); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override public final MaterialDialogBuilder setIconAttribute(final int attributeId) { TypedArray typedArray = context.getTheme().obtainStyledAttributes( new int[] { attributeId }); return setIcon(typedArray.getDrawable(0)); } @Override public final MaterialDialogBuilder setNegativeButton( final CharSequence text, final OnClickListener listener) { negativeButtonText = text; negativeButtonListener = listener; return this; } @Override public final MaterialDialogBuilder setNegativeButton(final int resourceId, final OnClickListener listener) { return setNegativeButton(context.getText(resourceId), listener); } @Override public final MaterialDialogBuilder setPositiveButton( final CharSequence text, final OnClickListener listener) { positiveButtonText = text; positiveButtonListener = listener; return this; } @Override public final MaterialDialogBuilder setPositiveButton(final int resourceId, final OnClickListener listener) { return setPositiveButton(context.getText(resourceId), listener); } @Override public final MaterialDialogBuilder setNeutralButton( final CharSequence text, final OnClickListener listener) { neutralButtonText = text; neutralButtonListener = listener; return this; } @Override public final MaterialDialogBuilder setNeutralButton(final int resourceId, final OnClickListener listener) { return setNeutralButton(context.getText(resourceId), listener); } @Override public final MaterialDialogBuilder setItems(final CharSequence[] items, final OnClickListener listener) { listAdapter = new ArrayAdapter<CharSequence>(context, android.R.layout.simple_list_item_1, items); listViewSingleChoiceListener = listener; listViewChoiceMode = ListView.CHOICE_MODE_NONE; return this; } @Override public final MaterialDialogBuilder setItems(final int resourceId, final OnClickListener listener) { return setItems(context.getResources().getTextArray(resourceId), listener); } @Override public final MaterialDialogBuilder setAdapter(final ListAdapter adapter, final OnClickListener listener) { listAdapter = adapter; listViewSingleChoiceListener = listener; listViewChoiceMode = ListView.CHOICE_MODE_NONE; return this; } @Override public final MaterialDialogBuilder setCursor(final Cursor cursor, final OnClickListener listener, final String labelColumn) { throw new UnsupportedOperationException( "This method is not supported yet"); } @Override public final MaterialDialogBuilder setSingleChoiceItems( final CharSequence[] items, final int checkedItem, final OnClickListener listener) { listAdapter = new ArrayAdapter<CharSequence>(context, android.R.layout.simple_list_item_single_choice, items); listViewSingleChoiceListener = listener; listViewChoiceMode = ListView.CHOICE_MODE_SINGLE; checkedListItems = new boolean[items.length]; for (int i = 0; i < checkedListItems.length; i++) { checkedListItems[i] = (i == checkedItem); } return this; } @Override public final MaterialDialogBuilder setSingleChoiceItems( final int resourceId, final int checkedItem, final OnClickListener listener) { return setSingleChoiceItems( context.getResources().getTextArray(resourceId), checkedItem, listener); } @Override public final MaterialDialogBuilder setSingleChoiceItems( final ListAdapter adapter, final int checkedItem, final OnClickListener listener) { listAdapter = adapter; listViewSingleChoiceListener = listener; listViewChoiceMode = ListView.CHOICE_MODE_SINGLE; checkedListItems = new boolean[adapter.getCount()]; for (int i = 0; i < checkedListItems.length; i++) { checkedListItems[i] = (i == checkedItem); } return this; } @Override public final MaterialDialogBuilder setSingleChoiceItems( final Cursor cursor, final int checkedItem, final String labelColumn, final OnClickListener listener) { throw new UnsupportedOperationException( "This method is not supported yet"); } @Override public final MaterialDialogBuilder setMultiChoiceItems( final CharSequence[] items, final boolean[] checkedItems, final OnMultiChoiceClickListener listener) { listAdapter = new ArrayAdapter<CharSequence>(context, android.R.layout.simple_list_item_multiple_choice, items); listViewMultiChoiceListener = listener; listViewChoiceMode = ListView.CHOICE_MODE_MULTIPLE; checkedListItems = checkedItems; return this; } @Override public final MaterialDialogBuilder setMultiChoiceItems( final int resourceId, final boolean[] checkedItems, final OnMultiChoiceClickListener listener) { return setMultiChoiceItems( context.getResources().getTextArray(resourceId), checkedItems, listener); } @Override public final MaterialDialogBuilder setMultiChoiceItems(final Cursor cursor, final String isCheckedColumn, final String labelColumn, final OnMultiChoiceClickListener listener) { throw new UnsupportedOperationException( "This method is not supported yet"); } @Override public final MaterialDialogBuilder setOnItemSelectedListener( final OnItemSelectedListener listener) { listViewItemSelectedListener = listener; return this; } @Override public final MaterialDialogBuilder setView(final View view) { customView = view; customViewId = 0; return this; } @Override public final MaterialDialogBuilder setView(final int resourceId) { customViewId = resourceId; customView = null; return this; } @Override public final MaterialDialogBuilder setCustomTitle(final View view) { customTitleView = view; return this; } @Override public final AlertDialog create() { View root = inflateLayout(); AlertDialog dialog = super.create(); ViewGroup titleContainer = inflateTitleView(root); TextView messageTextView = initializeMessage(root, titleContainer); inflateContentView(root, titleContainer, messageTextView, dialog); inflateButtonBar(root, dialog); return dialog; } }
package org.apache.jmeter.modifiers; import java.io.Serializable; import java.util.Collection; import java.util.LinkedList; import org.apache.jmeter.engine.event.LoopIterationEvent; import org.apache.jmeter.engine.event.LoopIterationListener; import org.apache.jmeter.processor.PreProcessor; import org.apache.jmeter.testelement.AbstractTestElement; import org.apache.jmeter.testelement.TestElement; import org.apache.jmeter.testelement.property.BooleanProperty; import org.apache.jmeter.testelement.property.CollectionProperty; import org.apache.jmeter.testelement.property.PropertyIterator; import org.apache.jmeter.threads.JMeterContextService; import org.apache.jmeter.threads.JMeterVariables; /** * @author Administrator * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. */ public class UserParameters extends AbstractTestElement implements Serializable, PreProcessor, LoopIterationListener { public static final String NAMES = "UserParameters.names"; public static final String THREAD_VALUES = "UserParameters.thread_values"; public static final String PER_ITERATION = "UserParameters.per_iteration"; private int counter = 0; private Integer lock = new Integer(0); public CollectionProperty getNames() { return (CollectionProperty) getProperty(NAMES); } public CollectionProperty getThreadLists() { return (CollectionProperty) getProperty(THREAD_VALUES); } /** * The list of names of the variables to hold values. This list must come in * the same order as the sub lists that are given to setThreadLists(List). */ public void setNames(Collection list) { setProperty(new CollectionProperty(NAMES, list)); } /** * The list of names of the variables to hold values. This list must come in * the same order as the sub lists that are given to setThreadLists(List). */ public void setNames(CollectionProperty list) { setProperty(list); } /** * The thread list is a list of lists. Each list within the parent list is a * collection of values for a simulated user. As many different sets of * values can be supplied in this fashion to cause JMeter to set different * values to variables for different test threads. */ public void setThreadLists(Collection threadLists) { setProperty(new CollectionProperty(THREAD_VALUES, threadLists)); } /** * The thread list is a list of lists. Each list within the parent list is a * collection of values for a simulated user. As many different sets of * values can be supplied in this fashion to cause JMeter to set different * values to variables for different test threads. */ public void setThreadLists(CollectionProperty threadLists) { setProperty(threadLists); } private CollectionProperty getValues() { CollectionProperty threadValues = (CollectionProperty) getProperty(THREAD_VALUES); if (threadValues.size() > 0) { return (CollectionProperty) threadValues.get(JMeterContextService.getContext().getThreadNum() % threadValues.size()); } else { return new CollectionProperty("noname", new LinkedList()); } } public boolean isPerIteration() { return getPropertyAsBoolean(PER_ITERATION); } public void setPerIteration(boolean perIter) { setProperty(new BooleanProperty(PER_ITERATION, perIter)); } public void process() { if (!isPerIteration()) { setValues(); } } private void setValues() { synchronized (lock) { log.debug("Running up named: " + getName()); PropertyIterator namesIter = getNames().iterator(); PropertyIterator valueIter = getValues().iterator(); JMeterVariables jmvars = JMeterContextService.getContext().getVariables(); while (namesIter.hasNext() && valueIter.hasNext()) { String name = namesIter.next().getStringValue(); String value = valueIter.next().getStringValue(); log.debug("saving variable: " + name + "=" + value); jmvars.put(name, value); } } } /** * @see org.apache.jmeter.engine.event.LoopIterationListener#iterationStart(LoopIterationEvent) */ public void iterationStart(LoopIterationEvent event) { if (isPerIteration()) { setValues(); } } /* This method doesn't appear to be used anymore. * jeremy_a@bigfoot.com 03 May 2003 * * @see org.apache.jmeter.testelement.ThreadListener#setJMeterVariables(org.apache.jmeter.threads.JMeterVariables) public void setJMeterVariables(JMeterVariables jmVars) {} */ /* (non-Javadoc) * @see java.lang.Object#clone() */ public Object clone() { UserParameters up = (UserParameters) super.clone(); up.lock = lock; return up; } /* (non-Javadoc) * @see org.apache.jmeter.testelement.AbstractTestElement#mergeIn(org.apache.jmeter.testelement.TestElement) */ protected void mergeIn(TestElement element) { // super.mergeIn(element); } }
package org.voltdb.compiler; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.CompletableFuture; import org.hsqldb_voltpatches.HSQLInterface; import org.voltcore.logging.VoltLogger; import org.voltdb.ProcInfo; import org.voltdb.ProcInfoData; import org.voltdb.SQLStmt; import org.voltdb.VoltDB; import org.voltdb.VoltNonTransactionalProcedure; import org.voltdb.VoltProcedure; import org.voltdb.VoltTable; import org.voltdb.VoltType; import org.voltdb.VoltTypeException; import org.voltdb.catalog.CatalogMap; import org.voltdb.catalog.Column; import org.voltdb.catalog.Database; import org.voltdb.catalog.Group; import org.voltdb.catalog.GroupRef; import org.voltdb.catalog.ProcParameter; import org.voltdb.catalog.Procedure; import org.voltdb.catalog.Statement; import org.voltdb.catalog.StmtParameter; import org.voltdb.catalog.Table; import org.voltdb.compiler.VoltCompiler.ProcedureDescriptor; import org.voltdb.compiler.VoltCompiler.VoltCompilerException; import org.voltdb.compilereport.ProcedureAnnotation; import org.voltdb.expressions.AbstractExpression; import org.voltdb.expressions.ParameterValueExpression; import org.voltdb.planner.StatementPartitioning; import org.voltdb.types.QueryType; import org.voltdb.utils.CatalogUtil; import org.voltdb.utils.InMemoryJarfile; import com.google_voltpatches.common.collect.ImmutableMap; /** * Compiles stored procedures into a given catalog, * invoking the StatementCompiler as needed. */ public abstract class ProcedureCompiler { static void compile(VoltCompiler compiler, HSQLInterface hsql, DatabaseEstimates estimates, Database db, ProcedureDescriptor procedureDescriptor, InMemoryJarfile jarOutput) throws VoltCompiler.VoltCompilerException { assert(compiler != null); assert(hsql != null); assert(estimates != null); if (procedureDescriptor.m_singleStmt == null) { compileJavaProcedure(compiler, hsql, estimates, db, procedureDescriptor, jarOutput); } else { compileSingleStmtProcedure(compiler, hsql, estimates, db, procedureDescriptor); } } public static Map<String, SQLStmt> getValidSQLStmts(VoltCompiler compiler, String procName, Class<?> procClass, Object procInstance, boolean withPrivate) throws VoltCompilerException { Map<String, SQLStmt> retval = new HashMap<>(); Field[] fields = procClass.getDeclaredFields(); for (Field f : fields) { // skip non SQL fields if (f.getType() != SQLStmt.class) continue; int modifiers = f.getModifiers(); // skip private fields if asked (usually a superclass) if (Modifier.isPrivate(modifiers) && (!withPrivate)) continue; // don't allow non-final SQLStmts if (Modifier.isFinal(modifiers) == false) { String msg = "Procedure " + procName + " contains a non-final SQLStmt field."; if (procClass.getSimpleName().equals(procName) == false) { msg = "Superclass " + procClass.getSimpleName() + " of procedure " + procName + " contains a non-final SQLStmt field."; } if (compiler != null) throw compiler.new VoltCompilerException(msg); else new VoltLogger("HOST").warn(msg); } f.setAccessible(true); SQLStmt stmt = null; try { stmt = (SQLStmt) f.get(procInstance); } // this exception handling here comes from other parts of the code // it's weird, but seems rather hard to hit catch (Exception e) { e.printStackTrace(); continue; } retval.put(f.getName(), stmt); } Class<?> superClass = procClass.getSuperclass(); if (superClass != null) { Map<String, SQLStmt> superStmts = getValidSQLStmts(compiler, procName, superClass, procInstance, false); for (Entry<String, SQLStmt> e : superStmts.entrySet()) { if (retval.containsKey(e.getKey()) == false) retval.put(e.getKey(), e.getValue()); } } return retval; } public static Map<String, SQLStmt> getSQLStmtMap(VoltCompiler compiler, Class<?> procClass) throws VoltCompilerException { VoltProcedure procInstance; try { procInstance = (VoltProcedure) procClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException("Error instantiating procedure " + procClass.getName(), e); } Map<String, SQLStmt> stmtMap = getValidSQLStmts(compiler, procClass.getSimpleName(), procClass, procInstance, true); return stmtMap; } /** * get the short name of the class (no package) * @param className fully qualified (or not) class name * @return short name of the class (no package) */ public static String deriveShortProcedureName( String className) { if( className == null || className.trim().isEmpty()) { return null; } String[] parts = className.split("\\."); String shortName = parts[parts.length - 1]; return shortName; } public static ProcInfoData checkPartitioningInfo(VoltCompiler compiler, String ddlPartitionString, String className, ProcedureAnnotation pa, Class<?> procClass) throws VoltCompilerException { // check if partition info was set in ddl ProcInfoData ddlInfo = null; if (ddlPartitionString != null && ! ddlPartitionString.trim().isEmpty()) { ddlInfo = new ProcInfoData(); ddlInfo.partitionInfo = ddlPartitionString; ddlInfo.singlePartition = true; } String shortName = deriveShortProcedureName(className); // get the annotation // first try to get one that has been passed from the compiler ProcInfoData info = compiler.getProcInfoOverride(shortName); // then check for the usual one in the class itself // and create a ProcInfo.Data instance for it if (info == null) { info = new ProcInfoData(); ProcInfo annotationInfo = procClass.getAnnotation(ProcInfo.class); // error out if partition info is present in both ddl and annotation if (annotationInfo != null) { if (ddlInfo != null) { String msg = "Procedure: " + shortName + " has partition properties defined both in "; msg += "class \"" + className + "\" and in the schema definition file(s)"; throw compiler.new VoltCompilerException(msg); } // Prevent AutoGenerated DDL from including PARTITION PROCEDURE for this procedure. pa.classAnnotated = true; info.partitionInfo = annotationInfo.partitionInfo(); info.singlePartition = annotationInfo.singlePartition(); } else if (ddlInfo != null) { info = ddlInfo; } } else { pa.classAnnotated = true; } assert(info != null); // make sure multi-partition implies no partitioning info if (info.singlePartition == false) { if ((info.partitionInfo != null) && (info.partitionInfo.length() > 0)) { String msg = "Procedure: " + shortName + " is annotated as multi-partition"; msg += " but partitionInfo has non-empty value: \"" + info.partitionInfo + "\""; throw compiler.new VoltCompilerException(msg); } } return info; } public static Map<String, Object> getFiledsMap(VoltCompiler compiler, Map<String, SQLStmt> stmtMap, Class<?> procClass, String shortName) throws VoltCompilerException { ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder(); builder.putAll(stmtMap); // find the run() method and get the params Method procMethod = null; Method[] methods = procClass.getDeclaredMethods(); for (final Method m : methods) { String name = m.getName(); if (name.equals("run")) { assert (m.getDeclaringClass() == procClass); // if not null, then we've got more than one run method if (procMethod != null) { String msg = "Procedure: " + shortName + " has multiple public run(...) methods. "; msg += "Only a single run(...) method is supported."; throw compiler.new VoltCompilerException(msg); } if (Modifier.isPublic(m.getModifiers())) { // found it! procMethod = m; } else { compiler.addWarn("Procedure: " + shortName + " has non-public run(...) method."); } } } if (procMethod == null) { String msg = "Procedure: " + shortName + " has no run(...) method."; throw compiler.new VoltCompilerException(msg); } // check the return type of the run method if ((procMethod.getReturnType() != VoltTable[].class) && (procMethod.getReturnType() != VoltTable.class) && (procMethod.getReturnType() != long.class) && (procMethod.getReturnType() != Long.class)) { String msg = "Procedure: " + shortName + " has run(...) method that doesn't return long, Long, VoltTable or VoltTable[]."; throw compiler.new VoltCompilerException(msg); } builder.put("@run",procMethod); Map<String, Object> fields = builder.build(); return fields; } public static void compileSQLStmtUpdatingProcedureInfomation(VoltCompiler compiler, HSQLInterface hsql, DatabaseEstimates estimates, Database db, Procedure procedure, boolean isSinglePartition, Map<String, Object> fields) throws VoltCompilerException { // track if there are any writer statements and/or sequential scans and/or an overlooked common partitioning parameter boolean procHasWriteStmts = false; boolean procHasSeqScans = false; // procWantsCommonPartitioning == true but commonPartitionExpression == null signifies a proc // for which the planner was requested to attempt to find an SP plan, but that was not possible // -- it had a replicated write or it had one or more partitioned reads that were not all // filtered by the same partition key value -- so it was planned as an MP proc. boolean procWantsCommonPartitioning = true; AbstractExpression commonPartitionExpression = null; String exampleSPstatement = null; Object exampleSPvalue = null; // determine if proc is read or read-write by checking if the proc contains any write sql stmts boolean readWrite = false; for (Object field : fields.values()) { if (!(field instanceof SQLStmt)) continue; SQLStmt stmt = (SQLStmt)field; QueryType qtype = QueryType.getFromSQL(stmt.getText()); if (!qtype.isReadOnly()) { readWrite = true; break; } } // default to FASTER determinism mode, which may favor non-deterministic plans // but if it's a read-write proc, use a SAFER planning mode wrt determinism. final DeterminismMode detMode = readWrite ? DeterminismMode.SAFER : DeterminismMode.FASTER; for (Entry<String, Object> entry : fields.entrySet()) { if (!(entry.getValue() instanceof SQLStmt)) continue; String stmtName = entry.getKey(); SQLStmt stmt = (SQLStmt)entry.getValue(); // add the statement to the catalog Statement catalogStmt = procedure.getStatements().add(stmtName); // compile the statement StatementPartitioning partitioning = isSinglePartition ? StatementPartitioning.forceSP() : StatementPartitioning.forceMP(); boolean cacheHit = StatementCompiler.compileFromSqlTextAndUpdateCatalog(compiler, hsql, db, estimates, catalogStmt, stmt.getText(), stmt.getJoinOrder(), detMode, partitioning); // if this was a cache hit or specified single, don't worry about figuring out more partitioning if (partitioning.wasSpecifiedAsSingle() || cacheHit) { procWantsCommonPartitioning = false; // Don't try to infer what's already been asserted. // The planner does not currently attempt to second-guess a plan declared as single-partition, maybe some day. // In theory, the PartitioningForStatement would confirm the use of (only) a parameter as a partition key -- // or if the partition key was determined to be some other constant (expression?) it might display an informational // message that the passed parameter is assumed to be equal to the hard-coded partition key constant (expression). // Validate any inferred statement partitioning given the statement's possible usage, until a contradiction is found. } else if (procWantsCommonPartitioning) { // Only consider statements that are capable of running SP with a partitioning parameter that does not seem to // conflict with the partitioning of prior statements. if (partitioning.getCountOfIndependentlyPartitionedTables() == 1) { AbstractExpression statementPartitionExpression = partitioning.singlePartitioningExpressionForReport(); if (statementPartitionExpression != null) { if (commonPartitionExpression == null) { commonPartitionExpression = statementPartitionExpression; exampleSPstatement = stmt.getText(); exampleSPvalue = partitioning.getInferredPartitioningValue(); } else if (commonPartitionExpression.equals(statementPartitionExpression) || (statementPartitionExpression instanceof ParameterValueExpression && commonPartitionExpression instanceof ParameterValueExpression)) { // Any constant used for partitioning would have to be the same for all statements, but // any statement parameter used for partitioning MIGHT come from the same proc parameter as // any other statement's parameter used for partitioning. } else { procWantsCommonPartitioning = false; // appears to be different partitioning for different statements } } else { // There is a statement with a partitioned table whose partitioning column is // not equality filtered with a constant or param. Abandon all hope. procWantsCommonPartitioning = false; } // Usually, replicated-only statements in a mix with others have no effect on the MP/SP decision } else if (partitioning.getCountOfPartitionedTables() == 0) { // but SP is strictly forbidden for DML, to maintain the consistency of the replicated data. if (partitioning.getIsReplicatedTableDML()) { procWantsCommonPartitioning = false; } } else { // There is a statement with a partitioned table whose partitioning column is // not equality filtered with a constant or param. Abandon all hope. procWantsCommonPartitioning = false; } } // if a single stmt is not read only, then the proc is not read only if (catalogStmt.getReadonly() == false) { procHasWriteStmts = true; } if (catalogStmt.getSeqscancount() > 0) { procHasSeqScans = true; } } // MIGHT the planner have uncovered an overlooked opportunity to run all statements SP? if (procWantsCommonPartitioning && (commonPartitionExpression != null)) { String msg = null; if (commonPartitionExpression instanceof ParameterValueExpression) { msg = "This procedure might benefit from an @ProcInfo annotation designating parameter " + ((ParameterValueExpression) commonPartitionExpression).getParameterIndex() + " of statement '" + exampleSPstatement + "'"; } else { String valueDescription = null; if (exampleSPvalue == null) { // Statements partitioned on a runtime constant. This is likely to be cryptic, but hopefully gets the idea across. valueDescription = "of " + commonPartitionExpression.explain(""); } else { valueDescription = exampleSPvalue.toString(); // A simple constant value COULD have been a parameter. } msg = "This procedure might benefit from an @ProcInfo annotation referencing an added parameter passed the value " + valueDescription; } compiler.addInfo(msg); } // set the read onlyness of a proc procedure.setReadonly(procHasWriteStmts == false); procedure.setHasseqscans(procHasSeqScans); String shortName = deriveShortProcedureName(procedure.getClassname()); checkForDeterminismWarnings(compiler, shortName, procedure, procHasWriteStmts); } public static Class<?>[] setParameterTypes(VoltCompiler compiler, Procedure procedure, String shortName, Method procMethod) throws VoltCompilerException { // set procedure parameter types CatalogMap<ProcParameter> params = procedure.getParameters(); Class<?>[] paramTypes = procMethod.getParameterTypes(); for (int i = 0; i < paramTypes.length; i++) { Class<?> cls = paramTypes[i]; ProcParameter param = params.add(String.valueOf(i)); param.setIndex(i); // handle the case where the param is an array if (cls.isArray()) { param.setIsarray(true); cls = cls.getComponentType(); } else param.setIsarray(false); // boxed types are not supported parameters at this time if ((cls == Long.class) || (cls == Integer.class) || (cls == Short.class) || (cls == Byte.class) || (cls == Double.class) || (cls == Character.class) || (cls == Boolean.class)) { String msg = "Procedure: " + shortName + " has a parameter with a boxed type: "; msg += cls.getSimpleName(); msg += ". Replace this parameter with the corresponding primitive type and the procedure may compile."; throw compiler.new VoltCompilerException(msg); } else if ((cls == Float.class) || (cls == float.class)) { String msg = "Procedure: " + shortName + " has a parameter with type: "; msg += cls.getSimpleName(); msg += ". Replace this parameter type with double and the procedure may compile."; throw compiler.new VoltCompilerException(msg); } VoltType type; try { type = VoltType.typeFromClass(cls); } catch (VoltTypeException e) { // handle the case where the type is invalid String msg = "Procedure: " + shortName + " has a parameter with invalid type: "; msg += cls.getSimpleName(); throw compiler.new VoltCompilerException(msg); } catch (RuntimeException e) { String msg = "Procedure: " + shortName + " unexpectedly failed a check on a parameter of type: "; msg += cls.getSimpleName(); msg += " with error: "; msg += e.toString(); throw compiler.new VoltCompilerException(msg); } param.setType(type.getValue()); } return paramTypes; } public static void addPartitioningInfo(VoltCompiler compiler, Procedure procedure, Database db, Class<?>[] paramTypes, ProcInfoData info) throws VoltCompilerException { // parse the procedureInfo procedure.setSinglepartition(info.singlePartition); if (!info.singlePartition) return; parsePartitionInfo(compiler, db, procedure, info.partitionInfo); if (procedure.getPartitionparameter() >= paramTypes.length) { String msg = "PartitionInfo parameter not a valid parameter for procedure: " + procedure.getClassname(); throw compiler.new VoltCompilerException(msg); } // check the type of partition parameter meets our high standards Class<?> partitionType = paramTypes[procedure.getPartitionparameter()]; Class<?>[] validPartitionClzzes = { Long.class, Integer.class, Short.class, Byte.class, long.class, int.class, short.class, byte.class, String.class, byte[].class }; boolean found = false; for (Class<?> candidate : validPartitionClzzes) { if (partitionType == candidate) found = true; } if (!found) { String msg = "PartitionInfo parameter must be a String or Number for procedure: " + procedure.getClassname(); throw compiler.new VoltCompilerException(msg); } VoltType columnType = VoltType.get((byte)procedure.getPartitioncolumn().getType()); VoltType paramType = VoltType.typeFromClass(partitionType); if ( ! columnType.canExactlyRepresentAnyValueOf(paramType)) { String msg = "Type mismatch between partition column and partition parameter for procedure " + procedure.getClassname() + " may cause overflow or loss of precision.\nPartition column is type " + columnType + " and partition parameter is type " + paramType; throw compiler.new VoltCompilerException(msg); } else if ( ! paramType.canExactlyRepresentAnyValueOf(columnType)) { String msg = "Type mismatch between partition column and partition parameter for procedure " + procedure.getClassname() + " does not allow the full range of partition key values.\nPartition column is type " + columnType + " and partition parameter is type " + paramType; compiler.addWarn(msg); } } static void compileJavaProcedure(VoltCompiler compiler, HSQLInterface hsql, DatabaseEstimates estimates, Database db, ProcedureDescriptor procedureDescriptor, InMemoryJarfile jarOutput) throws VoltCompiler.VoltCompilerException { final String className = procedureDescriptor.m_className; // Load the class given the class name Class<?> procClass = procedureDescriptor.m_class; // get the short name of the class (no package) String shortName = deriveShortProcedureName(className); // add an entry to the catalog final Procedure procedure = db.getProcedures().add(shortName); for (String groupName : procedureDescriptor.m_authGroups) { final Group group = db.getGroups().get(groupName); if (group == null) { throw compiler.new VoltCompilerException("Procedure " + className + " allows access by a role " + groupName + " that does not exist"); } final GroupRef groupRef = procedure.getAuthgroups().add(groupName); groupRef.setGroup(group); } procedure.setClassname(className); // sysprocs don't use the procedure compiler procedure.setSystemproc(false); procedure.setDefaultproc(procedureDescriptor.m_builtInStmt); procedure.setHasjava(true); ProcedureAnnotation pa = (ProcedureAnnotation) procedure.getAnnotation(); if (pa == null) { pa = new ProcedureAnnotation(); procedure.setAnnotation(pa); } // check if partition info was set in ddl ProcInfoData info = checkPartitioningInfo(compiler, procedureDescriptor.m_partitionString, className, pa, procClass); // if the procedure is non-transactional, then take this special path here if (VoltNonTransactionalProcedure.class.isAssignableFrom(procClass)) { compileNTProcedure(compiler, procClass, procedure, jarOutput); return; } // if still here, that means the procedure is transactional procedure.setTransactional(true); // iterate through the fields and get valid sql statements Map<String, SQLStmt> stmtMap = getSQLStmtMap(compiler, procClass); Map<String, Object> fields = getFiledsMap(compiler, stmtMap, procClass, shortName); Method procMethod = (Method) fields.get("@run"); assert(procMethod != null); compileSQLStmtUpdatingProcedureInfomation(compiler, hsql, estimates, db, procedure, info.singlePartition, fields); // set procedure parameter types Class<?>[] paramTypes = setParameterTypes(compiler, procedure, shortName, procMethod); addPartitioningInfo(compiler, procedure, db, paramTypes, info); // put the compiled code for this procedure into the jarfile // need to find the outermost ancestor class for the procedure in the event // that it's actually an inner (or inner inner...) class. // addClassToJar recursively adds all the children, which should include this // class Class<?> ancestor = procClass; while (ancestor.getEnclosingClass() != null) { ancestor = ancestor.getEnclosingClass(); } compiler.addClassToJar(jarOutput, ancestor); } public static void compileNTProcedure(VoltCompiler compiler, Class<?> procClass, Procedure procedure, InMemoryJarfile jarOutput) throws VoltCompilerException { // get the short name of the class (no package) String shortName = deriveShortProcedureName(procClass.getName()); try { procClass.newInstance(); } catch (InstantiationException e) { throw new RuntimeException("Error instantiating procedure \"" + procClass.getName() + "\"", e); } catch (IllegalAccessException e) { throw new RuntimeException("Error instantiating procedure \"" + procClass.getName() + "\"", e); } // find the run() method and get the params Method procMethod = null; Method[] methods = procClass.getDeclaredMethods(); for (final Method m : methods) { String name = m.getName(); if (name.equals("run")) { assert (m.getDeclaringClass() == procClass); // if not null, then we've got more than one run method if (procMethod != null) { String msg = "Procedure: " + shortName + " has multiple public run(...) methods. "; msg += "Only a single run(...) method is supported."; throw compiler.new VoltCompilerException(msg); } if (Modifier.isPublic(m.getModifiers())) { // found it! procMethod = m; } else { compiler.addWarn("Procedure: " + shortName + " has non-public run(...) method."); } } } if (procMethod == null) { String msg = "Procedure: " + shortName + " has no run(...) method."; throw compiler.new VoltCompilerException(msg); } // check the return type of the run method if ((procMethod.getReturnType() != CompletableFuture.class) && (procMethod.getReturnType() != VoltTable[].class) && (procMethod.getReturnType() != VoltTable.class) && (procMethod.getReturnType() != long.class) && (procMethod.getReturnType() != Long.class)) { String msg = "Procedure: " + shortName + " has run(...) method that doesn't return long, Long, VoltTable, VoltTable[] or CompleteableFuture."; throw compiler.new VoltCompilerException(msg); } // set procedure parameter types CatalogMap<ProcParameter> params = procedure.getParameters(); Class<?>[] paramTypes = procMethod.getParameterTypes(); setCatalogProcedureParameterTypes(compiler, shortName, params, paramTypes); // actually make sure the catalog records this is a different kind of procedure procedure.setTransactional(false); // put the compiled code for this procedure into the jarfile // need to find the outermost ancestor class for the procedure in the event // that it's actually an inner (or inner inner...) class. // addClassToJar recursively adds all the children, which should include this // class Class<?> ancestor = procClass; while (ancestor.getEnclosingClass() != null) { ancestor = ancestor.getEnclosingClass(); } compiler.addClassToJar(jarOutput, ancestor); } private static void setCatalogProcedureParameterTypes(VoltCompiler compiler, String shortName, CatalogMap<ProcParameter> params, Class<?>[] paramTypes) throws VoltCompilerException { for (int i = 0; i < paramTypes.length; i++) { Class<?> cls = paramTypes[i]; ProcParameter param = params.add(String.valueOf(i)); param.setIndex(i); // handle the case where the param is an array if (cls.isArray()) { param.setIsarray(true); cls = cls.getComponentType(); } else param.setIsarray(false); // boxed types are not supported parameters at this time if ((cls == Long.class) || (cls == Integer.class) || (cls == Short.class) || (cls == Byte.class) || (cls == Double.class) || (cls == Character.class) || (cls == Boolean.class)) { String msg = "Procedure: " + shortName + " has a parameter with a boxed type: "; msg += cls.getSimpleName(); msg += ". Replace this parameter with the corresponding primitive type and the procedure may compile."; throw compiler.new VoltCompilerException(msg); } else if ((cls == Float.class) || (cls == float.class)) { String msg = "Procedure: " + shortName + " has a parameter with type: "; msg += cls.getSimpleName(); msg += ". Replace this parameter type with double and the procedure may compile."; throw compiler.new VoltCompilerException(msg); } VoltType type; try { type = VoltType.typeFromClass(cls); } catch (VoltTypeException e) { // handle the case where the type is invalid String msg = "Procedure: " + shortName + " has a parameter with invalid type: "; msg += cls.getSimpleName(); throw compiler.new VoltCompilerException(msg); } catch (RuntimeException e) { String msg = "Procedure: " + shortName + " unexpectedly failed a check on a parameter of type: "; msg += cls.getSimpleName(); msg += " with error: "; msg += e.toString(); throw compiler.new VoltCompilerException(msg); } param.setType(type.getValue()); } } public static void checkForDeterminismWarnings(VoltCompiler compiler, String shortName, final Procedure procedure, boolean procHasWriteStmts) { for (Statement catalogStmt : procedure.getStatements()) { if (catalogStmt.getIscontentdeterministic() == false) { String potentialErrMsg = "Procedure " + shortName + " has a statement with a non-deterministic result - statement: \"" + catalogStmt.getSqltext() + "\" , reason: " + catalogStmt.getNondeterminismdetail(); compiler.addWarn(potentialErrMsg); } else if (catalogStmt.getIsorderdeterministic() == false) { String warnMsg; if (procHasWriteStmts) { String rwPotentialErrMsg = "Procedure " + shortName + " is RW and has a statement whose result has a non-deterministic ordering - statement: \"" + catalogStmt.getSqltext() + "\", reason: " + catalogStmt.getNondeterminismdetail(); warnMsg = rwPotentialErrMsg; } else { warnMsg = "Procedure " + shortName + " has a statement with a non-deterministic result - statement: \"" + catalogStmt.getSqltext() + "\", reason: " + catalogStmt.getNondeterminismdetail(); } compiler.addWarn(warnMsg); } } } static void compileSingleStmtProcedure(VoltCompiler compiler, HSQLInterface hsql, DatabaseEstimates estimates, Database db, ProcedureDescriptor procedureDescriptor) throws VoltCompiler.VoltCompilerException { final String className = procedureDescriptor.m_className; if (className.indexOf('@') != -1) { throw compiler.new VoltCompilerException("User procedure names can't contain \"@\"."); } // if there are multiple statements, // the string of statements will begin and end with single quotes // but all the statements are stored in m_singleStmt as a single string String stmtsStr = procedureDescriptor.m_singleStmt; if( stmtsStr.charAt(0) == '\'' && stmtsStr.charAt(stmtsStr.length()-2) == '\'' ) { stmtsStr = stmtsStr.substring(1, stmtsStr.length()-2); } // get the short name of the class (no package if a user procedure) // use the Table.<builtin> name (allowing the period) if builtin. String shortName = className; if (procedureDescriptor.m_builtInStmt == false) { String[] parts = className.split("\\."); shortName = parts[parts.length - 1]; } // add an entry to the catalog (using the full className) final Procedure procedure = db.getProcedures().add(shortName); for (String groupName : procedureDescriptor.m_authGroups) { final Group group = db.getGroups().get(groupName); if (group == null) { throw compiler.new VoltCompilerException("Procedure " + className + " allows access by a role " + groupName + " that does not exist"); } final GroupRef groupRef = procedure.getAuthgroups().add(groupName); groupRef.setGroup(group); } procedure.setClassname(className); // sysprocs don't use the procedure compiler procedure.setSystemproc(false); procedure.setDefaultproc(procedureDescriptor.m_builtInStmt); procedure.setHasjava(false); procedure.setTransactional(true); // get the annotation // first try to get one that has been passed from the compiler ProcInfoData info = compiler.getProcInfoOverride(shortName); // then check for the usual one in the class itself // and create a ProcInfo.Data instance for it if (info == null) { info = new ProcInfoData(); if (procedureDescriptor.m_partitionString != null) { info.partitionInfo = procedureDescriptor.m_partitionString; info.singlePartition = true; } } assert(info != null); // TODO: parse the statements in the proc and have a loop for the code below for each stmt String[] stmts = stmtsStr.split(";"); //String curStmt = stmts[0]; // ADD THE STATEMENT int stmtNum = 0; for (String curStmt: stmts) { // add the statement to the catalog Statement catalogStmt = procedure.getStatements().add(VoltDB.ANON_STMT_NAME + String.valueOf(stmtNum++)); // Statement catalogStmt = procedure.getStatements().add(VoltDB.ANON_STMT_NAME); // compile the statement StatementPartitioning partitioning = info.singlePartition ? StatementPartitioning.forceSP() : StatementPartitioning.forceMP(); // default to FASTER detmode because stmt procs can't feed read output into writes StatementCompiler.compileFromSqlTextAndUpdateCatalog(compiler, hsql, db, estimates, catalogStmt, curStmt,//procedureDescriptor.m_singleStmt, procedureDescriptor.m_joinOrder, DeterminismMode.FASTER, partitioning); // if the single stmt is not read only, then the proc is not read only boolean procHasWriteStmts = (catalogStmt.getReadonly() == false); // set the read onlyness of a proc procedure.setReadonly(procHasWriteStmts == false); int seqs = catalogStmt.getSeqscancount(); procedure.setHasseqscans(seqs > 0); // set procedure parameter types CatalogMap<ProcParameter> params = procedure.getParameters(); CatalogMap<StmtParameter> stmtParams = catalogStmt.getParameters(); // set the procedure parameter types from the statement parameter types // int paramCount = 0; int paramCount = params.size(); for (StmtParameter stmtParam : CatalogUtil.getSortedCatalogItems(stmtParams, "index")) { // name each parameter "param1", "param2", etc... ProcParameter procParam = params.add("param" + String.valueOf(paramCount)); // procParam.setIndex(stmtParam.getIndex() + paramCount); procParam.setIndex(paramCount); procParam.setIsarray(stmtParam.getIsarray()); procParam.setType(stmtParam.getJavatype()); paramCount++; } // parse the procinfo procedure.setSinglepartition(info.singlePartition); if (info.singlePartition) { parsePartitionInfo(compiler, db, procedure, info.partitionInfo); if (procedure.getPartitionparameter() >= params.size()) { String msg = "PartitionInfo parameter not a valid parameter for procedure: " + procedure.getClassname(); throw compiler.new VoltCompilerException(msg); } // TODO: The planner does not currently validate that a single-statement plan declared as single-partition correctly uses // the designated parameter as a partitioning filter, maybe some day. // In theory, the PartitioningForStatement would confirm the use of (only) a parameter as a partition key -- // or if the partition key was determined to be some other hard-coded constant (expression?) it might display a warning // message that the passed parameter is assumed to be equal to that constant (expression). } else { if (partitioning.getCountOfIndependentlyPartitionedTables() == 1) { AbstractExpression statementPartitionExpression = partitioning.singlePartitioningExpressionForReport(); if (statementPartitionExpression != null) { // The planner has uncovered an overlooked opportunity to run the statement SP. String msg = "This procedure " + shortName + " would benefit from being partitioned, by "; String tableName = "tableName", partitionColumnName = "partitionColumnName"; try { assert(partitioning.getFullColumnName() != null); String array[] = partitioning.getFullColumnName().split("\\."); tableName = array[0]; partitionColumnName = array[1]; } catch(Exception ex) { } if (statementPartitionExpression instanceof ParameterValueExpression) { paramCount = ((ParameterValueExpression) statementPartitionExpression).getParameterIndex(); } else { String valueDescription = null; Object partitionValue = partitioning.getInferredPartitioningValue(); if (partitionValue == null) { // Statement partitioned on a runtime constant. This is likely to be cryptic, but hopefully gets the idea across. valueDescription = "of " + statementPartitionExpression.explain(""); } else { valueDescription = partitionValue.toString(); // A simple constant value COULD have been a parameter. } msg += "adding a parameter to be passed the value " + valueDescription + " and "; } msg += "adding a 'PARTITION ON TABLE " + tableName + " COLUMN " + partitionColumnName + " PARAMETER " + paramCount + "' clause to the " + "CREATE PROCEDURE statement. or using a separate PARTITION PROCEDURE statement"; compiler.addWarn(msg); } } } } } /** * Determine which parameter is the partition indicator */ public static void parsePartitionInfo(VoltCompiler compiler, Database db, Procedure procedure, String info) throws VoltCompilerException { assert(procedure.getSinglepartition() == true); // check this isn't empty if (info.length() == 0) { String msg = "Missing or Truncated PartitionInfo in attribute for procedure: " + procedure.getClassname(); throw compiler.new VoltCompilerException(msg); } // split on the colon String[] parts = info.split(":"); // if the colon doesn't split well, we have a problem if (parts.length != 2) { String msg = "Possibly invalid PartitionInfo in attribute for procedure: " + procedure.getClassname(); throw compiler.new VoltCompilerException(msg); } // relabel the parts for code readability String columnInfo = parts[0].trim(); int paramIndex = Integer.parseInt(parts[1].trim()); int paramCount = procedure.getParameters().size(); if ((paramIndex < 0) || (paramIndex >= paramCount)) { String msg = "PartitionInfo specifies invalid parameter index for procedure: " + procedure.getClassname(); throw compiler.new VoltCompilerException(msg); } // locate the parameter procedure.setPartitionparameter(paramIndex); // split the columninfo parts = columnInfo.split("\\."); if (parts.length != 2) { String msg = "Possibly invalid PartitionInfo " + info + " in attribute for procedure: " + procedure.getClassname(); throw compiler.new VoltCompilerException(msg); } // relabel the parts for code readability String tableName = parts[0].trim(); String columnName = parts[1].trim(); // locate the partition column CatalogMap<Table> tables = db.getTables(); for (Table table : tables) { if (table.getTypeName().equalsIgnoreCase(tableName)) { CatalogMap<Column> columns = table.getColumns(); Column partitionColumn = table.getPartitioncolumn(); if (partitionColumn == null) { String msg = String.format("PartitionInfo for procedure %s references table %s which has no partition column (may be replicated).", procedure.getClassname(), table.getTypeName()); throw compiler.new VoltCompilerException(msg); } for (Column column : columns) { if (column.getTypeName().equalsIgnoreCase(columnName)) { if (partitionColumn.getTypeName().equals(column.getTypeName())) { procedure.setPartitioncolumn(column); procedure.setPartitiontable(table); return; } else { String msg = "PartitionInfo for procedure " + procedure.getClassname() + " refers to a column in schema which is not a partition key."; throw compiler.new VoltCompilerException(msg); } } } } } String msg = "PartitionInfo for procedure " + procedure.getClassname() + " refers to a column in schema which can't be found."; throw compiler.new VoltCompilerException(msg); } }
import java.io.FileNotFoundException; import java.util.Scanner; public class Utils { public static Scanner sc = new Scanner(System.in); public static Trans getTransFromInput() { Types type; double km; int yom; int aveLife; String vin; int wheels; boolean hitch; boolean people; System.out.print("Enter vehicle type:"); type = Types.fromString(sc.next()); System.out.print("Enter number of km traveled:"); km = sc.nextDouble(); System.out.print("Enter year of manufacture:"); yom = sc.nextInt(); System.out.print("Enter average life:"); aveLife = sc.nextInt(); System.out.print("Enter VIN:"); vin = sc.next(); System.out.print("Enter number of wheels:"); wheels = sc.nextInt(); System.out.print("Does the vehicle have hitch?:"); hitch = sc.next().startsWith("y"); System.out.print("Does the vehicle carry people?:"); people = sc.next().startsWith("y"); return new Trans(type, km, yom, aveLife, vin, wheels, hitch, people); } public static void printMenu(){ System.out.println("1 add "); System.out.println("2 delete "); System.out.println("3 print "); System.out.println("4 sort "); System.out.println("5 to exit"); } public static void chooseMenu(int op) throws FileNotFoundException { switch (op) { case 1: addCar(); break; case 2: delCar(); break; case 3: printCars(); break; case 4: sort(); break; } } public static void printCars() { Main.CARN = 1; for (int n = 0; n < Main.ARR.size(); n++) { System.out.format("%2d. " + Main.ARR.get(n).toString(), Main.CARN); System.out.println(); Main.CARN++; } } public static void addCar() { try { Main.ARR.add(getTransFromInput()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void delCar() { System.out.println("Enter index of car to delete"); Main.ARR.remove(sc.nextInt() - 1); } public static void sort() { System.out.println("Enter parameter to sort by(type, wheels, km)"); switch (sc.next().toLowerCase()) { case "type": Main.ARR.sort(new Trans.SorterbyType()); break; case "wheels": Main.ARR.sort(new Trans.SorterbyWheels()); break; case "km": Main.ARR.sort(new Trans.SorterbyKm()); break; } } }
package garin.artemiy.quickaction.example; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.RelativeLayout; import garin.artemiy.quickaction.R; import garin.artemiy.quickaction.library.QuickAction; public class MainActivity extends Activity { private QuickAction quickAction; @SuppressWarnings("InflateParams") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_layout); RelativeLayout customLayout = (RelativeLayout) getLayoutInflater().inflate(R.layout.popup_custom_layout, null); quickAction = new QuickAction (this, R.style.PopupAnimation, customLayout, customLayout); } @SuppressWarnings("unused") public void onClickTopButton(View view) { quickAction.show(view); } @SuppressWarnings("unused") public void onClickMiddleButton(View view) { quickAction.show(view); } @SuppressWarnings("unused") public void onClickBottomButton(View view) { quickAction.show(view); } }
package hu.gaborkolozsy.dictionary.model; import java.util.HashMap; import java.util.Map; import java.util.Set; public class DictionaryBox { /** * DictionaryBox map. */ private final Map<String, String> dictionary = new HashMap<>(); /** * Put the key-value paar in the dictionary. * @param key the key * @param value the value */ public void put(String key, String value) { dictionary.put(key, value); } /** * Return true if dictionary is empty. * @return <b>true</b> if dictionary is empty <b>false</b> otherwise */ public boolean isEmpty() { return dictionary.isEmpty(); } /** * Clear dictionary. */ public void clear() { dictionary.clear(); } /** * Return the key set. * @return the dictionary's key set */ public Set getKeySet() { return dictionary.keySet(); } /** * Return the value by specified key. * @param key the specified key * @return value */ public String getValue(String key) { return dictionary.get(key); } /** * Return the size of {@code dictionary} data member. * @return {@code dictionary} size */ public int getSize() { return dictionary.size(); } }
package ibis.satin.impl.faultTolerance; import ibis.ipl.IbisIdentifier; import ibis.ipl.ReadMessage; import ibis.ipl.ReceivePort; import ibis.ipl.ReceivePortConnectUpcall; import ibis.ipl.ReceivePortIdentifier; import ibis.ipl.Registry; import ibis.ipl.ResizeHandler; import ibis.ipl.SendPort; import ibis.ipl.SendPortConnectUpcall; import ibis.ipl.SendPortIdentifier; import ibis.ipl.StaticProperties; import ibis.ipl.WriteMessage; import ibis.satin.impl.Config; import ibis.satin.impl.Satin; import ibis.satin.impl.communication.Protocol; import ibis.satin.impl.loadBalancing.Victim; import ibis.satin.impl.spawnSync.InvocationRecord; import ibis.satin.impl.spawnSync.ReturnRecord; import ibis.satin.impl.spawnSync.Stamp; import ibis.util.Timer; import java.io.IOException; import java.util.Map; final class FTCommunication implements Config, ReceivePortConnectUpcall, SendPortConnectUpcall, ResizeHandler { private Satin s; private JoinThread joinThread; private boolean connectionUpcallsDisabled = false; protected FTCommunication(Satin s) { this.s = s; } protected void init(StaticProperties requestedProperties) { try { electClusterCoordinator(); } catch (Exception e) { ftLogger.fatal("SATIN '" + s.ident + "': Could not start ibis: " + e, e); System.exit(1); // Could not start ibis } } protected void electClusterCoordinator() throws ClassNotFoundException, IOException { Registry r = s.comm.ibis.registry(); s.ft.clusterCoordinatorIdent = r.elect("satin " + s.comm.ibis.identifier().cluster() + " cluster coordinator"); if (s.ft.clusterCoordinatorIdent.equals(s.comm.ibis.identifier())) { /* I am the cluster coordinator */ s.clusterCoordinator = true; ftLogger.info("cluster coordinator for cluster " + s.comm.ibis.identifier().cluster() + " is " + s.ft.clusterCoordinatorIdent); } } /** * If the job is being redone (redone flag is * set to true), perform a lookup in the global result table. * The lookup might fail if the result is thrown away for some reason, or * if the node that stored the result has crashed. * * @param r * invocation record of the job * @return true if an entry was found, false otherwise */ protected boolean askForJobResult(InvocationRecord r) { GlobalResultTableValue value = null; synchronized (s) { value = s.ft.globalResultTable.lookup(r.getStamp()); } if (value == null) return false; if (value.type == GlobalResultTableValue.TYPE_POINTER) { //remote result Victim v = null; synchronized (s) { if (s.deadIbises.contains(value.owner)) { //the one who's got the result has crashed return false; } grtLogger.debug("SATIN '" + s.ident + "': sending a result request of " + r.getStamp() + " to " + value.owner); v = s.victims.getVictim(value.owner); if (v == null) return false; // victim has probably crashed //put the job in the stolen jobs list. r.setStealer(value.owner); s.lb.addToOutstandingJobList(r); } // send a request to the remote node try { WriteMessage m = v.newMessage(); m.writeByte(Protocol.RESULT_REQUEST); m.writeObject(r.getStamp()); m.finish(); } catch (IOException e) { grtLogger.warn("SATIN '" + s.ident + "': trying to send RESULT_REQUEST but got " + "exception: " + e, e); synchronized (s) { s.outstandingJobs.remove(r); } return false; } return true; } if (value.type == GlobalResultTableValue.TYPE_RESULT) { // local result, handle normally ReturnRecord rr = value.result; rr.assignTo(r); r.decrSpawnCounter(); return true; } return false; } protected void sendAbortAndStoreMessage(InvocationRecord r) { Satin.assertLocked(s); abortLogger.debug("SATIN '" + s.ident + ": sending abort and store message to: " + r.getStealer() + " for job " + r.getStamp()); if (s.deadIbises.contains(r.getStealer())) { /* don't send abort and store messages to crashed ibises */ return; } try { Victim v = s.victims.getVictim(r.getStealer()); if (v == null) return; // probably crashed WriteMessage writeMessage = v.newMessage(); writeMessage.writeByte(Protocol.ABORT_AND_STORE); writeMessage.writeObject(r.getParentStamp()); long cnt = writeMessage.finish(); if (s.comm.inDifferentCluster(r.getStealer())) { s.stats.interClusterMessages++; s.stats.interClusterBytes += cnt; } else { s.stats.intraClusterMessages++; s.stats.intraClusterBytes += cnt; } } catch (IOException e) { ftLogger.warn("SATIN '" + s.ident + "': Got Exception while sending abort message: " + e); // This should not be a real problem, it is just inefficient. // Let's continue... } } // connect upcall functions public boolean gotConnection(ReceivePort me, SendPortIdentifier applicant) { // accept all connections return true; } protected void handleLostConnection(IbisIdentifier dead) { Victim v = null; synchronized (s) { if (s.deadIbises.contains(dead)) return; s.ft.crashedIbises.add(dead); s.deadIbises.add(dead); if (dead.equals(s.lb.getCurrentVictim())) { s.currentVictimCrashed = true; s.lb.setCurrentVictim(null); } s.ft.gotCrashes = true; v = s.victims.remove(dead); s.notifyAll(); } if (v != null) { v.close(); } } public void lostConnection(ReceivePort me, SendPortIdentifier johnDoe, Exception reason) { ftLogger.debug("SATIN '" + s.ident + "': got lostConnection upcall: " + johnDoe.ibis() + ", reason = " + reason); if (connectionUpcallsDisabled) { return; } handleLostConnection(johnDoe.ibis()); } public void lostConnection(SendPort me, ReceivePortIdentifier johnDoe, Exception reason) { ftLogger.debug("SATIN '" + s.ident + "': got SENDPORT lostConnection upcall: " + johnDoe.ibis()); if (connectionUpcallsDisabled) { return; } handleLostConnection(johnDoe.ibis()); } /** The ibis upcall that is called whenever a node joins the computation */ public void joined(IbisIdentifier joiner) { ftLogger.debug("SATIN '" + s.ident + "': got join of " + joiner); if (joinThread == null) { joinThread = new JoinThread(s); joinThread.start(); } joinThread.addJoiner(joiner); } public void died(IbisIdentifier corpse) { ftLogger.debug("SATIN '" + s.ident + "': " + corpse + " died"); left(corpse); handleLostConnection(corpse); } public void left(IbisIdentifier leaver) { if (leaver.equals(s.ident)) return; ftLogger.debug("SATIN '" + s.ident + "': " + leaver + " left"); Victim v; synchronized (s) { // master and cluster coordinators will be reelected // only if their crash was confirmed by the nameserver if (leaver.equals(s.masterIdent)) { s.ft.masterHasCrashed = true; s.ft.gotCrashes = true; } if (leaver.equals(s.ft.clusterCoordinatorIdent)) { s.ft.clusterCoordinatorHasCrashed = true; s.ft.gotCrashes = true; } s.so.removeSOConnection(leaver); v = s.victims.remove(leaver); s.notifyAll(); } if (v != null) { v.close(); } } public void mustLeave(IbisIdentifier[] ids) { for (int i = 0; i < ids.length; i++) { if (s.ident.equals(ids[i])) { s.ft.gotDelete = true; break; } } } protected void handleJoins(IbisIdentifier[] joiners) { String[] names = new String[joiners.length]; for (int i = 0; i < names.length; i++) { names[i] = "satin port on " + joiners[i].name(); } ftLogger.debug("SATIN '" + s.ident + "': dealing with " + names.length + " joins"); s.so.createSoPorts(joiners); ReceivePortIdentifier[] r = null; try { r = s.comm.lookup(names); } catch (Exception e) { ftLogger.warn("SATIN '" + s.ident + "': got an exception while looking up receive ports", e); return; } ftLogger.debug("SATIN '" + s.ident + "': lookups succeeded"); for (int i = 0; i < r.length; i++) { IbisIdentifier joiner = joiners[i]; ftLogger.debug("SATIN '" + s.ident + "': creating sendport"); SendPort p = null; try { p = s.comm.portType.createSendPort("satin sendport"); } catch (Exception e) { ftLogger.warn("SATIN '" + s.ident + "': got an exception in Satin.join", e); continue; } ftLogger.debug("SATIN '" + s.ident + "': creating sendport done"); ftLogger.debug("SATIN '" + s.ident + "': creating SO connections"); s.so.addSOConnection(joiner); ftLogger.debug("SATIN '" + s.ident + "': creating SO connections done"); if (!FT_NAIVE) { s.ft.globalResultTable.addReplica(joiner); } synchronized (s) { s.victims.add(new Victim(joiner, p, r[i])); s.notifyAll(); } ftLogger.debug("SATIN '" + s.ident + "': " + joiner + " JOINED"); } } protected void handleAbortAndStore(ReadMessage m) { try { Stamp stamp = (Stamp) m.readObject(); synchronized (s) { s.ft.addToAbortAndStoreList(stamp); } // m.finish(); } catch (Exception e) { grtLogger.error("SATIN '" + s.ident + "': got exception while reading abort_and_store: " + e, e); } } protected void handleResultRequest(ReadMessage m) { Victim v = null; GlobalResultTableValue value = null; Timer handleLookupTimer = null; try { handleLookupTimer = Timer.createTimer(); handleLookupTimer.start(); Stamp stamp = (Stamp) m.readObject(); IbisIdentifier ident = m.origin().ibis(); m.finish(); synchronized (s) { value = s.ft.globalResultTable.lookup(stamp); if (value == null && ASSERTS) { grtLogger.fatal("SATIN '" + s.ident + "': EEK!!! no requested result in the table: " + stamp); System.exit(1); // Failed assertion } if (value.type == GlobalResultTableValue.TYPE_POINTER && ASSERTS) { grtLogger.fatal("SATIN '" + s.ident + "': EEK!!! " + ident + " requested a result: " + stamp + " which is stored on another node: " + value); System.exit(1); // Failed assertion } v = s.victims.getVictim(ident); } if (v == null) { ftLogger.debug("SATIN '" + s.ident + "': the node requesting a result died"); handleLookupTimer.stop(); s.stats.handleLookupTimer.add(handleLookupTimer); return; } value.result.setStamp(stamp); WriteMessage w = v.newMessage(); w.writeByte(Protocol.JOB_RESULT_NORMAL); w.writeObject(value.result); w.finish(); } catch (Exception e) { grtLogger.error("SATIN '" + s.ident + "': trying to send result back, but got exception: " + e, e); } handleLookupTimer.stop(); s.stats.handleLookupTimer.add(handleLookupTimer); } protected void handleResultPush(ReadMessage m) { grtLogger.info("SATIN '" + s.ident + ": handle result push"); try { Map results = (Map) m.readObject(); synchronized (s) { s.ft.globalResultTable.updateAll(results); } } catch (Exception e) { grtLogger.error("SATIN '" + s.ident + "': trying to read result push, but got exception: " + e, e); } grtLogger.info("SATIN '" + s.ident + ": handle result push finished"); } protected void disableConnectionUpcalls() { connectionUpcallsDisabled = true; } protected void pushResults(Victim victim, Map toPush) { if (toPush.size() == 0) return; try { WriteMessage m = victim.newMessage(); m.writeByte(Protocol.RESULT_PUSH); m.writeObject(toPush); long numBytes = m.finish(); grtLogger.debug("SATIN '" + s.ident + "': " + numBytes + " bytes pushed"); } catch (IOException e) { grtLogger.info("SATIN '" + s.ident + "': error pushing results " + e); } } }
package org.apache.jmeter.control.gui; import java.awt.Font; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; import org.apache.jmeter.control.GenericController; import org.apache.jmeter.testelement.TestElement; import org.apache.jmeter.util.JMeterUtils; import org.apache.jorphan.gui.layout.VerticalLayout; public class LogicControllerGui extends AbstractControllerGui { public LogicControllerGui() { init(); } public TestElement createTestElement() { GenericController lc = new GenericController(); configureTestElement(lc); return lc; } /** * Modifies a given TestElement to mirror the data in the gui components. * @see org.apache.jmeter.gui.JMeterGUIComponent#modifyTestElement(TestElement) */ public void modifyTestElement(TestElement el) { configureTestElement(el); } public String getStaticLabel() { return JMeterUtils.getResString("logic_controller_title"); } public void updateGui() { } private void init() { this.setLayout(new VerticalLayout(5, VerticalLayout.LEFT, VerticalLayout.TOP)); // MAIN PANEL JPanel mainPanel = new JPanel(); Border margin = new EmptyBorder(10, 10, 5, 10); mainPanel.setBorder(margin); mainPanel.setLayout(new VerticalLayout(5, VerticalLayout.LEFT)); // TITLE JLabel panelTitleLabel = new JLabel(JMeterUtils.getResString("logic_controller_title")); Font curFont = panelTitleLabel.getFont(); int curFontSize = curFont.getSize(); curFontSize += 4; panelTitleLabel.setFont(new Font(curFont.getFontName(), curFont.getStyle(), curFontSize)); mainPanel.add(panelTitleLabel); // NAME mainPanel.add(getNamePanel()); this.add(mainPanel); } }
package de.danoeh.antennapod.fragment; import org.apache.commons.lang3.StringEscapeUtils; import android.annotation.SuppressLint; import android.app.Activity; import android.content.ClipData; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.TypedArray; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.util.TypedValue; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.webkit.WebSettings.LayoutAlgorithm; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; import com.actionbarsherlock.app.SherlockFragment; import de.danoeh.antennapod.AppConfig; import de.danoeh.antennapod.PodcastApp; import de.danoeh.antennapod.R; import de.danoeh.antennapod.feed.FeedItem; import de.danoeh.antennapod.feed.FeedManager; import de.danoeh.antennapod.preferences.UserPreferences; import de.danoeh.antennapod.util.ShareUtils; import de.danoeh.antennapod.util.playback.Playable; /** Displays the description of a Playable object in a Webview. */ public class ItemDescriptionFragment extends SherlockFragment { private static final String TAG = "ItemDescriptionFragment"; private static final String PREF = "ItemDescriptionFragmentPrefs"; private static final String PREF_SCROLL_Y = "prefScrollY"; private static final String PREF_PLAYABLE_ID = "prefPlayableId"; private static final String ARG_PLAYABLE = "arg.playable"; private static final String ARG_FEED_ID = "arg.feedId"; private static final String ARG_FEED_ITEM_ID = "arg.feeditemId"; private static final String ARG_SAVE_STATE = "arg.saveState"; private WebView webvDescription; private Playable media; private FeedItem item; private AsyncTask<Void, Void, Void> webViewLoader; private String shownotes; /** URL that was selected via long-press. */ private String selectedURL; /** * True if Fragment should save its state (e.g. scrolling position) in a * shared preference. */ private boolean saveState; public static ItemDescriptionFragment newInstance(Playable media, boolean saveState) { ItemDescriptionFragment f = new ItemDescriptionFragment(); Bundle args = new Bundle(); args.putParcelable(ARG_PLAYABLE, media); args.putBoolean(ARG_SAVE_STATE, saveState); f.setArguments(args); return f; } public static ItemDescriptionFragment newInstance(FeedItem item, boolean saveState) { ItemDescriptionFragment f = new ItemDescriptionFragment(); Bundle args = new Bundle(); args.putLong(ARG_FEED_ID, item.getFeed().getId()); args.putLong(ARG_FEED_ITEM_ID, item.getId()); args.putBoolean(ARG_SAVE_STATE, saveState); f.setArguments(args); return f; } @SuppressLint("NewApi") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (AppConfig.DEBUG) Log.d(TAG, "Creating view"); webvDescription = new WebView(getActivity()); if (UserPreferences.getTheme() == R.style.Theme_AntennaPod_Dark) { if (Build.VERSION.SDK_INT >= 11 && Build.VERSION.SDK_INT <= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { webvDescription.setLayerType(View.LAYER_TYPE_SOFTWARE, null); } webvDescription.setBackgroundColor(getResources().getColor( R.color.black)); } webvDescription.getSettings().setUseWideViewPort(false); webvDescription.getSettings().setLayoutAlgorithm( LayoutAlgorithm.NARROW_COLUMNS); webvDescription.getSettings().setLoadWithOverviewMode(true); webvDescription.setOnLongClickListener(webViewLongClickListener); webvDescription.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); return true; } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if (AppConfig.DEBUG) Log.d(TAG, "Page finished"); // Restoring the scroll position might not always work view.postDelayed(new Runnable() { @Override public void run() { restoreFromPreference(); } }, 50); } }); registerForContextMenu(webvDescription); return webvDescription; } @Override public void onDestroyView() { super.onDestroyView(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (AppConfig.DEBUG) Log.d(TAG, "Fragment attached"); } @Override public void onDetach() { super.onDetach(); if (AppConfig.DEBUG) Log.d(TAG, "Fragment detached"); if (webViewLoader != null) { webViewLoader.cancel(true); } } @Override public void onDestroy() { super.onDestroy(); if (AppConfig.DEBUG) Log.d(TAG, "Fragment destroyed"); if (webViewLoader != null) { webViewLoader.cancel(true); } } @SuppressLint("NewApi") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (AppConfig.DEBUG) Log.d(TAG, "Creating fragment"); Bundle args = getArguments(); saveState = args.getBoolean(ARG_SAVE_STATE, false); if (args.containsKey(ARG_PLAYABLE)) { media = args.getParcelable(ARG_PLAYABLE); } else if (args.containsKey(ARG_FEED_ID) && args.containsKey(ARG_FEED_ITEM_ID)) { long feedId = args.getLong(ARG_FEED_ID); long itemId = args.getLong(ARG_FEED_ITEM_ID); FeedItem f = FeedManager.getInstance().getFeedItem(itemId, feedId); if (f != null) { item = f; } } } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); if (media != null) { media.loadShownotes(new Playable.ShownoteLoaderCallback() { @Override public void onShownotesLoaded(String shownotes) { ItemDescriptionFragment.this.shownotes = shownotes; if (ItemDescriptionFragment.this.shownotes != null) { startLoader(); } } }); } else if (item != null) { if (item.getDescription() == null || item.getContentEncoded() == null) { FeedManager.getInstance().loadExtraInformationOfItem( PodcastApp.getInstance(), item, new FeedManager.TaskCallback<String[]>() { @Override public void onCompletion(String[] result) { if (result[1] != null) { shownotes = result[1]; } else { shownotes = result[0]; } if (shownotes != null) { startLoader(); } } }); } else { shownotes = item.getContentEncoded(); startLoader(); } } else { Log.e(TAG, "Error in onViewCreated: Item and media were null"); } } @Override public void onResume() { super.onResume(); } @SuppressLint("NewApi") private void startLoader() { webViewLoader = createLoader(); if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.GINGERBREAD_MR1) { webViewLoader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else { webViewLoader.execute(); } } /** * Return the CSS style of the Webview. * * @param textColor * the default color to use for the text in the webview. This * value is inserted directly into the CSS String. * */ private String applyWebviewStyle(String textColor, String data) { final String WEBVIEW_STYLE = "<html><head><style type=\"text/css\"> * { color: %s; font-family: Helvetica; line-height: 1.5em; font-size: 11pt; } a { font-style: normal; text-decoration: none; font-weight: normal; color: #00A8DF; } img { display: block; margin: 10 auto; max-width: %s; height: auto; } body { margin: %dpx %dpx %dpx %dpx; }</style></head><body>%s</body></html>"; final int pageMargin = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 8, getResources() .getDisplayMetrics()); return String.format(WEBVIEW_STYLE, textColor, "100%", pageMargin, pageMargin, pageMargin, pageMargin, data); } private View.OnLongClickListener webViewLongClickListener = new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { WebView.HitTestResult r = webvDescription.getHitTestResult(); if (r != null && r.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE) { if (AppConfig.DEBUG) Log.d(TAG, "Link of webview was long-pressed. Extra: " + r.getExtra()); selectedURL = r.getExtra(); webvDescription.showContextMenu(); return true; } selectedURL = null; return false; } }; @SuppressWarnings("deprecation") @SuppressLint("NewApi") @Override public boolean onContextItemSelected(MenuItem item) { boolean handled = selectedURL != null; if (selectedURL != null) { switch (item.getItemId()) { case R.id.open_in_browser_item: Uri uri = Uri.parse(selectedURL); getActivity() .startActivity(new Intent(Intent.ACTION_VIEW, uri)); break; case R.id.share_url_item: ShareUtils.shareLink(getActivity(), selectedURL); break; case R.id.copy_url_item: if (android.os.Build.VERSION.SDK_INT >= 11) { ClipData clipData = ClipData.newPlainText(selectedURL, selectedURL); android.content.ClipboardManager cm = (android.content.ClipboardManager) getActivity() .getSystemService(Context.CLIPBOARD_SERVICE); cm.setPrimaryClip(clipData); } else { android.text.ClipboardManager cm = (android.text.ClipboardManager) getActivity() .getSystemService(Context.CLIPBOARD_SERVICE); cm.setText(selectedURL); } Toast t = Toast.makeText(getActivity(), R.string.copied_url_msg, Toast.LENGTH_SHORT); t.show(); break; default: handled = false; break; } selectedURL = null; } return handled; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { if (selectedURL != null) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(Menu.NONE, R.id.open_in_browser_item, Menu.NONE, R.string.open_in_browser_label); menu.add(Menu.NONE, R.id.copy_url_item, Menu.NONE, R.string.copy_url_label); menu.add(Menu.NONE, R.id.share_url_item, Menu.NONE, R.string.share_url_label); menu.setHeaderTitle(selectedURL); } } private AsyncTask<Void, Void, Void> createLoader() { return new AsyncTask<Void, Void, Void>() { @Override protected void onCancelled() { super.onCancelled(); if (getSherlockActivity() != null) { getSherlockActivity() .setSupportProgressBarIndeterminateVisibility(false); } webViewLoader = null; } String data; @Override protected void onPostExecute(Void result) { super.onPostExecute(result); // /webvDescription.loadData(url, "text/html", "utf-8"); webvDescription.loadDataWithBaseURL(null, data, "text/html", "utf-8", "about:blank"); if (getSherlockActivity() != null) { getSherlockActivity() .setSupportProgressBarIndeterminateVisibility(false); } if (AppConfig.DEBUG) Log.d(TAG, "Webview loaded"); webViewLoader = null; } @Override protected void onPreExecute() { super.onPreExecute(); if (getSherlockActivity() != null) { getSherlockActivity() .setSupportProgressBarIndeterminateVisibility(true); } } @Override protected Void doInBackground(Void... params) { if (AppConfig.DEBUG) Log.d(TAG, "Loading Webview"); data = ""; data = StringEscapeUtils.unescapeHtml4(shownotes); Activity activity = getActivity(); if (activity != null) { TypedArray res = getActivity() .getTheme() .obtainStyledAttributes( new int[] { android.R.attr.textColorPrimary }); int colorResource = res.getColor(0, 0); String colorString = String.format("#%06X", 0xFFFFFF & colorResource); Log.i(TAG, "text color: " + colorString); res.recycle(); data = applyWebviewStyle(colorString, data); } else { cancel(true); } return null; } }; } @Override public void onPause() { super.onPause(); savePreference(); } private void savePreference() { if (saveState) { if (AppConfig.DEBUG) Log.d(TAG, "Saving preferences"); SharedPreferences prefs = getActivity().getSharedPreferences(PREF, Activity.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); if (media != null && webvDescription != null) { if (AppConfig.DEBUG) Log.d(TAG, "Saving scroll position: " + webvDescription.getScrollY()); editor.putInt(PREF_SCROLL_Y, webvDescription.getScrollY()); editor.putString(PREF_PLAYABLE_ID, media.getIdentifier() .toString()); } else { if (AppConfig.DEBUG) Log.d(TAG, "savePreferences was called while media or webview was null"); editor.putInt(PREF_SCROLL_Y, -1); editor.putString(PREF_PLAYABLE_ID, ""); } editor.commit(); } } private boolean restoreFromPreference() { if (saveState) { if (AppConfig.DEBUG) Log.d(TAG, "Restoring from preferences"); SharedPreferences prefs = getActivity().getSharedPreferences(PREF, Activity.MODE_PRIVATE); String id = prefs.getString(PREF_PLAYABLE_ID, ""); int scrollY = prefs.getInt(PREF_SCROLL_Y, -1); if (scrollY != -1 && media != null && id.equals(media.getIdentifier().toString()) && webvDescription != null) { if (AppConfig.DEBUG) Log.d(TAG, "Restored scroll Position: " + scrollY); webvDescription.scrollTo(webvDescription.getScrollX(), scrollY); return true; } } return false; } }
package dr.evomodel.continuous; import dr.evolution.tree.MultivariateTraitTree; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evomodel.branchratemodel.DiscretizedBranchRates; import dr.evomodel.tree.TreeModel; import dr.evomodel.tree.TreeStatistic; import dr.geo.math.SphericalPolarCoordinates; import dr.inference.model.Statistic; import dr.math.distributions.MultivariateNormalDistribution; import dr.stats.DiscreteStatistics; import dr.xml.*; import java.util.ArrayList; import java.util.List; /** * @author Marc Suchard * @author Philippe Lemey * @author Andrew Rambaut */ public class DiffusionRateStatistic extends Statistic.Abstract { public static final String DIFFUSION_RATE_STATISTIC = "diffusionRateStatistic"; public static final String TREE_DISPERSION_STATISTIC = "treeDispersionStatistic"; public static final String BOOLEAN_DIS_OPTION = "greatCircleDistance"; public static final String MODE = "mode"; public static final String MEDIAN = "median"; public static final String AVERAGE = "average"; // average over all branches public static final String WEIGHTEDAVERAGE = "weightedAverage"; // weighted average (=total distance/total time) public static final String COEFFICIENT_OF_VARIATION = "coefficientOfVariation"; // weighted average (=total distance/total time) // public static final String DIFFUSIONCOEFFICIENT = "diffusionCoefficient"; // weighted average (=total distance/total time) public static final String BOOLEAN_DC_OPTION = "diffusionCoefficient"; public static final String HEIGHT_UPPER = "heightUpper"; public static final String HEIGHT_LOWER = "heightLower"; public DiffusionRateStatistic(String name, List<AbstractMultivariateTraitLikelihood> traitLikelihoods, boolean option, Mode mode, boolean diffusionCoefficient, double heightUpper, double heightLower, DiscretizedBranchRates branchRates) { super(name); this.traitLikelihoods = traitLikelihoods; this.useGreatCircleDistances = option; summaryMode = mode; this.diffusionCoefficient = diffusionCoefficient; this.heightUpper = heightUpper; this.heightLower = heightLower; this.branchRates = branchRates; } public int getDimension() { return 1; } public double getStatisticValue(int dim) { String traitName = traitLikelihoods.get(0).getTraitName(); double treelength = 0; double treeDistance = 0; //double[] rates = null; List<Double> rates = new ArrayList<Double>(); //double[] diffusionCoefficients = null; List<Double> diffusionCoefficients = new ArrayList<Double>(); double waDiffusionCoefficient = 0; for (AbstractMultivariateTraitLikelihood traitLikelihood : traitLikelihoods) { MultivariateTraitTree tree = traitLikelihood.getTreeModel(); for (int i = 0; i < tree.getNodeCount(); i++) { NodeRef node = tree.getNode(i); if (node != tree.getRoot()) { NodeRef parentNode = tree.getParent(node); if ((tree.getNodeHeight(parentNode) > heightLower) && (tree.getNodeHeight(node) < heightUpper)) { double[] trait = traitLikelihood.getTraitForNode(tree, node, traitName); double[] parentTrait = traitLikelihood.getTraitForNode(tree, parentNode, traitName); double[] traitUp = parentTrait; double[] traitLow = trait; double timeUp = tree.getNodeHeight(parentNode); double timeLow = tree.getNodeHeight(node); double rate = 1; if (branchRates != null){ rate = branchRates.getBranchRate(tree,node); } MultivariateDiffusionModel diffModel = traitLikelihoods.get(0).diffusionModel; double[] precision = diffModel.getPrecisionParameter().getParameterValues(); if (tree.getNodeHeight(parentNode) > heightUpper) { timeUp = heightUpper; //TODO: implement TrueNoise traitUp = imputeValue(trait, parentTrait, heightUpper, tree.getNodeHeight(node), tree.getNodeHeight(parentNode), precision, rate, false); } if (tree.getNodeHeight(node) < heightLower) { timeLow = heightLower; traitLow = imputeValue(trait, parentTrait, heightLower, tree.getNodeHeight(node), tree.getNodeHeight(parentNode), precision, rate, false); } double time = timeUp - timeLow; treelength += time; if (useGreatCircleDistances && (trait.length == 2)) { // Great Circle distance SphericalPolarCoordinates coord1 = new SphericalPolarCoordinates(traitLow[0], traitLow[1]); SphericalPolarCoordinates coord2 = new SphericalPolarCoordinates(traitUp[0], traitUp[1]); double distance = coord1.distance(coord2); treeDistance += distance; double dc = Math.pow(distance,2)/(4*time); diffusionCoefficients.add(dc); waDiffusionCoefficient += dc*time; rates.add(distance/time); } else { double distance = getNativeDistance(trait, parentTrait); treeDistance += distance; double dc = Math.pow(distance,2)/(4*time); diffusionCoefficients.add(dc); waDiffusionCoefficient += dc*time; rates.add(distance/time); } } } } } if (!diffusionCoefficient){ if (summaryMode == Mode.AVERAGE) { return DiscreteStatistics.mean(toArray(rates)); } else if (summaryMode == Mode.MEDIAN) { return DiscreteStatistics.median(toArray(rates)); } else if (summaryMode == Mode.COEFFICIENT_OF_VARIATION) { // don't compute mean twice final double mean = DiscreteStatistics.mean(toArray(rates)); return Math.sqrt(DiscreteStatistics.variance(toArray(rates), mean)) / mean; } else { return treeDistance / treelength; } } else { if (summaryMode == Mode.AVERAGE) { return DiscreteStatistics.mean(toArray(diffusionCoefficients)); } else if (summaryMode == Mode.MEDIAN) { return DiscreteStatistics.median(toArray(diffusionCoefficients)); } else if (summaryMode == Mode.COEFFICIENT_OF_VARIATION) { // don't compute mean twice final double mean = DiscreteStatistics.mean(toArray(diffusionCoefficients)); return Math.sqrt(DiscreteStatistics.variance(toArray(diffusionCoefficients), mean)) / mean; } else { return waDiffusionCoefficient/treelength; } } } // private double getNativeDistance(double[] location1, double[] location2) { // return Math.sqrt(Math.pow((location2[0] - location1[0]), 2.0) + Math.pow((location2[1] - location1[1]), 2.0)); private double getNativeDistance(double[] location1, double[] location2) { int traitDimension = location1.length; double sum = 0; for (int i = 0; i < traitDimension; i++) { sum += Math.pow((location2[i] - location1[i]),2); } return Math.sqrt(sum); } private double[] toArray(List<Double> list) { double[] returnArray = new double[list.size()]; for (int i = 0; i < list.size(); i++) { returnArray[i] = Double.valueOf(list.get(i).toString()); } return returnArray; } private double[] imputeValue(double[] nodeValue, double[] parentValue, double time, double nodeHeight, double parentHeight, double[] precisionArray, double rate, boolean trueNoise) { final double scaledTimeChild = (time - nodeHeight) * rate; final double scaledTimeParent = (parentHeight - time) * rate; final double scaledWeightTotal = 1.0 / scaledTimeChild + 1.0 / scaledTimeParent; final int dim = nodeValue.length; double[][] precision = new double[dim][dim]; int counter = 0; for (int a = 0; a < dim; a++){ for (int b = 0; b < dim; b++){ precision[a][b] = precisionArray[counter]; counter++ ; } } if (scaledTimeChild == 0) return nodeValue; if (scaledTimeParent == 0) return parentValue; // Find mean value, weighted average double[] mean = new double[dim]; double[][] scaledPrecision = new double[dim][dim]; for (int i = 0; i < dim; i++) { mean[i] = (nodeValue[i] / scaledTimeChild + parentValue[i] / scaledTimeParent) / scaledWeightTotal; if (trueNoise) { for (int j = i; j < dim; j++) scaledPrecision[j][i] = scaledPrecision[i][j] = precision[i][j] * scaledWeightTotal; } } // System.out.print(time+"\t"+nodeHeight+"\t"+parentHeight+"\t"+scaledTimeChild+"\t"+scaledTimeParent+"\t"+scaledWeightTotal+"\t"+mean[0]+"\t"+mean[1]+"\t"+scaledPrecision[0][0]+"\t"+scaledPrecision[0][1]+"\t"+scaledPrecision[1][0]+"\t"+scaledPrecision[1][1]); if (trueNoise) { mean = MultivariateNormalDistribution.nextMultivariateNormalPrecision(mean, scaledPrecision); } // System.out.println("\t"+mean[0]+"\t"+mean[1]+"\r"); double[] result = new double[dim]; for (int i = 0; i < dim; i++) result[i] = mean[i]; return result; } enum Mode { AVERAGE, WEIGHTED_AVERAGE, MEDIAN, COEFFICIENT_OF_VARIATION } public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return DIFFUSION_RATE_STATISTIC; } @Override public String[] getParserNames() { return new String[]{getParserName(), TREE_DISPERSION_STATISTIC}; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { String name = xo.getAttribute(NAME, xo.getId()); boolean option = xo.getAttribute(BOOLEAN_DIS_OPTION, false); // Default value is false Mode averageMode; String mode = xo.getAttribute(MODE, WEIGHTEDAVERAGE); if (mode.equals(AVERAGE)) { averageMode = Mode.AVERAGE; } else if (mode.equals(MEDIAN)) { averageMode = Mode.MEDIAN; } else if (mode.equals(COEFFICIENT_OF_VARIATION)) { averageMode = Mode.COEFFICIENT_OF_VARIATION; } else { averageMode = Mode.WEIGHTED_AVERAGE; } boolean diffCoeff = xo.getAttribute(BOOLEAN_DC_OPTION, false); // Default value is false final double upperHeight = xo.getAttribute(HEIGHT_UPPER, Double.MAX_VALUE); final double lowerHeight = xo.getAttribute(HEIGHT_LOWER, 0.0); List<AbstractMultivariateTraitLikelihood> traitLikelihoods = new ArrayList<AbstractMultivariateTraitLikelihood>(); DiscretizedBranchRates branchRates = null; for (int i = 0; i < xo.getChildCount(); i++) { if (xo.getChild(i) instanceof AbstractMultivariateTraitLikelihood) { traitLikelihoods.add((AbstractMultivariateTraitLikelihood) xo.getChild(i)); } if (xo.getChild(i) instanceof DiscretizedBranchRates) { branchRates = (DiscretizedBranchRates) xo.getChild(i); } } return new DiffusionRateStatistic(name, traitLikelihoods, option, averageMode, diffCoeff, upperHeight, lowerHeight, branchRates); }
package edu.wpi.first.wpilibj.templates.subsystems; import edu.wpi.first.wpilibj.Talon; import edu.wpi.first.wpilibj.DoubleSolenoid; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.Gyro; import edu.wpi.first.wpilibj.ADXL345_I2C; import edu.wpi.first.wpilibj.templates.RobotMap; import edu.wpi.first.wpilibj.CounterBase; import edu.wpi.first.wpilibj.PIDController; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.command.PIDSubsystem; import edu.wpi.first.wpilibj.templates.commands.DriveArcadeDrive; /** * * @author Super NURDs * */ public class Drivetrain extends PIDSubsystem { // Put methods for controlling this subsystem // here. Call these from Commands. //Doubles and booleans public boolean driveHighGearState = true; //true is high gear and false is low gear public double driveMoveSpeed = 0.0; public double driveRotateSpeed = 0.0; public double driveGyroAngle = 0.0; public double drivetrainLeftEncoderValue = 0.0; public double drivetrainRightEncoderValue = 0.0; // DriveBoxes DriveBox driveBoxLeft = null; DriveBox driveBoxRight = null; //Robot Drive RobotDrive drivetrain = null; //Solenoids DoubleSolenoid driveShiftSolenoid = null; //Encoders public Encoder driveEncoderRight = null; public Encoder driveEncoderLeft = null; //Gyro and Accelerometer public Gyro driveGyroscope = null; public PIDController gyroscope = null; public ADXL345_I2C driveAccelerometer = null; public Drivetrain() { super("Drivetrain Encoder PID", 7.0, 3.0, 4.0); setAbsoluteTolerance(0.1); PIDController controller = this.getPIDController(); controller.setContinuous(true); try { driveBoxLeft = new DriveBox("Left DriveBox", RobotMap.DRIVEBOX_LEFT_TALON_TOP, RobotMap.DRIVEBOX_LEFT_TALON_MIDDLE, RobotMap.DRIVEBOX_LEFT_TALON_BOTTOM, RobotMap.SOLENOID_SLOT_1, RobotMap.DRIVEBOX_LEFT_SOLENOID_OPEN, RobotMap.DRIVEBOX_LEFT_SOLENOID_CLOSE, RobotMap.DRIVEBOX_LEFT_ENCODER_CH_A, RobotMap.DRIVEBOX_LEFT_ENCODER_CH_B); driveBoxRight = new DriveBox("Right DriveBox", RobotMap.DRIVEBOX_RIGHT_TALON_TOP, RobotMap.DRIVEBOX_RIGHT_TALON_MIDDLE, RobotMap.DRIVEBOX_RIGHT_TALON_BOTTOM, RobotMap.SOLENOID_SLOT_1, RobotMap.DRIVEBOX_RIGHT_SOLENOID_OPEN, RobotMap.DRIVEBOX_RIGHT_SOLENOID_CLOSE, RobotMap.DRIVEBOX_RIGHT_ENCODER_CH_A, RobotMap.DRIVEBOX_RIGHT_ENCODER_CH_B); } catch (Exception e) { e.printStackTrace(); } } public double getError() { return this.getPIDController().getError(); } public void setPositionSpeed(double s) { try { driveFrontLeftTalon.pidWrite(s); driveFrontRightTalon.pidWrite(-s); driveBackLeftTalon.pidWrite(s); driveBackRightTalon.pidWrite(-s); } catch (Exception e) { } } public void setTurnSpeed(double speed) { try { driveFrontLeftTalon.pidWrite(speed); driveFrontRightTalon.pidWrite(speed); driveBackLeftTalon.pidWrite(speed); driveBackRightTalon.pidWrite(speed); } catch (Exception e) { } } public void arcadeDrive(double moveValue, double rotateValue) { try { drivetrain.arcadeDrive(moveValue, rotateValue, driveHighGearState); driveMoveSpeed = moveValue; driveRotateSpeed = rotateValue; } catch (Exception e) { } } public void arcadeDriveAxes() { try { drivetrain.arcadeDrive(edu.wpi.first.wpilibj.templates.commands.CommandBase.oi.DriverHID, 2, edu.wpi.first.wpilibj.templates.commands.CommandBase.oi.DriverHID, 4, driveHighGearState); } catch (Exception e) { } } public void tankDrive(double leftValue, double rightValue){ try { drivetrain.tankDrive(leftValue, rightValue); driveMoveSpeed = leftValue; driveRotateSpeed = 0.0; } catch(Exception e) { } } public double driveMoveSpeed() { return driveMoveSpeed; } public double driveRotateSpeed() { return driveRotateSpeed; } public double getRightEncoderValue() { if (driveEncoderRight == null) { return (0.0); } double encValue = driveEncoderRight.getDistance(); drivetrainRightEncoderValue = encValue; return (encValue); } public double getLeftEncoderValue() { if (driveEncoderLeft == null) { return (0.0); } double encValue = driveEncoderLeft.getDistance(); drivetrainLeftEncoderValue = encValue; return (encValue); } public double getEncoderAverages() { double encAve = ((getRightEncoderValue() + getLeftEncoderValue())/2); return encAve; } public void startEncoders() { try { driveEncoderLeft.start(); driveEncoderRight.start(); } catch (Exception e) { } } public void stopEncoders() { try { driveEncoderLeft.stop(); driveEncoderRight.stop(); } catch (Exception e) { } } public void resetEncoders() { try { driveEncoderLeft.reset(); driveEncoderRight.reset(); } catch (Exception e) { } } public void driveEncodersInit() { startEncoders(); resetEncoders(); } public double driveEncodersLeftValue() { return drivetrainLeftEncoderValue; } public double driveEncodersRightValue() { return drivetrainRightEncoderValue; } public void resetGyro() { try { driveGyroscope.reset(); } catch (Exception e) { } } public void initGyroscope(double Kp, double Ki, double Kd, double setpoint) { try { gyroscope.setPID(Kp, Ki, Kd); gyroscope.setSetpoint(setpoint); driveGyroscope.reset(); gyroscope.enable(); } catch (Exception e) { } } public double getGyroAngle() { if (driveGyroscope == null) { return 0.0; } return driveGyroscope.getAngle(); } public double getAcceleration(String axis) { if ("x".equals(axis)) { return driveAccelerometer.getAcceleration(ADXL345_I2C.Axes.kX); } else if ("y".equals(axis)) { return driveAccelerometer.getAcceleration(ADXL345_I2C.Axes.kY); } else if ("z".equals(axis)) { return driveAccelerometer.getAcceleration(ADXL345_I2C.Axes.kZ); } else { return 0.0; } } public void shiftLowGear() { try { driveShiftSolenoid.set(DoubleSolenoid.Value.kReverse); driveHighGearState = false; } catch (Exception e) { } } public void shiftHighGear() { try { driveShiftSolenoid.set(DoubleSolenoid.Value.kForward); driveHighGearState = true; } catch (Exception e) { } } public boolean gearState() { return driveHighGearState; } public void initDefaultCommand() { // Set the default command for a subsystem here. this.setDefaultCommand(new DriveArcadeDrive()); } protected double returnPIDInput() { return getLeftEncoderValue(); } protected void usePIDOutput(double output) { setPositionSpeed(output); } }
package edu.wheaton.simulator.statistics; import java.util.HashMap; import edu.wheaton.simulator.entity.Prototype; import edu.wheaton.simulator.entity.Slot; import edu.wheaton.simulator.simulation.Grid; /** * @author Daniel Gill, Nico Lasta * */ class GridObserver { private StatisticsManager statManager; /** * Constructor. */ public GridObserver(StatisticsManager statManager) { this.statManager = statManager; } public void observe(Grid grid, Integer step, HashMap<String, Prototype> prototypes) { for (Slot s : grid) { // store snapshot of Slot // store snapshot of Agent (if != null) } } }
package edu.wheaton.simulator.statistics; import java.util.HashMap; import java.util.Set; /** * A class representing all the information to track from slots in the game. * * @author akonwi * */ public class SlotSnapshot extends EntitySnapshot { /** * How many agents are occupying this slot */ public final Set<EntityID> agents; /** * Constructor * * @param id * The ID of the Slot associated with this snapshot. * @param fields * The current values of the fields of the GridEntity * @param step * The step in the simulation associated with this snapshot. * @param prototype * The prototype for this category of Slot. * @param agents * the number of agents occupying this slot */ public SlotSnapshot(EntityID id, HashMap<String, Object> fields, Integer step, EntityPrototype prototype, Set<EntityID> agents) { super(id, fields, step, prototype); this.agents = agents; } }
package emergencylanding.k.library.lwjgl.render; import emergencylanding.k.library.internalstate.ELEntity; import emergencylanding.k.library.lwjgl.Shapes; public class TextureRender extends Render<ELEntity> { @Override public void doRender(ELEntity entity, float posX, float posY, float posZ) { VBAO quad = Shapes.getQuad(new VertexData(), new VertexData().setXYZ( (float) entity.getTex().getWidth(), (float) entity.getTex() .getHeight(), posZ), Shapes.XY); quad.setTexture(entity.getTex()); quad.setXYZOff(entity.getInterpolated()); quad.draw(); } }
/* Open Source Software - may be modified and shared by FRC teams. The code */ /* the project. */ package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.*; import edu.wpi.first.wpilibj.can.CANTimeoutException; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class RobotTemplate extends IterativeRobot { Joystick joystickRight = new Joystick(1); Joystick joystickLeft = new Joystick(2); Joystick joystickManip = new Joystick(3); CANJaguar leftDrive; CANJaguar rightDrive; Compressor compressor = new Compressor (7,2); RobotDrive robotDrive; /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { try { leftDrive = new CANJaguar(8); rightDrive = new CANJaguar(4); robotDrive = new RobotDrive(leftDrive, rightDrive); } catch (CANTimeoutException e) { e.printStackTrace(); } compressor.start(); } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { } /** * This function is called periodically during operator control */ public void teleopPeriodic() { } /** * This function is called periodically during test mode */ public void testPeriodic() { } }
package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.AnalogChannel; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.SimpleRobot; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; public class RobotTemplate extends SimpleRobot { // these inputs are to test weather the magnetic encoder is in the correct field. // These don't need to be used. static final int MAGNETIC_FIELD_DECREASING_TEST = 4; static final int MAGNETIC_FIELD_INCREASING_TEST = 3; DigitalInput magdec = new DigitalInput(MAGNETIC_FIELD_DECREASING_TEST); DigitalInput maginc = new DigitalInput(MAGNETIC_FIELD_INCREASING_TEST); // Find the output foltage from the low-pass filter from the pwm out static final int ABSOLUTE_ENCODER_CHANNEL = 1; AnalogChannel absAngle = new AnalogChannel(ABSOLUTE_ENCODER_CHANNEL); static final double HEURISTIC_VOLTAGE = 4.9; public void operatorControl() { while(true) { // output voltage is ~4.9v. Conversion to angle // If the max voltage doesn't give 360 degrees, then the heuristic voltage is wrong double angle = absAngle.getVoltage() * 360/HEURISTIC_VOLTAGE; SmartDashboard.putBoolean("maginc", maginc.get()); SmartDashboard.putBoolean("magdec", magdec.get()); SmartDashboard.putNumber("voltage", absAngle.getVoltage()); SmartDashboard.putNumber("angle", angle); System.out.println("voltage:" + absAngle.getVoltage()); System.out.println("angle:" + angle); } } }
package org.neo4j.server; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.neo4j.server.ServerBuilder.server; import org.junit.Test; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; public class ServerConfigTest { private static final int NON_DEFAULT_PORT = 54321; @Test public void shouldPickUpPortFromConfig() throws Exception { NeoServer server = server().onPort(NON_DEFAULT_PORT).build(); server.start(); assertEquals(NON_DEFAULT_PORT, server.webServerPort); Client client = Client.create(); ClientResponse response = client.resource(server.baseUri()).get(ClientResponse.class); assertThat(response.getStatus(), is(200)); } }
package gov.nih.nci.caIntegrator.services.util; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.ejb.EJBLocalHome; import javax.ejb.EJBHome; import javax.rmi.PortableRemoteObject; import java.util.Map; import java.util.Collections; import java.util.HashMap; import java.util.Properties; import java.io.InputStream; import java.io.IOException; public class ServiceLocator { private static InitialContext initialContext; private Map cache; private String deployment ; private static ServiceLocator ONLY_INSTANCE; static { ONLY_INSTANCE = new ServiceLocator(); } static public ServiceLocator getInstance() { return ONLY_INSTANCE; } public Object locateHome(java.util.Hashtable environment, String jndiName, Class narrowTo) throws javax.naming.NamingException { if (environment != null) initialContext = new javax.naming.InitialContext(environment); Object objRef ; if (cache.containsKey(jndiName)) { objRef = cache.get(jndiName); } else { Object remObjRef = initialContext.lookup(jndiName); // narrow only if necessary if (narrowTo.isInstance(java.rmi.Remote.class)) { objRef = javax.rmi.PortableRemoteObject.narrow(remObjRef , narrowTo); } else { objRef = remObjRef; } cache.put(jndiName, remObjRef); } return objRef; } public Object relocateHome(java.util.Hashtable environment, String jndiName, Class narrowTo) throws javax.naming.NamingException, Exception { // remove old reference so that it can be re-intialized cache.remove(jndiName); initializeContext(); return locateHome(environment, jndiName, narrowTo); } private ServiceLocator() { try { initializeContext(); cache = Collections.synchronizedMap(new HashMap()); } catch(NamingException ne) { ne.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } } public Object getLocalHome(String jndiHomeName) throws Exception{ Object localHome = null; try { if (cache.containsKey(jndiHomeName)) { localHome = cache.get(jndiHomeName); } else { localHome = initialContext.lookup(jndiHomeName); cache.put(jndiHomeName, localHome); } } catch(NamingException ne) { ne.printStackTrace(); throw new Exception(ne); } return localHome; } public EJBHome getRemoteHome(String jndiHomeName, Class homeClassName) throws Exception{ EJBHome remoteHome = null; try { if (cache.containsKey(jndiHomeName)) { remoteHome = (EJBHome) cache.get(jndiHomeName); } else { Object objRef = initialContext.lookup(jndiHomeName); Object obj = PortableRemoteObject.narrow(objRef, homeClassName); remoteHome = (EJBHome) obj; cache.put(jndiHomeName, remoteHome); } } catch(NamingException ne) { ne.printStackTrace(); throw new Exception(ne); } return remoteHome; } private void initializeContext () throws Exception{ try { Properties p = System.getProperties(); InputStream is = ServiceLocator.class.getResourceAsStream("/jndi.properties"); p.load(is); deployment = p.getProperty("jndi.deployment"); initialContext = new InitialContext(p); } catch(IOException ioe) { throw new Exception(ioe); } } public String getDeployment() { return deployment; } }
package org.rstudio.studio.client.common; import org.rstudio.core.client.VirtualConsole; import org.rstudio.core.client.widget.FontSizer; import org.rstudio.core.client.widget.PreWidget; import org.rstudio.studio.client.workbench.views.console.ConsoleResources; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.ScrollPanel; public class OutputBuffer extends Composite { public OutputBuffer() { output_ = new PreWidget(); output_.setStylePrimaryName( ConsoleResources.INSTANCE.consoleStyles().output()); FontSizer.applyNormalFontSize(output_); scrollPanel_ = new ScrollPanel(); scrollPanel_.setSize("100%", "100%"); scrollPanel_.add(output_); initWidget(scrollPanel_); } public void append(String output) { virtualConsole_.submit(output); output_.setText(virtualConsole_.toString()); scrollPanel_.scrollToBottom(); } public void scrollToBottom() { scrollPanel_.scrollToBottom(); } public void clear() { output_.setText(""); } private PreWidget output_; private VirtualConsole virtualConsole_ = new VirtualConsole(); private ScrollPanel scrollPanel_; }
package fitnesse.responders.editing; import util.RegexTestCase; import fitnesse.FitNesseContext; import fitnesse.http.MockRequest; import fitnesse.http.SimpleResponse; import fitnesse.testutil.FitNesseUtil; import fitnesse.wiki.InMemoryPage; import fitnesse.wiki.PageCrawler; import fitnesse.wiki.PageData; import fitnesse.wiki.PathParser; import fitnesse.wiki.WikiPage; import fitnesse.wiki.WikiPageProperties; public class EditResponderTest extends RegexTestCase { private WikiPage root; private MockRequest request; private EditResponder responder; private PageCrawler crawler; public void setUp() throws Exception { root = InMemoryPage.makeRoot("root"); FitNesseUtil.makeTestContext(root); crawler = root.getPageCrawler(); request = new MockRequest(); responder = new EditResponder(); } public void testResponse() throws Exception { WikiPage page=crawler.addPage(root, PathParser.parse("ChildPage"), "child content with <html>"); PageData data = page.getData(); WikiPageProperties properties = data.getProperties(); properties.set(PageData.PropertySUITES, "Edit Page tags"); page.commit(data); request.setResource("ChildPage"); SimpleResponse response = (SimpleResponse) responder.makeResponse(new FitNesseContext(root), request); assertEquals(200, response.getStatus()); String body = response.getContent(); assertSubString("<html>", body); assertSubString("<form", body); assertSubString("method=\"post\"", body); assertSubString("child content with &lt;html&gt;", body); assertSubString("name=\"responder\"", body); assertSubString("name=\"" + EditResponder.TIME_STAMP + "\"", body); assertSubString("name=\"" + EditResponder.TICKET_ID + "\"", body); assertSubString("name=\"" + EditResponder.HELP_TEXT + "\"", body); assertSubString("select id=\"" + EditResponder.TEMPLATE_MAP + "\"", body); assertSubString("type=\"submit\"", body); assertSubString(String.format("textarea", EditResponder.CONTENT_INPUT_NAME), body); assertSubString("<h5> Edit Page tags</h5>", body); } public void testResponseWhenNonexistentPageRequestsed() throws Exception { request.setResource("NonExistentPage"); request.addInput("nonExistent", true); FitNesseContext context = new FitNesseContext(root); SimpleResponse response = (SimpleResponse) responder.makeResponse(context, request); assertEquals(200, response.getStatus()); String body = response.getContent(); assertSubString("<html>", body); assertSubString("<form", body); assertSubString("method=\"post\"", body); assertSubString(context.defaultNewPageContent, body); assertSubString("name=\"responder\"", body); assertSubString("name=\"" + EditResponder.TIME_STAMP + "\"", body); assertSubString("name=\"" + EditResponder.TICKET_ID + "\"", body); assertSubString("type=\"submit\"", body); assertNotSubString("<h5> </h5>", body); } public void testRedirectToRefererEffect() throws Exception { crawler.addPage(root, PathParser.parse("ChildPage"), "child content with <html>"); request.setResource("ChildPage"); request.addInput("redirectToReferer", true); request.addInput("redirectAction", "boom"); request.addHeader("Referer", "http://fitnesse.org:8080/SomePage"); SimpleResponse response = (SimpleResponse) responder.makeResponse(new FitNesseContext(root), request); assertEquals(200, response.getStatus()); String body = response.getContent(); assertSubString("name=\"redirect\" value=\"http://fitnesse.org:8080/SomePage?boom\"", body); } public void testTemplateListPopulates() throws Exception { crawler.addPage(root, PathParser.parse("TemplateLibrary"), "template library"); crawler.addPage(root, PathParser.parse("TemplateLibrary.TemplateOne"), "template 1"); crawler.addPage(root, PathParser.parse("TemplateLibrary.TemplateTwo"), "template 2"); crawler.addPage(root, PathParser.parse("ChildPage"), "child content with <html>"); request.setResource("ChildPage"); SimpleResponse response = (SimpleResponse) responder.makeResponse(new FitNesseContext(root), request); assertEquals(200, response.getStatus()); String body = response.getContent(); assertSubString("<html>", body); assertSubString("<form", body); assertSubString("method=\"post\"", body); assertSubString("child content with &lt;html&gt;", body); assertSubString("name=\"responder\"", body); assertSubString("name=\"" + EditResponder.TIME_STAMP + "\"", body); assertSubString("name=\"" + EditResponder.TICKET_ID + "\"", body); assertSubString("name=\"" + EditResponder.HELP_TEXT + "\"", body); assertSubString("select id=\"" + EditResponder.TEMPLATE_MAP + "\"", body); assertSubString("option value=\"" + ".TemplateLibrary.TemplateOne" + "\"", body); assertSubString("option value=\"" + ".TemplateLibrary.TemplateTwo" + "\"", body); assertSubString("type=\"submit\"", body); assertSubString(String.format("textarea", EditResponder.CONTENT_INPUT_NAME), body); } public void testTemplateInserterScriptsExists() throws Exception { SimpleResponse response = (SimpleResponse) responder.makeResponse(new FitNesseContext(root), request); String body = response.getContent(); assertMatches("TemplateInserter.js", body); } public void testPasteFromExcelExists() throws Exception { SimpleResponse response = (SimpleResponse) responder.makeResponse(new FitNesseContext(root), request); String body = response.getContent(); assertMatches("SpreadsheetTranslator.js", body); } public void testFormatterScriptsExist() throws Exception { SimpleResponse response = (SimpleResponse) responder.makeResponse(new FitNesseContext(root), request); String body = response.getContent(); assertMatches("WikiFormatter.js", body); } public void testMissingPageDoesNotGetCreated() throws Exception { request.setResource("MissingPage"); responder.makeResponse(new FitNesseContext(root), request); assertFalse(root.hasChildPage("MissingPage")); } }
package flatland.protobuf; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import ordered_map.core.OrderedMap; import ordered_set.core.OrderedSet; import clojure.lang.APersistentMap; import clojure.lang.ASeq; import clojure.lang.IFn; import clojure.lang.IMapEntry; import clojure.lang.IObj; import clojure.lang.IPersistentCollection; import clojure.lang.IPersistentMap; import clojure.lang.IPersistentVector; import clojure.lang.ISeq; import clojure.lang.ITransientMap; import clojure.lang.ITransientSet; import clojure.lang.Keyword; import clojure.lang.MapEntry; import clojure.lang.Numbers; import clojure.lang.Obj; import clojure.lang.PersistentArrayMap; import clojure.lang.PersistentVector; import clojure.lang.RT; import clojure.lang.SeqIterator; import clojure.lang.Sequential; import clojure.lang.Symbol; import clojure.lang.Var; import com.google.protobuf.CodedInputStream; import com.google.protobuf.CodedOutputStream; import com.google.protobuf.DescriptorProtos; import com.google.protobuf.DescriptorProtos.FieldOptions; import com.google.protobuf.Descriptors; import com.google.protobuf.DynamicMessage; import com.google.protobuf.GeneratedMessage; import com.google.protobuf.InvalidProtocolBufferException; public class PersistentProtocolBufferMap extends APersistentMap implements IObj { public static class Def { public static interface NamingStrategy { /** * Given a Clojure map key, return the string to be used as the protobuf message field name. */ String protoName(Object clojureName); /** * Given a protobuf message field name, return a Clojure object suitable for use as a map key. */ Object clojureName(String protoName); } // we want this to work for anything Named, so use clojure.core/name public static final Var NAME_VAR = Var.intern(RT.CLOJURE_NS, Symbol.intern("name")); public static final String nameStr(Object named) { try { return (String)((IFn)NAME_VAR.deref()).invoke(named); } catch (Exception e) { return null; } } public static final NamingStrategy protobufNames = new NamingStrategy() { @Override public String protoName(Object name) { return nameStr(name); } @Override public Object clojureName(String name) { return Keyword.intern(name.toLowerCase()); } @Override public String toString() { return "[protobuf names]"; } }; public static final NamingStrategy convertUnderscores = new NamingStrategy() { @Override public String protoName(Object name) { return nameStr(name).replaceAll("-", "_"); } @Override public Object clojureName(String name) { return Keyword.intern(name.replaceAll("_", "-").toLowerCase()); } @Override public String toString() { return "[convert underscores]"; } }; public final Descriptors.Descriptor type; public final NamingStrategy namingStrategy; public final int sizeLimit; public static final Object NULL = new Object(); // keys should be FieldDescriptors, except that NULL is used as a replacement for real null ConcurrentHashMap<Object, Object> key_to_field; private static final class DefOptions { public final Descriptors.Descriptor type; public final NamingStrategy strat; public final int sizeLimit; public DefOptions(Descriptors.Descriptor type, NamingStrategy strat, int sizeLimit) { this.type = type; this.strat = strat; this.sizeLimit = sizeLimit; } public boolean equals(Object other) { if (this.getClass() != other.getClass()) return false; DefOptions od = (DefOptions)other; return type.equals(od.type) && strat.equals(od.strat) && sizeLimit == od.sizeLimit; } public int hashCode() { return type.hashCode() + strat.hashCode() + sizeLimit; } } static ConcurrentHashMap<DefOptions, Def> defCache = new ConcurrentHashMap<DefOptions, Def>(); public static Def create(Descriptors.Descriptor type, NamingStrategy strat, int sizeLimit) { DefOptions opts = new DefOptions(type, strat, sizeLimit); Def def = defCache.get(type); if (def == null) { def = new Def(type, strat, sizeLimit); defCache.putIfAbsent(opts, def); } return def; } protected Def(Descriptors.Descriptor type, NamingStrategy strat, int sizeLimit) { this.type = type; this.key_to_field = new ConcurrentHashMap<Object, Object>(); this.namingStrategy = strat; this.sizeLimit = sizeLimit; } public DynamicMessage parseFrom(byte[] bytes) throws InvalidProtocolBufferException { return DynamicMessage.parseFrom(type, bytes); } public DynamicMessage parseFrom(CodedInputStream input) throws IOException { input.setSizeLimit(sizeLimit); return DynamicMessage.parseFrom(type, input); } public DynamicMessage.Builder parseDelimitedFrom(InputStream input) throws IOException { DynamicMessage.Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder; } else { return null; } } public DynamicMessage.Builder newBuilder() { return DynamicMessage.newBuilder(type); } public Descriptors.FieldDescriptor fieldDescriptor(Object key) { if (key == null) { return null; } if (key instanceof Descriptors.FieldDescriptor) { return (Descriptors.FieldDescriptor)key; } else { Object field = key_to_field.get(key); if (field != null) { if (field == NULL) { return null; } return (Descriptors.FieldDescriptor)field; } else { field = type.findFieldByName(namingStrategy.protoName(key)); key_to_field.putIfAbsent(key, field == null ? NULL : field); } return (Descriptors.FieldDescriptor)field; } } public String getName() { return type.getName(); } public String getFullName() { return type.getFullName(); } public Descriptors.Descriptor getMessageType() { return type; } static final ConcurrentHashMap<NamingStrategy, ConcurrentHashMap<String, Object>> caches = new ConcurrentHashMap<NamingStrategy, ConcurrentHashMap<String, Object>>(); static final Object nullv = new Object(); public Object intern(String name) { ConcurrentHashMap<String, Object> nameCache = caches.get(namingStrategy); if (nameCache == null) { nameCache = new ConcurrentHashMap<String, Object>(); ConcurrentHashMap<String, Object> existing = caches.putIfAbsent(namingStrategy, nameCache); if (existing != null) { nameCache = existing; } } Object clojureName = nameCache.get(name); if (clojureName == null) { if (name == "") { clojureName = nullv; } else { clojureName = namingStrategy.clojureName(name); if (clojureName == null) { clojureName = nullv; } } Object existing = nameCache.putIfAbsent(name, clojureName); if (existing != null) { clojureName = existing; } } return clojureName == nullv ? null : clojureName; } public Object clojureEnumValue(Descriptors.EnumValueDescriptor enum_value) { return intern(enum_value.getName()); } protected Object mapFieldBy(Descriptors.FieldDescriptor field) { return intern(field.getOptions().getExtension(Extensions.mapBy)); } protected PersistentProtocolBufferMap mapValue(Descriptors.FieldDescriptor field, PersistentProtocolBufferMap left, PersistentProtocolBufferMap right) { if (left == null) { return right; } else { Object map_exists = intern(field.getOptions().getExtension(Extensions.mapExists)); if (map_exists != null) { if (left.valAt(map_exists) == Boolean.FALSE && right.valAt(map_exists) == Boolean.TRUE) { return right; } else { return left.append(right); } } Object map_deleted = intern(field.getOptions().getExtension(Extensions.mapDeleted)); if (map_deleted != null) { if (left.valAt(map_deleted) == Boolean.TRUE && right.valAt(map_deleted) == Boolean.FALSE) { return right; } else { return left.append(right); } } return left.append(right); } } } public final Def def; private final DynamicMessage message; private final IPersistentMap _meta; private final IPersistentMap ext; static public PersistentProtocolBufferMap create(Def def, byte[] bytes) throws InvalidProtocolBufferException { DynamicMessage message = def.parseFrom(bytes); return new PersistentProtocolBufferMap(null, def, message); } static public PersistentProtocolBufferMap parseFrom(Def def, CodedInputStream input) throws IOException { DynamicMessage message = def.parseFrom(input); return new PersistentProtocolBufferMap(null, def, message); } static public PersistentProtocolBufferMap parseDelimitedFrom(Def def, InputStream input) throws IOException { DynamicMessage.Builder builder = def.parseDelimitedFrom(input); if (builder != null) { return new PersistentProtocolBufferMap(null, def, builder); } else { return null; } } static public PersistentProtocolBufferMap construct(Def def, Object keyvals) { PersistentProtocolBufferMap protobuf = new PersistentProtocolBufferMap(null, def); return protobuf.cons(keyvals); } protected PersistentProtocolBufferMap(IPersistentMap meta, Def def) { this._meta = meta; this.ext = null; this.def = def; this.message = null; } protected PersistentProtocolBufferMap(IPersistentMap meta, Def def, DynamicMessage message) { this._meta = meta; this.ext = null; this.def = def; this.message = message; } protected PersistentProtocolBufferMap(IPersistentMap meta, IPersistentMap ext, Def def, DynamicMessage message) { this._meta = meta; this.ext = ext; this.def = def; this.message = message; } protected PersistentProtocolBufferMap(IPersistentMap meta, Def def, DynamicMessage.Builder builder) { this._meta = meta; this.ext = null; this.def = def; this.message = builder.build(); } protected PersistentProtocolBufferMap(IPersistentMap meta, IPersistentMap ext, Def def, DynamicMessage.Builder builder) { this._meta = meta; this.ext = ext; this.def = def; this.message = builder.build(); } public byte[] toByteArray() { return message().toByteArray(); } public void writeTo(CodedOutputStream output) throws IOException { message().writeTo(output); } public void writeDelimitedTo(OutputStream output) throws IOException { message().writeDelimitedTo(output); } public Descriptors.Descriptor getMessageType() { return def.getMessageType(); } public DynamicMessage message() { if (message == null) { return def.newBuilder().build(); // This will only work if an empty message is valid. } else { return message; } } public DynamicMessage.Builder builder() { if (message == null) { return def.newBuilder(); } else { return message.toBuilder(); } } protected Object fromProtoValue(Descriptors.FieldDescriptor field, Object value) { return fromProtoValue(field, value, true); } static Keyword k_key = Keyword.intern("key"); static Keyword k_val = Keyword.intern("val"); static Keyword k_item = Keyword.intern("item"); static Keyword k_exists = Keyword.intern("exists"); protected Object fromProtoValue(Descriptors.FieldDescriptor field, Object value, boolean use_extensions) { if (value instanceof List) { List<?> values = (List<?>)value; Iterator<?> iterator = values.iterator(); if (use_extensions) { Object map_field_by = def.mapFieldBy(field); DescriptorProtos.FieldOptions options = field.getOptions(); if (map_field_by != null) { ITransientMap map = (ITransientMap)OrderedMap.EMPTY.asTransient(); while (iterator.hasNext()) { PersistentProtocolBufferMap v = (PersistentProtocolBufferMap)fromProtoValue(field, iterator.next()); Object k = v.valAt(map_field_by); PersistentProtocolBufferMap existing = (PersistentProtocolBufferMap)map.valAt(k); map = map.assoc(k, def.mapValue(field, existing, v)); } return map.persistent(); } else if (options.getExtension(Extensions.counter)) { Object count = iterator.next(); while (iterator.hasNext()) { count = Numbers.add(count, iterator.next()); } return count; } else if (options.getExtension(Extensions.succession)) { return fromProtoValue(field, values.get(values.size() - 1)); } else if (options.getExtension(Extensions.map)) { Descriptors.Descriptor type = field.getMessageType(); Descriptors.FieldDescriptor key_field = type.findFieldByName("key"); Descriptors.FieldDescriptor val_field = type.findFieldByName("val"); ITransientMap map = (ITransientMap)OrderedMap.EMPTY.asTransient(); while (iterator.hasNext()) { DynamicMessage message = (DynamicMessage)iterator.next(); Object k = fromProtoValue(key_field, message.getField(key_field)); Object v = fromProtoValue(val_field, message.getField(val_field)); Object existing = map.valAt(k); if (existing instanceof PersistentProtocolBufferMap) { map = map.assoc(k, def.mapValue(field, (PersistentProtocolBufferMap)existing, (PersistentProtocolBufferMap)v)); } else if (existing instanceof IPersistentCollection) { map = map.assoc(k, ((IPersistentCollection)existing).cons(v)); } else { map = map.assoc(k, v); } } return map.persistent(); } else if (options.getExtension(Extensions.set)) { Descriptors.Descriptor type = field.getMessageType(); Descriptors.FieldDescriptor item_field = type.findFieldByName("item"); Descriptors.FieldDescriptor exists_field = type.findFieldByName("exists"); ITransientSet set = (ITransientSet)OrderedSet.EMPTY.asTransient(); while (iterator.hasNext()) { DynamicMessage message = (DynamicMessage)iterator.next(); Object item = fromProtoValue(item_field, message.getField(item_field)); Boolean exists = (Boolean)message.getField(exists_field); if (exists) { set = (ITransientSet)set.conj(item); } else { try { set = set.disjoin(item); } catch (Exception e) { e.printStackTrace(); } } } return set.persistent(); } } List<Object> list = new ArrayList<Object>(values.size()); while (iterator.hasNext()) { list.add(fromProtoValue(field, iterator.next(), use_extensions)); } return PersistentVector.create(list); } else { switch (field.getJavaType()) { case ENUM: Descriptors.EnumValueDescriptor e = (Descriptors.EnumValueDescriptor)value; if (use_extensions && field.getOptions().getExtension(Extensions.nullable) && field.getOptions().getExtension(nullExtension(field)).equals(e.getNumber())) { return null; } else { return def.clojureEnumValue(e); } case MESSAGE: Def fieldDef = PersistentProtocolBufferMap.Def.create(field.getMessageType(), this.def.namingStrategy, this.def.sizeLimit); DynamicMessage message = (DynamicMessage)value; // Total hack because getField() doesn't return an empty array for repeated messages. if (field.isRepeated() && !message.isInitialized()) { return fromProtoValue(field, new ArrayList<Object>(), use_extensions); } return new PersistentProtocolBufferMap(null, fieldDef, message); default: if (use_extensions && field.getOptions().getExtension(Extensions.nullable) && field.getOptions().getExtension(nullExtension(field)).equals(value)) { return null; } else { return value; } } } } protected Object toProtoValue(Descriptors.FieldDescriptor field, Object value) { if (value == null && field.getOptions().getExtension(Extensions.nullable)) { value = field.getOptions().getExtension(nullExtension(field)); if (field.getJavaType() == Descriptors.FieldDescriptor.JavaType.ENUM) { Descriptors.EnumDescriptor enum_type = field.getEnumType(); Descriptors.EnumValueDescriptor enum_value = enum_type.findValueByNumber((Integer)value); if (enum_value == null) { PrintWriter err = (PrintWriter)RT.ERR.deref(); err.format("invalid enum number %s for enum type %s\n", value, enum_type.getFullName()); } return enum_value; } } switch (field.getJavaType()) { case LONG: return ((Number)value).longValue(); case INT: return ((Number)value).intValue(); case FLOAT: return ((Number)value).floatValue(); case DOUBLE: return ((Number)value).doubleValue(); case ENUM: String name = def.namingStrategy.protoName(value); Descriptors.EnumDescriptor enum_type = field.getEnumType(); Descriptors.EnumValueDescriptor enum_value = enum_type.findValueByName(name); if (enum_value == null) { PrintWriter err = (PrintWriter)RT.ERR.deref(); err.format("invalid enum value %s for enum type %s\n", name, enum_type.getFullName()); } return enum_value; case MESSAGE: PersistentProtocolBufferMap protobuf; if (value instanceof PersistentProtocolBufferMap) { protobuf = (PersistentProtocolBufferMap)value; } else { Def fieldDef = PersistentProtocolBufferMap.Def.create(field.getMessageType(), this.def.namingStrategy, this.def.sizeLimit); protobuf = PersistentProtocolBufferMap.construct(fieldDef, value); } return protobuf.message(); default: return value; } } static protected GeneratedMessage.GeneratedExtension<FieldOptions, ?> nullExtension( Descriptors.FieldDescriptor field) { switch (field.getJavaType()) { case LONG: return Extensions.nullLong; case INT: return Extensions.nullInt; case FLOAT: return Extensions.nullFloat; case DOUBLE: return Extensions.nullDouble; case STRING: return Extensions.nullString; case ENUM: return Extensions.nullEnum; default: return null; } } protected void addRepeatedField(DynamicMessage.Builder builder, Descriptors.FieldDescriptor field, Object value) { try { builder.addRepeatedField(field, value); } catch (Exception e) { String msg = String.format("error adding %s to %s field %s", value, field.getJavaType().toString().toLowerCase(), field.getFullName()); throw new IllegalArgumentException(msg, e); } } protected void setField(DynamicMessage.Builder builder, Descriptors.FieldDescriptor field, Object value) { try { builder.setField(field, value); } catch (IllegalArgumentException e) { String msg = String.format("error setting %s field %s to %s", field.getJavaType().toString().toLowerCase(), field.getFullName(), value); throw new IllegalArgumentException(msg, e); } } // returns true if the protobuf can store this key protected boolean addField(DynamicMessage.Builder builder, Object key, Object value) { if (key == null) { return false; } Descriptors.FieldDescriptor field = def.fieldDescriptor(key); if (field == null) { return false; } if (value == null && !(field.getOptions().getExtension(Extensions.nullable))) { return true; } boolean set = field.getOptions().getExtension(Extensions.set); if (field.isRepeated()) { builder.clearField(field); if (value instanceof Sequential && !set) { for (ISeq s = RT.seq(value); s != null; s = s.next()) { Object v = toProtoValue(field, s.first()); addRepeatedField(builder, field, v); } } else { Object map_field_by = def.mapFieldBy(field); if (map_field_by != null) { String field_name = def.namingStrategy.protoName(map_field_by); for (ISeq s = RT.seq(value); s != null; s = s.next()) { Map.Entry<?, ?> e = (Map.Entry<?, ?>)s.first(); IPersistentMap map = (IPersistentMap)e.getValue(); Object k = e.getKey(); Object v = toProtoValue(field, map.assoc(map_field_by, k).assoc(field_name, k)); addRepeatedField(builder, field, v); } } else if (field.getOptions().getExtension(Extensions.map)) { for (ISeq s = RT.seq(value); s != null; s = s.next()) { Map.Entry<?, ?> e = (Map.Entry<?, ?>)s.first(); Object[] map = {k_key, e.getKey(), k_val, e.getValue()}; addRepeatedField(builder, field, toProtoValue(field, new PersistentArrayMap(map))); } } else if (set) { Object k, v; boolean isMap = (value instanceof IPersistentMap); for (ISeq s = RT.seq(value); s != null; s = s.next()) { if (isMap) { Map.Entry<?, ?> e = (Map.Entry<?, ?>)s.first(); k = e.getKey(); v = e.getValue(); } else { k = s.first(); v = true; } Object[] map = {k_item, k, k_exists, v}; addRepeatedField(builder, field, toProtoValue(field, new PersistentArrayMap(map))); } } else { addRepeatedField(builder, field, toProtoValue(field, value)); } } } else { Object v = toProtoValue(field, value); if (v instanceof DynamicMessage) { v = ((DynamicMessage)builder.getField(field)).toBuilder().mergeFrom((DynamicMessage)v).build(); } setField(builder, field, v); } return true; } @Override public PersistentProtocolBufferMap withMeta(IPersistentMap meta) { if (meta == meta()) { return this; } return new PersistentProtocolBufferMap(meta, ext, def, message); } @Override public IPersistentMap meta() { return _meta; } @Override public boolean containsKey(Object key) { return protoContainsKey(key) || RT.booleanCast(RT.contains(ext, key)); } private boolean protoContainsKey(Object key) { Descriptors.FieldDescriptor field = def.fieldDescriptor(key); if (field == null) { return false; } else if (field.isRepeated()) { return message().getRepeatedFieldCount(field) > 0; } else { return message().hasField(field) || field.hasDefaultValue(); } } private static final Object sentinel = new Object(); @Override public IMapEntry entryAt(Object key) { Object value = valAt(key, sentinel); return (value == sentinel) ? null : new MapEntry(key, value); } @Override public Object valAt(Object key) { return getValAt(key, true); } @Override public Object valAt(Object key, Object notFound) { return getValAt(key, notFound, true); } public Object getValAt(Object key, boolean use_extensions) { Object val = getValAt(key, sentinel, use_extensions); return (val == sentinel) ? null : val; } public Object getValAt(Object key, Object notFound, boolean use_extensions) { Descriptors.FieldDescriptor field = def.fieldDescriptor(key); if (protoContainsKey(key)) { return fromProtoValue(field, message().getField(field), use_extensions); } else { return RT.get(ext, key, notFound); } } @Override public PersistentProtocolBufferMap assoc(Object key, Object value) { DynamicMessage.Builder builder = builder(); if (addField(builder, key, value)) { return new PersistentProtocolBufferMap(meta(), ext, def, builder); } else { return new PersistentProtocolBufferMap(meta(), (IPersistentMap)RT.assoc(ext, key, value), def, builder); } } @Override public PersistentProtocolBufferMap assocEx(Object key, Object value) { if (containsKey(key)) { throw new RuntimeException("Key already present"); } return assoc(key, value); } @Override public PersistentProtocolBufferMap cons(Object o) { if (o instanceof Map.Entry) { Map.Entry<?, ?> e = (Map.Entry<?, ?>)o; return assoc(e.getKey(), e.getValue()); } else if (o instanceof IPersistentVector) { IPersistentVector v = (IPersistentVector)o; if (v.count() != 2) { throw new IllegalArgumentException("Vector arg to map conj must be a pair"); } return assoc(v.nth(0), v.nth(1)); } else { DynamicMessage.Builder builder = builder(); IPersistentMap ext = this.ext; for (ISeq s = RT.seq(o); s != null; s = s.next()) { Map.Entry<?, ?> e = (Map.Entry<?, ?>)s.first(); Object k = e.getKey(), v = e.getValue(); if (!addField(builder, k, v)) { ext = (IPersistentMap)RT.assoc(ext, k, v); } } return new PersistentProtocolBufferMap(meta(), ext, def, builder); } } public PersistentProtocolBufferMap append(IPersistentMap map) { PersistentProtocolBufferMap proto; if (map instanceof PersistentProtocolBufferMap) { proto = (PersistentProtocolBufferMap)map; } else { proto = construct(def, map); } return new PersistentProtocolBufferMap(meta(), ext, def, builder().mergeFrom(proto.message())); } @Override public IPersistentMap without(Object key) { Descriptors.FieldDescriptor field = def.fieldDescriptor(key); if (field == null) { IPersistentMap newExt = (IPersistentMap)RT.dissoc(ext, key); if (newExt == ext) { return this; } return new PersistentProtocolBufferMap(meta(), newExt, def, builder()); } if (field.isRequired()) { throw new RuntimeException("Can't remove required field"); } return new PersistentProtocolBufferMap(meta(), ext, def, builder().clearField(field)); } @Override public Iterator<?> iterator() { return new SeqIterator(seq()); } @Override public int count() { int count = RT.count(ext); for (Descriptors.FieldDescriptor field : def.type.getFields()) { if (protoContainsKey(field)) { count++; } } return count; } @Override public ISeq seq() { return Seq.create(null, this, RT.seq(def.type.getFields())); } @Override public IPersistentCollection empty() { return new PersistentProtocolBufferMap(meta(), null, def, builder().clear()); } private static class Seq extends ASeq { private final PersistentProtocolBufferMap proto; private final MapEntry first; private final ISeq fields; public static ISeq create(IPersistentMap meta, PersistentProtocolBufferMap proto, ISeq fields) { for (ISeq s = fields; s != null; s = s.next()) { Descriptors.FieldDescriptor field = (Descriptors.FieldDescriptor)s.first(); Object k = proto.def.intern(field.getName()); Object v = proto.valAt(k, sentinel); if (v != sentinel) { return new Seq(meta, proto, new MapEntry(k, v), s); } } return RT.seq(proto.ext); } protected Seq(IPersistentMap meta, PersistentProtocolBufferMap proto, MapEntry first, ISeq fields) { super(meta); this.proto = proto; this.first = first; this.fields = fields; } @Override public Obj withMeta(IPersistentMap meta) { if (meta != meta()) { return new Seq(meta, proto, first, fields); } return this; } @Override public Object first() { return first; } @Override public ISeq next() { return create(meta(), proto, fields.next()); } } }
package org.voltdb.dtxn; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import org.voltcore.messaging.HeartbeatMessage; import org.voltcore.messaging.HeartbeatResponseMessage; import org.voltcore.messaging.HostMessenger; import org.voltcore.messaging.Mailbox; import org.voltcore.messaging.Subject; import org.voltcore.messaging.VoltMessage; import org.voltcore.network.Connection; import org.voltdb.ClientResponseImpl; import org.voltdb.VoltDB; import org.voltdb.client.ClientResponse; import org.voltdb.fault.FaultHandler; import org.voltdb.fault.SiteFailureFault; import org.voltdb.fault.VoltFault; import org.voltdb.fault.VoltFault.FaultType; import org.voltdb.messaging.CoalescedHeartbeatMessage; import org.voltdb.messaging.CompleteTransactionMessage; import org.voltdb.messaging.InitiateResponseMessage; import org.voltdb.utils.ResponseSampler; /** * DtxnInitiatorQueue matches incoming result set responses to outstanding * transactions, performing duplicate suppression and consistency checking * for single-partition transactions when replication is enabled. * * It currently shares/uses m_initiator's intrinsic lock to maintain * thread-safety across callers into SimpleDtxnInitiator and threads which * provide InitiateResponses via offer(). This is a bit ugly but is identical * with the synchronization mechanism that existed before the extraction of * this class, so it should JustWork(tm). */ public class DtxnInitiatorMailbox implements Mailbox { private class InitiatorNodeFailureFaultHandler implements FaultHandler { @Override public void faultOccured(Set<VoltFault> faults) { synchronized (m_initiator) { for (VoltFault fault : faults) { if (fault instanceof SiteFailureFault) { SiteFailureFault site_fault = (SiteFailureFault)fault; for (Long site : site_fault.getSiteIds()) { removeSite(site); m_safetyState.removeState(site); } } } } } } /** Map of transaction ids to transaction information */ private long m_hsId; private final Map<Long, InFlightTxnState> m_pendingTxns = new HashMap<Long, InFlightTxnState>(); private TransactionInitiator m_initiator; private final HostMessenger m_hostMessenger; private final ExecutorTxnIdSafetyState m_safetyState; /** * Storage for initiator statistics */ InitiatorStats m_stats = null; /** * Latency distribution, stored in buckets. */ LatencyStats m_latencies = null; /** * Construct a new DtxnInitiatorQueue */ public DtxnInitiatorMailbox(ExecutorTxnIdSafetyState safetyState, HostMessenger hostMessenger) { assert(safetyState != null); assert(hostMessenger != null); m_hostMessenger = hostMessenger; m_safetyState = safetyState; VoltDB.instance().getFaultDistributor(). // For Node failure, the initiators need to be ordered after the catalog // but before everything else (to prevent any new work for bad sites) registerFaultHandler(SiteFailureFault.SITE_FAILURE_INITIATOR, new InitiatorNodeFailureFaultHandler(), FaultType.SITE_FAILURE); } public ExecutorTxnIdSafetyState getSafetyState() { return m_safetyState; } public void setInitiator(TransactionInitiator initiator) { m_initiator = initiator; } public void addPendingTxn(InFlightTxnState txn) { m_pendingTxns.put(txn.txnId, txn); } public void removeSite(long siteId) { ArrayList<Long> txnIdsToRemove = new ArrayList<Long>(); for (InFlightTxnState state : m_pendingTxns.values()) { // skips txns that don't have this site as coordinator if (!state.siteIsCoordinator(siteId)) continue; // note that the site failed ClientResponseImpl toSend = state.addFailedOrRecoveringResponse(siteId); // send a response if the state wants to if (toSend != null) { enqueueResponse(toSend, state); } if (state.hasAllResponses()) { txnIdsToRemove.add(state.txnId); m_initiator.reduceBackpressure(state.messageSize); if (!state.hasSentResponse()) { assert(false); } } } for (long txnId : txnIdsToRemove) { m_pendingTxns.remove(txnId); } } private void enqueueResponse(ClientResponseImpl response, InFlightTxnState state) { response.setClientHandle(state.invocation.getClientHandle()); //Horrible but so much more efficient. final Connection c = (Connection)state.clientData; assert(c != null) : "NULL connection in connection state client data."; final long now = System.currentTimeMillis(); final int delta = (int)(now - state.initiateTime); response.setClusterRoundtrip(delta); m_stats.logTransactionCompleted( state.connectionId, state.connectionHostname, state.invocation, delta, response.getStatus()); m_latencies.logTransactionCompleted(delta); ByteBuffer buf = ByteBuffer.allocate(response.getSerializedSize() + 4); buf.putInt(buf.capacity() - 4); response.flattenToBuffer(buf).flip(); c.writeStream().enqueue(buf); } public void removeConnectionStats(long connectionId) { m_stats.removeConnectionStats(connectionId); } /** * Currently used to provide object state for the dump manager * @return A list of outstanding transaction state objects */ public List<InFlightTxnState> getInFlightTxns() { List<InFlightTxnState> retval = new ArrayList<InFlightTxnState>(); retval.addAll(m_pendingTxns.values()); return retval; } @Override public void deliver(VoltMessage message) { if (message instanceof CoalescedHeartbeatMessage) { demuxCoalescedHeartbeatMessage((CoalescedHeartbeatMessage)message); return; } ClientResponseImpl toSend = null; InFlightTxnState state = null; synchronized (m_initiator) { // update the state of seen txnids for each executor if (message instanceof HeartbeatResponseMessage) { HeartbeatResponseMessage hrm = (HeartbeatResponseMessage) message; m_safetyState.updateLastSeenTxnIdFromExecutorBySiteId( hrm.getExecHSId(), hrm.getLastReceivedTxnId(), hrm.isBlocked()); return; } // only valid messages are this and heartbeatresponse assert(message instanceof InitiateResponseMessage); final InitiateResponseMessage r = (InitiateResponseMessage) message; state = m_pendingTxns.get(r.getTxnId()); assert(m_hsId == r.getInitiatorHSId()); // if this is a dummy response, make sure the m_pendingTxns list thinks // the site has been removed from the list if (r.isRecovering()) { toSend = state.addFailedOrRecoveringResponse(r.getCoordinatorHSId()); } // otherwise update the InFlightTxnState with the response else { toSend = state.addResponse(r.getCoordinatorHSId(), r.getClientResponseData()); } if (state.isSinglePartition == false) { sendCommitNotice(toSend, state); } if (state.hasAllResponses()) { m_initiator.reduceBackpressure(state.messageSize); m_pendingTxns.remove(r.getTxnId()); // TODO make this send an error message on failure assert(state.hasSentResponse()); } } //Stop moving the response send into the initiator locked section. It isn't necessary, //and several other locks need to be acquired in the network subsystem. Bad voodoo. //addResponse returning non-null means send the response to the client if (toSend != null) { // the next bit is usually a noop, unless we're sampling responses for test if (!state.isReadOnly) ResponseSampler.offerResponse(this.getHSId(), state.txnId, state.invocation, toSend); // queue the response to be sent to the client enqueueResponse(toSend, state); } } /** * Send commit notice to all known participants again in case the * coordinator didn't see some of the sites because of rejoin. Those sites * will be blocked waiting for work. Sending this commit notice will * release those sites. * * @param toSend * @param state */ private void sendCommitNotice(final ClientResponseImpl toSend, final InFlightTxnState state) { VoltDB.instance().scheduleWork(new Runnable() { @Override public void run() { CompleteTransactionMessage ft = new CompleteTransactionMessage(getHSId(), state.firstCoordinatorId, state.txnId, state.isReadOnly, toSend.getStatus() != ClientResponse.SUCCESS, false); send(state.otherSiteIds, ft); for (long hsId : state.coordinatorReplicas) { send(hsId, ft); } } }, 0, -1, TimeUnit.SECONDS); } private void demuxCoalescedHeartbeatMessage( CoalescedHeartbeatMessage message) { final long destinations[] = message.getHeartbeatDestinations(); final HeartbeatMessage heartbeats[] = message.getHeartbeatsToDeliver(); assert(destinations.length == heartbeats.length); for (int ii = 0; ii < destinations.length; ii++) { m_hostMessenger.send(destinations[ii], heartbeats[ii]); } } @Override public void deliverFront(VoltMessage message) { throw new UnsupportedOperationException(); } @Override public VoltMessage recv() { throw new UnsupportedOperationException(); } @Override public VoltMessage recv(Subject[] s) { throw new UnsupportedOperationException(); } @Override public VoltMessage recvBlocking() { throw new UnsupportedOperationException(); } @Override public VoltMessage recvBlocking(Subject[] s) { throw new UnsupportedOperationException(); } @Override public void send(long hsId, VoltMessage message) { message.m_sourceHSId = m_hsId; m_hostMessenger.send(hsId, message); } @Override public void send(long[] hsIds, VoltMessage message) { assert(message != null); assert(hsIds != null); message.m_sourceHSId = m_hsId; m_hostMessenger.send(hsIds, message); } @Override public VoltMessage recvBlocking(long timeout) { throw new UnsupportedOperationException(); } @Override public VoltMessage recvBlocking(Subject[] s, long timeout) { throw new UnsupportedOperationException(); } @Override public long getHSId() { return m_hsId; } @Override public void setHSId(long hsId) { this.m_hsId = hsId; m_stats = new InitiatorStats(m_hsId); m_latencies = new LatencyStats(m_hsId); } Map<Long, long[]> getOutstandingTxnStats() { HashMap<Long, long[]> retval = new HashMap<Long, long[]>(); for (InFlightTxnState state : m_pendingTxns.values()) { if (!retval.containsKey(state.connectionId)) { // Default new entries to not admin/no outstanding txns retval.put(state.connectionId, new long[]{0, 0}); } retval.get(state.connectionId)[0] = (state.isAdmin ? 1 : 0); retval.get(state.connectionId)[1]++; } return retval; } }
package it.unimi.dsi.sux4j.scratch; import it.unimi.dsi.Util; import it.unimi.dsi.bits.Fast; import it.unimi.dsi.bits.LongArrayBitVector; import it.unimi.dsi.bits.TransformationStrategies; import it.unimi.dsi.bits.TransformationStrategy; import it.unimi.dsi.fastutil.ints.AbstractIntComparator; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntArrays; import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import it.unimi.dsi.fastutil.io.BinIO; import it.unimi.dsi.fastutil.longs.AbstractLongIterator; import it.unimi.dsi.fastutil.longs.LongArrayList; import it.unimi.dsi.fastutil.longs.LongBigList; import it.unimi.dsi.io.FastBufferedReader; import it.unimi.dsi.io.FileLinesCollection; import it.unimi.dsi.io.LineIterator; import it.unimi.dsi.io.OfflineIterable; import it.unimi.dsi.io.OfflineIterable.OfflineIterator; import it.unimi.dsi.io.OfflineIterable.Serializer; import it.unimi.dsi.lang.MutableString; import it.unimi.dsi.logging.ProgressLogger; import it.unimi.dsi.sux4j.bits.SparseRank; import it.unimi.dsi.sux4j.io.ChunkedHashStore; import it.unimi.dsi.sux4j.mph.AbstractHashFunction; import it.unimi.dsi.sux4j.mph.Hashes; import it.unimi.dsi.sux4j.mph.HypergraphSorter; import it.unimi.dsi.sux4j.util.EliasFanoLongBigList; import it.unimi.dsi.util.XorShift1024StarRandomGenerator; import java.io.DataInput; import java.io.DataOutput; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.Serializable; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.zip.GZIPInputStream; import org.apache.commons.lang.mutable.MutableLong; import org.apache.commons.math3.primes.Primes; import org.apache.commons.math3.random.RandomGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.martiansoftware.jsap.FlaggedOption; import com.martiansoftware.jsap.JSAP; import com.martiansoftware.jsap.JSAPException; import com.martiansoftware.jsap.JSAPResult; import com.martiansoftware.jsap.Parameter; import com.martiansoftware.jsap.SimpleJSAP; import com.martiansoftware.jsap.Switch; import com.martiansoftware.jsap.UnflaggedOption; import com.martiansoftware.jsap.stringparsers.FileStringParser; import com.martiansoftware.jsap.stringparsers.ForNameStringParser; /** * A minimal perfect hash function. * * <P>Given a list of keys without duplicates, the {@linkplain Builder builder} of this class finds a minimal * perfect hash function for the list. Subsequent calls to the {@link #getLong(Object)} method will * return a distinct number for each keys in the list. For keys out of the list, the * resulting number is not specified. In some (rare) cases it might be possible to establish that a * key was not in the original list, and in that case -1 will be returned; this behaviour * can be made standard by <em>signing</em> the function (see below). The class can then be * saved by serialisation and reused later. * * <p>This class uses a {@linkplain ChunkedHashStore chunked hash store} to provide highly scalable construction. Note that at construction time * you can {@linkplain Builder#store(ChunkedHashStore) pass a ChunkedHashStore} * containing the keys (associated with any value); however, if the store is rebuilt because of a * {@link it.unimi.dsi.sux4j.io.ChunkedHashStore.DuplicateException} it will be rebuilt associating with each key its ordinal position. * * <P>The theoretical memory requirements for the algorithm we use are 2{@link HypergraphSorter#GAMMA &gamma;}=2.46 + * o(<var>n</var>) bits per key, plus the bits for the random hashes (which are usually * negligible). The o(<var>n</var>) part is due to an embedded ranking scheme that increases space * occupancy by 0.625%, bringing the actual occupied space to around 2.68 bits per key. * * <P>As a commodity, this class provides a main method that reads from standard input a (possibly * <samp>gzip</samp>'d) sequence of newline-separated strings, and writes a serialised minimal * perfect hash function for the given list. * * <h3>Signing</h3> * * <p>Optionally, it is possible to {@linkplain Builder#signed(int) <em>sign</em>} the minimal perfect hash function. A <var>w</var>-bit signature will * be associated with each key, so that {@link #getLong(Object)} will return -1 on strings that are not * in the original key set. As usual, false positives are possible with probability 2<sup>-<var>w</var></sup>. * * <h3>How it Works</h3> * * <p>The technique used is described by Djamal Belazzougui, Fabiano C. Botelho and Martin Dietzfelbinger * in &ldquo;Hash, displace and compress&rdquo;, <i>Algorithms - ESA 2009</i>, LNCS 5757, pages 682&minus;693, 2009. * However, with respect to the algorithm described in the paper, this implementation * is much more scalable, as it uses a {@link ChunkedHashStore} * to split the generation of large key sets into generation of smaller functions for each chunk (of size * approximately 2<sup>{@value #LOG2_CHUNK_SIZE}</sup>). * * @author Sebastiano Vigna * @since 3.1.2 */ public class MinimalPerfectHashFunction<T> extends AbstractHashFunction<T> implements Serializable { private static final Logger LOGGER = LoggerFactory.getLogger( MinimalPerfectHashFunction.class ); private static final boolean ASSERTS = true; public static final long serialVersionUID = 4L; /** A builder class for {@link MinimalPerfectHashFunction}. */ public static class Builder<T> { protected Iterable<? extends T> keys; protected TransformationStrategy<? super T> transform; protected int signatureWidth; protected File tempDir; protected int lambda = 5; protected ChunkedHashStore<T> chunkedHashStore; /** Whether {@link #build()} has already been called. */ protected boolean built; /** Specifies the keys to hash; if you have specified a {@link #store(ChunkedHashStore) ChunkedHashStore}, it can be {@code null}. * * @param keys the keys to hash. * @return this builder. */ public Builder<T> keys( final Iterable<? extends T> keys ) { this.keys = keys; return this; } /** Specifies the average size of a bucket. * * @param lambda the average size of a bucket. * @return this builder. */ public Builder<T> lambda( final int lambda ) { this.lambda = lambda; return this; } /** Specifies the transformation strategy for the {@linkplain #keys(Iterable) keys to hash}. * * @param transform a transformation strategy for the {@linkplain #keys(Iterable) keys to hash}. * @return this builder. */ public Builder<T> transform( final TransformationStrategy<? super T> transform ) { this.transform = transform; return this; } /** Specifies that the resulting {@link MinimalPerfectHashFunction} should be signed using a given number of bits per key. * * @param signatureWidth a signature width, or 0 for no signature. * @return this builder. */ public Builder<T> signed( final int signatureWidth ) { this.signatureWidth = signatureWidth; return this; } /** Specifies a temporary directory for the {@link #store(ChunkedHashStore) ChunkedHashStore}. * * @param tempDir a temporary directory for the {@link #store(ChunkedHashStore) ChunkedHashStore} files, or {@code null} for the standard temporary directory. * @return this builder. */ public Builder<T> tempDir( final File tempDir ) { this.tempDir = tempDir; return this; } public Builder<T> store( final ChunkedHashStore<T> chunkedHashStore ) { this.chunkedHashStore = chunkedHashStore; return this; } public MinimalPerfectHashFunction<T> build() throws IOException { if ( built ) throw new IllegalStateException( "This builder has been already used" ); built = true; if ( transform == null ) { if ( chunkedHashStore != null ) transform = chunkedHashStore.transform(); else throw new IllegalArgumentException( "You must specify a TransformationStrategy, either explicitly or via a given ChunkedHashStore" ); } return new MinimalPerfectHashFunction<T>( keys, transform, lambda, signatureWidth, tempDir, chunkedHashStore ); } } /** The number of bits per block in the rank structure. */ public static final int BITS_PER_BLOCK = 1024; /** The logarithm of the desired chunk size. */ public final static int LOG2_CHUNK_SIZE = 16; /** The number of keys. */ protected final long n; /** The shift for chunks. */ private final int chunkShift; /** The seed used to generate the initial hash triple. */ protected final long globalSeed; /** The seed of the underlying 3-hypergraphs. */ protected final long[] seed; /** The start offset of each chunk. */ protected final long[] offset; /** The number of buckets of each chunk, stored cumulatively. */ protected final long[] numBuckets; /** The transformation strategy. */ protected final TransformationStrategy<? super T> transform; /** The displacement coefficients. */ protected final EliasFanoLongBigList coefficients; /** The sparse ranking structure containing the unused entries. */ protected final SparseRank rank; /** The mask to compare signatures, or zero for no signatures. */ protected final long signatureMask; /** The signatures. */ protected final LongBigList signatures; /** * Creates a new minimal perfect hash function for the given keys. * * @param keys the keys to hash, or {@code null}. * @param transform a transformation strategy for the keys. * @param lambda the average bucket size * @param signatureWidth a signature width, or 0 for no signature. * @param tempDir a temporary directory for the store files, or {@code null} for the standard temporary directory. * @param chunkedHashStore a chunked hash store containing the keys, or {@code null}; the store * can be unchecked, but in this case <code>keys</code> and <code>transform</code> must be non-{@code null}. */ protected MinimalPerfectHashFunction( final Iterable<? extends T> keys, final TransformationStrategy<? super T> transform, final int lambda, final int signatureWidth, final File tempDir, ChunkedHashStore<T> chunkedHashStore ) throws IOException { this.transform = transform; final ProgressLogger pl = new ProgressLogger( LOGGER ); pl.displayLocalSpeed = true; pl.displayFreeMemory = true; final RandomGenerator r = new XorShift1024StarRandomGenerator(); pl.itemsName = "keys"; final boolean givenChunkedHashStore = chunkedHashStore != null; if ( !givenChunkedHashStore ) { chunkedHashStore = new ChunkedHashStore<T>( transform, tempDir, pl ); chunkedHashStore.reset( r.nextLong() ); chunkedHashStore.addAll( keys.iterator() ); } n = chunkedHashStore.size(); defRetValue = -1; // For the very few cases in which we can decide int log2NumChunks = Math.max( 0, Fast.mostSignificantBit( n >> LOG2_CHUNK_SIZE ) ); chunkShift = chunkedHashStore.log2Chunks( log2NumChunks ); final int numChunks = 1 << log2NumChunks; LOGGER.info( "Number of chunks: " + numChunks ); LOGGER.info( "Average chunk size: " + (double)n / numChunks ); seed = new long[ numChunks ]; offset = new long[ numChunks + 1 ]; numBuckets = new long[ numChunks + 1 ]; int duplicates = 0; final LongArrayList holes = new LongArrayList(); @SuppressWarnings("resource") final OfflineIterable<MutableLong, MutableLong> coefficients = new OfflineIterable<MutableLong, MutableLong>( new Serializer<MutableLong, MutableLong>() { @Override public void write( final MutableLong a, final DataOutput dos ) throws IOException { long x = a.longValue(); while ( ( x & ~0x7FL ) != 0 ) { dos.writeByte( (int)( x | 0x80 ) ); x >>>= 7; } dos.writeByte( (int)x ); } @Override public void read( final DataInput dis, final MutableLong x ) throws IOException { byte b = dis.readByte(); long t = b & 0x7F; for ( int shift = 7; ( b & 0x80 ) != 0; shift += 7 ) { b = dis.readByte(); t |= ( b & 0x7FL ) << shift; } x.setValue( t ); } }, new MutableLong() ); for ( ;; ) { LOGGER.debug( "Generating minimal perfect hash function..." ); holes.clear(); coefficients.clear(); pl.expectedUpdates = numChunks; pl.itemsName = "chunks"; pl.start( "Analysing chunks... " ); try { int chunkNumber = 0; for ( ChunkedHashStore.Chunk chunk : chunkedHashStore ) { /* We treat a chunk as a single hash function. The number of bins is thus * the first prime larger than the chunk size divided by the load factor. */ final int p = Primes.nextPrime( chunk.size() ); final boolean used[] = new boolean[ p ]; final int numBuckets = ( chunk.size() + lambda - 1 ) / lambda; this.numBuckets[ chunkNumber + 1 ] = this.numBuckets[ chunkNumber ] + numBuckets; final int[] cc0 = new int[ numBuckets ]; final int[] cc1 = new int[ numBuckets ]; @SuppressWarnings("unchecked") final ArrayList<long[]>[] bucket = new ArrayList[ numBuckets ]; for( int i = bucket.length; i-- != 0; ) bucket[ i ] = new ArrayList<long[]>(); tryChunk: for(;;) { for( ArrayList<long[]> b : bucket ) b.clear(); Arrays.fill( used, false ); /* At each try, the allocation to keys to bucket is randomized differently. */ final long seed = r.nextLong(); // System.err.println( "Number of keys: " + chunk.size() + " Number of bins: " + p + " seed: " + seed ); /* We distribute the keys in this chunks in the buckets. */ for( Iterator<long[]> iterator = chunk.iterator(); iterator.hasNext(); ) { final long[] triple = iterator.next(); final long[] h = new long[ 3 ]; Hashes.jenkins( triple, seed, h ); final ArrayList<long[]> b = bucket[ (int)( ( h[ 0 ] >>> 1 ) % numBuckets ) ]; h[ 1 ] = (int)( ( h[ 1 ] >>> 1 ) % p ); h[ 2 ] = (int)( ( h[ 2 ] >>> 1 ) % ( p - 1 ) ) + 1; // All elements in a bucket must have either different h[ 1 ] or different h[ 2 ] for( long[] t: b ) if ( t[ 1 ] == h[ 1 ] && t[ 2 ] == h[ 2 ] ) { LOGGER.info( "Duplicate index" + Arrays.toString( t ) ); continue tryChunk; } b.add( h ); } final int[] perm = Util.identity( bucket.length ); IntArrays.quickSort( perm, new AbstractIntComparator() { @Override public int compare( int a0, int a1 ) { return Integer.compare( bucket[ a1 ].size(), bucket[ a0 ].size() ); } } ); for( int i = 0; i < perm.length; ) { final LinkedList<Integer> bucketsToDo = new LinkedList<Integer>(); final int size = bucket[ perm[ i ] ].size(); //System.err.println( "Bucket size: " + size ); int j; // Gather indices of all buckets with the same size for( j = i; j < perm.length && bucket[ perm[ j ] ].size() == size; j++ ) bucketsToDo.add( Integer.valueOf( perm[ j ] ) ); // Examine for each pair (c0,c1) the buckets still to do ext: for( int c1 = 0; c1 < p; c1++ ) for( int c0 = 0; c0 < p; c0++ ) { //System.err.println( "Testing " + c0 + ", " + c1 + " (to do: " + bucketsToDo.size() + ")" ); for( Iterator<Integer> iterator = bucketsToDo.iterator(); iterator.hasNext(); ) { final int k = iterator.next().intValue(); final ArrayList<long[]> b = bucket[ k ]; boolean completed = true; final IntArrayList done = new IntArrayList(); // Try to see whether the necessary entries are not used for( long[] h: b ) { //assert k == h[ 0 ]; int pos = (int)( ( h[ 1 ] + c0 * h[ 2 ] + c1 ) % p ); //System.err.println( "Testing pos " + pos + " for " + Arrays.toString( e )); if ( used[ pos ] ) { completed = false; break; } else { used[ pos ] = true; done.add( pos ); } } if ( completed ) { // All positions were free cc0[ k ] = c0; cc1[ k ] = c1; iterator.remove(); } else for( int d: done ) used[ d ] = false; } if ( bucketsToDo.isEmpty() ) break ext; } if ( ! bucketsToDo.isEmpty() ) continue tryChunk; this.seed[ chunkNumber ] = seed; i = j; } break; } // System.err.println("DONE!"); if ( ASSERTS ) { final IntOpenHashSet pos = new IntOpenHashSet(); final long h[] = new long[ 3 ]; for( Iterator<long[]> iterator = chunk.iterator(); iterator.hasNext(); ) { final long[] triple = iterator.next(); Hashes.jenkins( triple, seed[ chunkNumber ], h ); h[ 0 ] = ( h[ 0 ] >>> 1 ) % numBuckets; h[ 1 ] = (int)( ( h[ 1 ] >>> 1 ) % p ); h[ 2 ] = (int)( ( h[ 2 ] >>> 1 ) % ( p - 1 ) ) + 1; //System.err.println( Arrays.toString( e ) ); assert pos.add( (int)( ( h[ 1 ] + cc0[ (int)( h[ 0 ] ) ] * h[ 2 ] + cc1[ (int)( h[ 0 ] ) ] ) % p ) ); } } final MutableLong l = new MutableLong(); for( int i = 0; i < numBuckets; i++ ) { l.setValue( cc0[ i ] + cc1[ i ] * p ); coefficients.add( l ); } for( int i = 0; i < p; i++ ) if ( ! used[ i ] ) holes.add( offset[ chunkNumber ] + i ); offset[ chunkNumber + 1 ] = offset[ chunkNumber ] + p; chunkNumber++; pl.update(); } pl.done(); break; } catch ( ChunkedHashStore.DuplicateException e ) { if ( keys == null ) throw new IllegalStateException( "You provided no keys, but the chunked hash store was not checked" ); if ( duplicates++ > 3 ) throw new IllegalArgumentException( "The input list contains duplicates" ); LOGGER.warn( "Found duplicate. Recomputing triples..." ); chunkedHashStore.reset( r.nextLong() ); chunkedHashStore.addAll( keys.iterator() ); } } rank = new SparseRank( offset[ offset.length - 1 ], holes.size(), holes.iterator() ); globalSeed = chunkedHashStore.seed(); this.coefficients = new EliasFanoLongBigList( new AbstractLongIterator() { final OfflineIterator<MutableLong, MutableLong> iterator = coefficients.iterator(); @Override public boolean hasNext() { return iterator.hasNext(); } public long nextLong() { return iterator.next().longValue(); } }, 0 ); coefficients.close(); LOGGER.info( "Completed." ); LOGGER.info( "Actual bit cost per key: " + (double)numBits() / n ); if ( signatureWidth != 0 ) { signatureMask = -1L >>> Long.SIZE - signatureWidth; ( signatures = LongArrayBitVector.getInstance().asLongBigList( signatureWidth ) ).size( n ); pl.expectedUpdates = n; pl.itemsName = "signatures"; pl.start( "Signing..." ); for ( ChunkedHashStore.Chunk chunk : chunkedHashStore ) { Iterator<long[]> iterator = chunk.iterator(); for( int i = chunk.size(); i final long[] triple = iterator.next(); long t = getLongByTripleNoCheck( triple ); signatures.set( t, signatureMask & triple[ 0 ] ); pl.lightUpdate(); } } pl.done(); } else { signatureMask = 0; signatures = null; } if ( !givenChunkedHashStore ) chunkedHashStore.close(); } /** * Returns the number of bits used by this structure. * * @return the number of bits used by this structure. */ public long numBits() { return seed.length * Long.SIZE + offset.length * Long.SIZE + coefficients.numBits() + numBuckets.length * Long.SIZE + rank.numBits(); } @SuppressWarnings("unchecked") public long getLong( final Object key ) { if ( n == 0 ) return defRetValue; final long[] triple = new long[ 3 ]; Hashes.jenkins( transform.toBitVector( (T)key ), globalSeed, triple ); final int chunk = chunkShift == Long.SIZE ? 0 : (int)( triple[ 0 ] >>> chunkShift ); final long chunkOffset = offset[ chunk ]; final int p = (int)( offset[ chunk + 1 ] - chunkOffset ); final long[] h = new long[ 3 ]; Hashes.jenkins( triple, seed[ chunk ], h ); h[ 1 ] = (int)( ( h[ 1 ] >>> 1 ) % p ); h[ 2 ] = (int)( ( h[ 2 ] >>> 1 ) % ( p - 1 ) ) + 1; final long c = coefficients.getLong( numBuckets[ chunk ] + ( h[ 0 ] >>> 1 ) % ( numBuckets[ chunk + 1 ] - numBuckets[ chunk ] ) ); long result = chunkOffset + (int)( ( h[ 1 ] + ( c % p ) * h[ 2 ] + c / p ) % p ); result -= rank.rank( result ); if ( signatureMask != 0 ) return result >= n || ( ( signatures.getLong( result ) ^ triple[ 0 ] ) & signatureMask ) != 0 ? defRetValue : result; // Out-of-set strings can generate bizarre 3-hyperedges. return result < n ? result : defRetValue; } /** A dirty function replicating the behaviour of {@link #getLongByTriple(long[])} but skipping the * signature test. Used in the constructor. <strong>Must</strong> be kept in sync with {@link #getLongByTriple(long[])}. */ private long getLongByTripleNoCheck( final long[] triple ) { final int chunk = chunkShift == Long.SIZE ? 0 : (int)( triple[ 0 ] >>> chunkShift ); final long chunkOffset = offset[ chunk ]; final int p = (int)( offset[ chunk + 1 ] - chunkOffset ); final long[] h = new long[ 3 ]; Hashes.jenkins( triple, seed[ chunk ], h ); h[ 1 ] = (int)( ( h[ 1 ] >>> 1 ) % p ); h[ 2 ] = (int)( ( h[ 2 ] >>> 1 ) % ( p - 1 ) ) + 1; final long c = coefficients.getLong( numBuckets[ chunk ] + ( h[ 0 ] >>> 1 ) % ( numBuckets[ chunk + 1 ] - numBuckets[ chunk ] ) ); final long result = chunkOffset + (int)( ( h[ 1 ] + ( c % p ) * h[ 2 ] + c / p ) % p ); return result - rank.rank( result ); } public long size64() { return n; } private void readObject( final ObjectInputStream s ) throws IOException, ClassNotFoundException { s.defaultReadObject(); } public static void main( final String[] arg ) throws NoSuchMethodException, IOException, JSAPException { final SimpleJSAP jsap = new SimpleJSAP( MinimalPerfectHashFunction.class.getName(), "Builds a minimal perfect hash function reading a newline-separated list of strings.", new Parameter[] { new FlaggedOption( "encoding", ForNameStringParser.getParser( Charset.class ), "UTF-8", JSAP.NOT_REQUIRED, 'e', "encoding", "The string file encoding." ), new FlaggedOption( "tempDir", FileStringParser.getParser(), JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'T', "temp-dir", "A directory for temporary files." ), new Switch( "iso", 'i', "iso", "Use ISO-8859-1 coding internally (i.e., just use the lower eight bits of each character)." ), new Switch( "utf32", JSAP.NO_SHORTFLAG, "utf-32", "Use UTF-32 internally (handles surrogate pairs)." ), new FlaggedOption( "signatureWidth", JSAP.INTEGER_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 's', "signature-width", "If specified, the signature width in bits." ), new Switch( "zipped", 'z', "zipped", "The string list is compressed in gzip format." ), new UnflaggedOption( "function", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, JSAP.NOT_GREEDY, "The filename for the serialised minimal perfect hash function." ), new UnflaggedOption( "stringFile", JSAP.STRING_PARSER, "-", JSAP.NOT_REQUIRED, JSAP.NOT_GREEDY, "The name of a file containing a newline-separated list of strings, or - for standard input; in the first case, strings will not be loaded into core memory." ), } ); JSAPResult jsapResult = jsap.parse( arg ); if ( jsap.messagePrinted() ) return; final String functionName = jsapResult.getString( "function" ); final String stringFile = jsapResult.getString( "stringFile" ); final Charset encoding = (Charset)jsapResult.getObject( "encoding" ); final boolean zipped = jsapResult.getBoolean( "zipped" ); final boolean iso = jsapResult.getBoolean( "iso" ); final boolean utf32 = jsapResult.getBoolean( "utf32" ); final int signatureWidth = jsapResult.getInt( "signatureWidth", 0 ); final Collection<MutableString> collection; if ( "-".equals( stringFile ) ) { final ProgressLogger pl = new ProgressLogger( LOGGER ); pl.displayLocalSpeed = true; pl.displayFreeMemory = true; pl.start( "Loading strings..." ); collection = new LineIterator( new FastBufferedReader( new InputStreamReader( zipped ? new GZIPInputStream( System.in ) : System.in, encoding ) ), pl ).allLines(); pl.done(); } else collection = new FileLinesCollection( stringFile, encoding.toString(), zipped ); final TransformationStrategy<CharSequence> transformationStrategy = iso ? TransformationStrategies.iso() : utf32 ? TransformationStrategies.utf32() : TransformationStrategies.utf16(); BinIO.storeObject( new MinimalPerfectHashFunction<CharSequence>( collection, transformationStrategy, 5, signatureWidth, jsapResult.getFile( "tempDir"), null ), functionName ); LOGGER.info( "Saved." ); } }
package org.xins.server; /** * Constants referring to all existing <code>ResponderState</code> * instances. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) */ public interface ResponderStates { /** * Uninitialized state. In this state no output can be written. */ final static ResponderState UNINITIALIZED = new ResponderState("uninitialized"); /** * Initial state, before response output is started. */ final static ResponderState BEFORE_START = new ResponderState("before start"); /** * State active when the output parameters can be written. This states * comes after {@link #BEFORE_START}. */ final static ResponderState WITHIN_PARAMS = new ResponderState("within params"); /** * State within the data section when a start tag has been opened, but not * closed yet. This state comes after {@link #WITHIN_PARAMS}. */ final static ResponderState START_TAG_OPEN = new ResponderState("start tag open"); /** * State within the data section after a start tag has been closed, but the * root element has not been closed yet. This state comes after * {@link #START_TAG_OPEN}. */ final static ResponderState WITHIN_ELEMENT = new ResponderState("within element"); /** * Final state, after response output is finished. */ final static ResponderState AFTER_END = new ResponderState("after end"); /** * Error state. Entered if an exception is thrown within an output method. */ final static ResponderState ERROR = new ResponderState("error"); }
package info.curtbinder.reefangel.phone; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionException; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.database.CursorIndexOutOfBoundsException; import android.database.SQLException; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; import android.widget.ToggleButton; public class StatusActivity extends Activity implements OnClickListener { private static final String TAG = "RAStatus"; RAApplication rapp; // Display views private View refreshButton; private TextView updateTime; // private TextView messageText; private TextView t1Text; private TextView t2Text; private TextView t3Text; private TextView phText; private TextView dpText; private TextView apText; private TextView salinityText; private TextView t1Label; private TextView t2Label; private TextView t3Label; private TextView dpLabel; private TextView apLabel; private TextView salinityLabel; private TextView[] mainPortLabels = new TextView[8]; private ToggleButton[] mainPortBtns = new ToggleButton[8]; private View[] mainPortMaskBtns = new View[8]; // Threading private Handler guiThread; private ExecutorService statusThread; private Runnable updateTask; @SuppressWarnings("rawtypes") private Future statusPending; private String controllerCommand; private boolean updateStatusScreen; // Message Receivers StatusReceiver receiver; IntentFilter filter; // View visibility // private boolean showMessageText; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.status); rapp = (RAApplication) getApplication(); // Message Receiver stuff receiver = new StatusReceiver(); filter = new IntentFilter(ControllerTask.UPDATE_DISPLAY_DATA_INTENT); filter.addAction(ControllerTask.UPDATE_STATUS_INTENT); filter.addAction(ControllerTask.ERROR_MESSAGE_INTENT); findViews(); initThreading(); updateViewsVisibility(); setOnClickListeners(); } @Override protected void onPause() { super.onPause(); unregisterReceiver(receiver); } @Override protected void onResume() { super.onResume(); registerReceiver(receiver, filter); updateDisplay(); } private void findViews() { refreshButton = findViewById(R.id.refresh_button); updateTime = (TextView) findViewById(R.id.updated); t1Text = (TextView) findViewById(R.id.temp1); t2Text = (TextView) findViewById(R.id.temp2); t3Text = (TextView) findViewById(R.id.temp3); phText = (TextView) findViewById(R.id.ph); dpText = (TextView) findViewById(R.id.dp); apText = (TextView) findViewById(R.id.ap); salinityText = (TextView) findViewById(R.id.salinity); t1Label = (TextView) findViewById(R.id.t1_label); t2Label = (TextView) findViewById(R.id.t2_label); t3Label = (TextView) findViewById(R.id.t3_label); dpLabel = (TextView) findViewById(R.id.dp_label); apLabel = (TextView) findViewById(R.id.ap_label); salinityLabel = (TextView) findViewById(R.id.salinity_label); mainPortLabels[0] = (TextView) findViewById(R.id.main_port1_label); mainPortLabels[1] = (TextView) findViewById(R.id.main_port2_label); mainPortLabels[2] = (TextView) findViewById(R.id.main_port3_label); mainPortLabels[3] = (TextView) findViewById(R.id.main_port4_label); mainPortLabels[4] = (TextView) findViewById(R.id.main_port5_label); mainPortLabels[5] = (TextView) findViewById(R.id.main_port6_label); mainPortLabels[6] = (TextView) findViewById(R.id.main_port7_label); mainPortLabels[7] = (TextView) findViewById(R.id.main_port8_label); mainPortBtns[0] = (ToggleButton) findViewById(R.id.main_port1); mainPortBtns[1] = (ToggleButton) findViewById(R.id.main_port2); mainPortBtns[2] = (ToggleButton) findViewById(R.id.main_port3); mainPortBtns[3] = (ToggleButton) findViewById(R.id.main_port4); mainPortBtns[4] = (ToggleButton) findViewById(R.id.main_port5); mainPortBtns[5] = (ToggleButton) findViewById(R.id.main_port6); mainPortBtns[6] = (ToggleButton) findViewById(R.id.main_port7); mainPortBtns[7] = (ToggleButton) findViewById(R.id.main_port8); mainPortMaskBtns[0] = findViewById(R.id.main_port1mask); mainPortMaskBtns[1] = findViewById(R.id.main_port2mask); mainPortMaskBtns[2] = findViewById(R.id.main_port3mask); mainPortMaskBtns[3] = findViewById(R.id.main_port4mask); mainPortMaskBtns[4] = findViewById(R.id.main_port5mask); mainPortMaskBtns[5] = findViewById(R.id.main_port6mask); mainPortMaskBtns[6] = findViewById(R.id.main_port7mask); mainPortMaskBtns[7] = findViewById(R.id.main_port8mask); } private void setOnClickListeners() { refreshButton.setOnClickListener(this); for (int i = 0; i < 8; i++) { if (isController()) { mainPortBtns[i].setOnClickListener(this); mainPortMaskBtns[i].setOnClickListener(this); } else { mainPortBtns[i].setClickable(false); mainPortMaskBtns[i].setClickable(false); } } } private void updateViewsVisibility() { // updates all the views visibility based on user settings // get values from Preferences // showMessageText = false; // Labels t1Label.setText(rapp.getPrefT1Label()); t2Label.setText(rapp.getPrefT2Label()); t3Label.setText(rapp.getPrefT3Label()); dpLabel.setText(rapp.getPrefDPLabel()); apLabel.setText(rapp.getPrefAPLabel()); setMainRelayLabels(); // Visibility if (rapp.getPrefT2Visibility()) { Log.d(TAG, "T2 visible"); t2Text.setVisibility(View.VISIBLE); t2Label.setVisibility(View.VISIBLE); } else { Log.d(TAG, "T2 gone"); t2Text.setVisibility(View.GONE); t2Label.setVisibility(View.GONE); } if (rapp.getPrefT3Visibility()) { Log.d(TAG, "T3 visible"); t3Text.setVisibility(View.VISIBLE); t3Label.setVisibility(View.VISIBLE); } else { Log.d(TAG, "T3 gone"); t3Text.setVisibility(View.GONE); t3Label.setVisibility(View.GONE); } if (rapp.getPrefDPVisibility()) { Log.d(TAG, "DP visible"); dpText.setVisibility(View.VISIBLE); dpLabel.setVisibility(View.VISIBLE); } else { Log.d(TAG, "DP gone"); dpText.setVisibility(View.GONE); dpLabel.setVisibility(View.GONE); } if (rapp.getPrefAPVisibility()) { Log.d(TAG, "AP visible"); apText.setVisibility(View.VISIBLE); apLabel.setVisibility(View.VISIBLE); } else { Log.d(TAG, "AP gone"); apText.setVisibility(View.GONE); apLabel.setVisibility(View.GONE); } if (rapp.getPrefSalinityVisibility()) { Log.d(TAG, "Salinity visible"); salinityText.setVisibility(View.VISIBLE); salinityLabel.setVisibility(View.VISIBLE); } else { Log.d(TAG, "Salinity gone"); salinityText.setVisibility(View.GONE); salinityLabel.setVisibility(View.GONE); } // if ( ! showMessageText ) // messageText.setVisibility(View.GONE); } private void setMainRelayLabels() { for (int i = 0; i < 8; i++) { mainPortLabels[i].setText(rapp.getPrefMainRelayLabel(i + 1)); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.refresh_button: // launch the update Log.d(TAG, "onClick Refresh button"); launchStatusTask(); break; case R.id.main_port1: Log.d(TAG, "toggle port 1"); sendRelayToggleTask(1); break; case R.id.main_port2: Log.d(TAG, "toggle port 2"); sendRelayToggleTask(2); break; case R.id.main_port3: Log.d(TAG, "toggle port 3"); sendRelayToggleTask(3); break; case R.id.main_port4: Log.d(TAG, "toggle port 4"); sendRelayToggleTask(4); break; case R.id.main_port5: Log.d(TAG, "toggle port 5"); sendRelayToggleTask(5); break; case R.id.main_port6: Log.d(TAG, "toggle port 6"); sendRelayToggleTask(6); break; case R.id.main_port7: Log.d(TAG, "toggle port 7"); sendRelayToggleTask(7); break; case R.id.main_port8: Log.d(TAG, "toggle port 8"); sendRelayToggleTask(8); break; case R.id.main_port1mask: Log.d(TAG, "clear mask 1"); sendRelayClearMaskTask(1); break; case R.id.main_port2mask: Log.d(TAG, "clear mask 2"); sendRelayClearMaskTask(2); break; case R.id.main_port3mask: Log.d(TAG, "clear mask 3"); sendRelayClearMaskTask(3); break; case R.id.main_port4mask: Log.d(TAG, "clear mask 4"); sendRelayClearMaskTask(4); break; case R.id.main_port5mask: Log.d(TAG, "clear mask 5"); sendRelayClearMaskTask(5); break; case R.id.main_port6mask: Log.d(TAG, "clear mask 6"); sendRelayClearMaskTask(6); break; case R.id.main_port7mask: Log.d(TAG, "clear mask 7"); sendRelayClearMaskTask(7); break; case R.id.main_port8mask: Log.d(TAG, "clear mask 8"); sendRelayClearMaskTask(8); break; } } private void sendRelayToggleTask(int port) { Log.d(TAG, "sendRelayToggleTask"); int status = Relay.PORT_STATE_OFF; if (mainPortBtns[port - 1].isChecked()) { status = Relay.PORT_STATE_ON; } launchRelayToggleTask(port, status); } private void sendRelayClearMaskTask(int port) { Log.d(TAG, "sendRelayClearMaskTask"); // hide ourself and clear the mask mainPortMaskBtns[port - 1].setVisibility(View.INVISIBLE); launchRelayToggleTask(port, Relay.PORT_STATE_AUTO); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_R: // launch the update Log.d(TAG, "onKeyDown R"); launchStatusTask(); break; default: return super.onKeyDown(keyCode, event); } return true; } private void initThreading() { // TODO move to Service thread guiThread = new Handler(); statusThread = Executors.newSingleThreadExecutor(); controllerCommand = ""; updateStatusScreen = true; updateTask = new Runnable() { public void run() { // Task to be run // Cancel any previous status check if exists if (statusPending != null) statusPending.cancel(true); try { // Get IP & Port Host h = new Host(); if (isController()) { // controller h.setHost(rapp.getPrefHost()); h.setPort(rapp.getPrefPort()); } else { // reeefangel.com h.setUserId(rapp.getPrefUserId()); } h.setCommand(controllerCommand); Log.d(TAG, "Task Host: " + h.toString()); // Create ControllerTask ControllerTask cTask = new ControllerTask(rapp, h, updateStatusScreen); statusPending = statusThread.submit(cTask); // Add ControllerTask to statusThread to be run } catch (RejectedExecutionException e) { Log.e(TAG, "initThreading RejectedExecution"); updateTime.setText(R.string.messageError); } } }; } private void launchStatusTask() { /** * Creates the thread that communicates with the controller Then that * function calls updateDisplay when it finishes */ Log.d(TAG, "launchStatusTask"); // cancel any previous update if it hasn't started yet guiThread.removeCallbacks(updateTask); // set the command to be executed if (isController()) { controllerCommand = Globals.requestStatus; } else { controllerCommand = Globals.requestReefAngel; } updateStatusScreen = true; // start an update guiThread.post(updateTask); } private void launchRelayToggleTask(int relay, int status) { Log.d(TAG, "launchRelayToggleTask"); // cancel any previous update if it hasn't started yet guiThread.removeCallbacks(updateTask); // set the command to be executed if (isController()) { controllerCommand = new String(String.format("%s%d%d", Globals.requestRelay, relay, status)); } else { controllerCommand = Globals.requestReefAngel; } updateStatusScreen = true; Log.d(TAG, "RelayCommand: " + controllerCommand); // start an update guiThread.post(updateTask); } private boolean isController() { // TODO move to application? String[] devicesArray = rapp.getResources().getStringArray( R.array.devicesValues); String device = rapp.getPrefDevice(); boolean b = false; if (device.equals(devicesArray[0])) { b = true; } return b; } public void updateDisplay() { Log.d(TAG, "updateDisplay"); try { Cursor c = rapp.getRAData().getLatestData(); String[] values; short r, ron, roff; Relay relay = new Relay(); if (c.moveToFirst()) { values = new String[] { c.getString(c.getColumnIndex(RAData.PCOL_LOGDATE)), c.getString(c.getColumnIndex(RAData.PCOL_T1)), c.getString(c.getColumnIndex(RAData.PCOL_T2)), c.getString(c.getColumnIndex(RAData.PCOL_T3)), c.getString(c.getColumnIndex(RAData.PCOL_PH)), c.getString(c.getColumnIndex(RAData.PCOL_DP)), c.getString(c.getColumnIndex(RAData.PCOL_AP)), c.getString(c.getColumnIndex(RAData.PCOL_SAL)) }; r = c.getShort(c.getColumnIndex(RAData.PCOL_RDATA)); ron = c.getShort(c.getColumnIndex(RAData.PCOL_RONMASK)); roff = c.getShort(c.getColumnIndex(RAData.PCOL_ROFFMASK)); } else { values = getNeverValues(); r = ron = roff = 0; } c.close(); loadDisplayedControllerValues(values); relay.setRelayData(r, ron, roff); updateMainRelayValues(relay); } catch (SQLException e) { Log.d(TAG, "SQLException: " + e.getMessage()); } catch (CursorIndexOutOfBoundsException e) { Log.d(TAG, "CursorIndex out of bounds: " + e.getMessage()); } } private void insertData(Intent i) { ContentValues v = new ContentValues(); v.put(RAData.PCOL_T1, i.getStringExtra(RAData.PCOL_T1)); v.put(RAData.PCOL_T2, i.getStringExtra(RAData.PCOL_T2)); v.put(RAData.PCOL_T3, i.getStringExtra(RAData.PCOL_T3)); v.put(RAData.PCOL_PH, i.getStringExtra(RAData.PCOL_PH)); v.put(RAData.PCOL_DP, i.getStringExtra(RAData.PCOL_DP)); v.put(RAData.PCOL_AP, i.getStringExtra(RAData.PCOL_AP)); v.put(RAData.PCOL_SAL, i.getStringExtra(RAData.PCOL_SAL)); v.put(RAData.PCOL_ATOHI, i.getBooleanExtra(RAData.PCOL_ATOHI, false)); v.put(RAData.PCOL_ATOLO, i.getBooleanExtra(RAData.PCOL_ATOLO, false)); v.put(RAData.PCOL_LOGDATE, i.getStringExtra(RAData.PCOL_LOGDATE)); v.put(RAData.PCOL_RDATA, i.getShortExtra(RAData.PCOL_RDATA, (short)0)); v.put(RAData.PCOL_RONMASK, i.getShortExtra(RAData.PCOL_RONMASK, (short)0)); v.put(RAData.PCOL_ROFFMASK, i.getShortExtra(RAData.PCOL_ROFFMASK, (short)0)); rapp.getRAData().insert(v); } class StatusReceiver extends BroadcastReceiver { private final String TAG = StatusReceiver.class.getSimpleName(); @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "onReceive"); String action = intent.getAction(); if ( action.equals(ControllerTask.UPDATE_STATUS_INTENT) ) { Log.d(TAG, "update status intent"); int id = intent.getIntExtra(ControllerTask.UPDATE_STATUS_ID, R.string.defaultStatusText); updateTime.setText(getResources().getString(id)); } else if ( action.equals(ControllerTask.UPDATE_DISPLAY_DATA_INTENT) ) { Log.d(TAG, "update data intent"); insertData(intent); updateDisplay(); } else if ( action.equals(ControllerTask.ERROR_MESSAGE_INTENT) ) { Log.d(TAG, "error message intent"); updateTime.setText(intent.getStringExtra(ControllerTask.ERROR_MESSAGE_STRING)); } } } private void updateMainRelayValues(Relay r) { short status; String s; String s1; boolean useMask = isController(); for (int i = 0; i < 8; i++) { status = r.getPortStatus(i + 1); if (status == Relay.PORT_STATE_ON) { s1 = "ON"; } else if (status == Relay.PORT_STATE_AUTO) { s1 = "AUTO"; } else { s1 = "OFF"; } s = new String(String.format("Port %d: %s(%s)", i + 1, r.isPortOn(i + 1, useMask) ? "ON" : "OFF", s1)); Log.d(TAG, s); mainPortBtns[i].setChecked(r.isPortOn(i + 1, useMask)); if (((status == Relay.PORT_ON) || (status == Relay.PORT_STATE_OFF)) && useMask) { // masked on or off, show button mainPortMaskBtns[i].setVisibility(View.VISIBLE); } else { mainPortMaskBtns[i].setVisibility(View.INVISIBLE); } } } private void loadDisplayedControllerValues(String[] v) { // The order must match with the order in getDisplayedControllerValues updateTime.setText(v[0]); t1Text.setText(v[1]); t2Text.setText(v[2]); t3Text.setText(v[3]); phText.setText(v[4]); dpText.setText(v[5]); apText.setText(v[6]); salinityText.setText(v[7]); } private String[] getNeverValues() { return new String[] { getString(R.string.messageNever), getString(R.string.defaultStatusText), getString(R.string.defaultStatusText), getString(R.string.defaultStatusText), getString(R.string.defaultStatusText), getString(R.string.defaultStatusText), getString(R.string.defaultStatusText), getString(R.string.defaultStatusText) }; } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.settings: // launch settings Log.d(TAG, "Menu Settings clicked"); startActivity(new Intent(this, PrefsActivity.class)); break; case R.id.about: // launch about box Log.d(TAG, "Menu About clicked"); startActivity(new Intent(this, AboutActivity.class)); break; case R.id.params: Log.d(TAG, "Menu Parameters clicked"); startActivity(new Intent(this, ParamsListActivity.class)); break; /* * case R.id.memory: // launch memory Log.d(TAG, "Memory clicked"); * startActivity(new Intent(this, Memory.class)); break; */ default: return super.onOptionsItemSelected(item); } return true; } }
package com.couchbase.lite; import android.content.res.Resources; import com.couchbase.lite.util.Log; import junit.framework.Assert; import org.apache.commons.io.IOUtils; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class ApiTest extends LiteTestCase { private int changeCount = 0; //SERVER & DOCUMENTS public void testAPIManager() throws Exception { Manager manager = this.manager; Assert.assertTrue(manager != null); for(String dbName : manager.getAllDatabaseNames()){ Database db = manager.getDatabase(dbName); Log.i(TAG, "Database '" + dbName + "':" + db.getDocumentCount() + " documents"); } ManagerOptions options= new ManagerOptions(); options.setReadOnly(true); Manager roManager=new Manager(new File(manager.getDirectory()), options); Assert.assertTrue(roManager!=null); Database db =roManager.getDatabase("foo"); Assert.assertNull(db); List<String> dbNames=manager.getAllDatabaseNames(); Assert.assertFalse(dbNames.contains("foo")); Assert.assertTrue(dbNames.contains(DEFAULT_TEST_DB)); } public void testCreateDocument() throws CouchbaseLiteException { Map<String,Object> properties = new HashMap<String,Object>(); properties.put("testName", "testCreateDocument"); properties.put("tag", 1337); Database db = startDatabase(); Document doc=createDocumentWithProperties(db, properties); String docID=doc.getId(); assertTrue("Invalid doc ID: " + docID, docID.length() > 10); String currentRevisionID=doc.getCurrentRevisionId(); assertTrue("Invalid doc revision: " + docID, currentRevisionID.length() > 10); assertEquals(doc.getUserProperties(), properties); assertEquals(db.getDocument(docID), doc); db.clearDocumentCache();// so we can load fresh copies Document doc2 = db.getExistingDocument(docID); assertEquals(doc2.getId(), docID); assertEquals(doc2.getCurrentRevisionId(), currentRevisionID); assertNull(db.getExistingDocument("b0gus")); } public void testDeleteDatabase() throws Exception { Database deleteme = manager.getDatabase("deleteme"); assertTrue(deleteme.exists()); deleteme.delete(); assertFalse(deleteme.exists()); deleteme.delete(); // delete again, even though already deleted Database deletemeFetched = manager.getExistingDatabase("deleteme"); assertNull(deletemeFetched); } public void testDatabaseCompaction() throws Exception{ Map<String,Object> properties = new HashMap<String,Object>(); properties.put("testName", "testDatabaseCompaction"); properties.put("tag", 1337); Document doc=createDocumentWithProperties(database, properties); SavedRevision rev1 = doc.getCurrentRevision(); Map<String,Object> properties2 = new HashMap<String,Object>(properties); properties2.put("tag", 4567); SavedRevision rev2 = rev1.createRevision(properties2); database.compact(); Document fetchedDoc = database.getDocument(doc.getId()); List<SavedRevision> revisions = fetchedDoc.getRevisionHistory(); for (SavedRevision revision : revisions) { if (revision.getId().equals(rev1)) { assertFalse(revision.arePropertiesAvailable()); } if (revision.getId().equals(rev2)) { assertTrue(revision.arePropertiesAvailable()); } } } public void testDocumentCache() throws Exception{ Database db = startDatabase(); Document doc = db.createDocument(); UnsavedRevision rev1 = doc.createRevision(); Map<String, Object> rev1Properties = new HashMap<String, Object>(); rev1Properties.put("foo", "bar"); rev1.setUserProperties(rev1Properties); SavedRevision savedRev1 = rev1.save(); String documentId = savedRev1.getDocument().getId(); // getting the document puts it in cache Document docRev1 = db.getExistingDocument(documentId); UnsavedRevision rev2 = docRev1.createRevision(); Map<String, Object> rev2Properties = rev2.getProperties(); rev2Properties.put("foo", "baz"); rev2.setUserProperties(rev2Properties); rev2.save(); Document docRev2 = db.getExistingDocument(documentId); assertEquals("baz", docRev2.getProperty("foo")); } public void testCreateRevisions() throws Exception{ Map<String,Object> properties = new HashMap<String,Object>(); properties.put("testName", "testCreateRevisions"); properties.put("tag", 1337); Database db = startDatabase(); Document doc=createDocumentWithProperties(db, properties); SavedRevision rev1 = doc.getCurrentRevision(); assertTrue(rev1.getId().startsWith("1-")); assertEquals(1, rev1.getSequence()); assertEquals(0, rev1.getAttachments().size()); // Test -createRevisionWithProperties: Map<String,Object> properties2 = new HashMap<String,Object>(properties); properties2.put("tag", 4567); SavedRevision rev2 = rev1.createRevision(properties2); assertNotNull("Put failed", rev2); assertTrue("Document revision ID is still " + doc.getCurrentRevisionId(), doc.getCurrentRevisionId().startsWith("2-")); assertEquals(rev2.getId(), doc.getCurrentRevisionId()); assertNotNull(rev2.arePropertiesAvailable()); assertEquals(rev2.getUserProperties(), properties2); assertEquals(rev2.getDocument(), doc); assertEquals(rev2.getProperty("_id"), doc.getId()); assertEquals(rev2.getProperty("_rev"), rev2.getId()); // Test -createRevision: UnsavedRevision newRev = rev2.createRevision(); assertNull(newRev.getId()); assertEquals(newRev.getParent(), rev2); assertEquals(newRev.getParentId(), rev2.getId()); List<SavedRevision> listRevs=new ArrayList<SavedRevision>(); listRevs.add(rev1); listRevs.add(rev2); assertEquals(newRev.getRevisionHistory(), listRevs); assertEquals(newRev.getProperties(), rev2.getProperties()); assertEquals(newRev.getUserProperties(), rev2.getUserProperties()); Map<String,Object> userProperties=new HashMap<String, Object>(); userProperties.put("because", "NoSQL"); newRev.setUserProperties(userProperties); assertEquals(newRev.getUserProperties(), userProperties); Map<String,Object> expectProperties=new HashMap<String, Object>(); expectProperties.put("because", "NoSQL"); expectProperties.put("_id", doc.getId()); expectProperties.put("_rev", rev2.getId()); assertEquals(newRev.getProperties(),expectProperties); SavedRevision rev3 = newRev.save(); assertNotNull(rev3); assertEquals(rev3.getUserProperties(), newRev.getUserProperties()); } public void testCreateNewRevisions() throws Exception{ Map<String,Object> properties = new HashMap<String,Object>(); properties.put("testName", "testCreateRevisions"); properties.put("tag", 1337); Database db = startDatabase(); Document doc=db.createDocument(); UnsavedRevision newRev =doc.createRevision(); Document newRevDocument = newRev.getDocument(); assertEquals(doc, newRevDocument); assertEquals(db, newRev.getDatabase()); assertNull(newRev.getParentId()); assertNull(newRev.getParent()); Map<String,Object> expectProperties=new HashMap<String, Object>(); expectProperties.put("_id", doc.getId()); assertEquals(expectProperties, newRev.getProperties()); assertTrue(!newRev.isDeletion()); assertEquals(newRev.getSequence(), 0); //ios support another approach to set properties:: //newRev.([@"testName"] = @"testCreateRevisions"; //newRev[@"tag"] = @1337; newRev.setUserProperties(properties); assertEquals(newRev.getUserProperties(), properties); SavedRevision rev1 = newRev.save(); assertNotNull("Save 1 failed", rev1); assertEquals(doc.getCurrentRevision(), rev1); assertNotNull(rev1.getId().startsWith("1-")); assertEquals(1, rev1.getSequence()); assertNull(rev1.getParentId()); assertNull(rev1.getParent()); newRev = rev1.createRevision(); newRevDocument = newRev.getDocument(); assertEquals(doc, newRevDocument); assertEquals(db, newRev.getDatabase()); assertEquals(rev1.getId(), newRev.getParentId()); assertEquals(rev1, newRev.getParent()); assertEquals(rev1.getProperties(), newRev.getProperties()); assertEquals(rev1.getUserProperties(), newRev.getUserProperties()); assertNotNull(!newRev.isDeletion()); // we can't add/modify one property as on ios. need to add separate method? // newRev[@"tag"] = @4567; properties.put("tag", 4567); newRev.setUserProperties(properties); SavedRevision rev2 = newRev.save(); assertNotNull( "Save 2 failed", rev2); assertEquals(doc.getCurrentRevision(), rev2); assertNotNull(rev2.getId().startsWith("2-")); assertEquals(2, rev2.getSequence()); assertEquals(rev1.getId(), rev2.getParentId()); assertEquals(rev1, rev2.getParent()); assertNotNull("Document revision ID is still " + doc.getCurrentRevisionId(), doc.getCurrentRevisionId().startsWith("2-")); // Add a deletion/tombstone revision: newRev = doc.createRevision(); assertEquals(rev2.getId(), newRev.getParentId()); assertEquals(rev2, newRev.getParent()); newRev.setIsDeletion(true); SavedRevision rev3 = newRev.save(); assertNotNull("Save 3 failed", rev3); assertEquals(doc.getCurrentRevision(), rev3); assertNotNull("Unexpected revID " + rev3.getId(), rev3.getId().startsWith("3-")); assertEquals(3, rev3.getSequence()); assertTrue(rev3.isDeletion()); assertTrue(doc.isDeleted()); db.getDocumentCount(); Document doc2 = db.getDocument(doc.getId()); assertEquals(doc, doc2); assertNull(db.getExistingDocument(doc.getId())); } //API_SaveMultipleDocuments on IOS //API_SaveMultipleUnsavedDocuments on IOS //API_DeleteMultipleDocuments commented on IOS public void testDeleteDocument() throws Exception{ Map<String,Object> properties = new HashMap<String, Object>(); properties.put("testName", "testDeleteDocument"); Database db = startDatabase(); Document doc=createDocumentWithProperties(db, properties); assertTrue(!doc.isDeleted()); assertTrue(!doc.getCurrentRevision().isDeletion()); assertTrue(doc.delete()); assertTrue(doc.isDeleted()); assertNotNull(doc.getCurrentRevision().isDeletion()); } public void testPurgeDocument() throws Exception{ Map<String,Object> properties = new HashMap<String, Object>(); properties.put("testName", "testPurgeDocument"); Database db = startDatabase(); Document doc=createDocumentWithProperties(db, properties); assertNotNull(doc); assertNotNull(doc.purge()); Document redoc = db.getCachedDocument(doc.getId()); assertNull(redoc); } public void testAllDocuments() throws Exception{ Database db = startDatabase(); int kNDocs = 5; createDocuments(db, kNDocs); // clear the cache so all documents/revisions will be re-fetched: db.clearDocumentCache(); Log.i(TAG, " Query query = db.createAllDocumentsQuery(); //query.prefetch = YES; Log.i(TAG, "Getting all documents: " + query); QueryEnumerator rows = query.run(); assertEquals(rows.getCount(), kNDocs); int n = 0; for (Iterator<QueryRow> it = rows; it.hasNext();) { QueryRow row = it.next(); Log.i(TAG, " --> " + row); Document doc = row.getDocument(); assertNotNull("Couldn't get doc from query", doc ); assertNotNull("QueryRow should have preloaded revision contents", doc.getCurrentRevision().arePropertiesAvailable()); Log.i(TAG, " Properties =" + doc.getProperties()); assertNotNull("Couldn't get doc properties", doc.getProperties()); assertEquals(doc.getProperty("testName"), "testDatabase"); n++; } assertEquals(n, kNDocs); } public void testLocalDocs() throws Exception{ Map<String,Object> properties = new HashMap<String, Object>(); properties.put("foo", "bar"); Database db = startDatabase(); Map<String,Object> props = db.getExistingLocalDocument("dock"); assertNull(props); assertNotNull("Couldn't put new local doc", db.putLocalDocument("dock", properties)); props = db.getExistingLocalDocument("dock"); assertEquals(props.get("foo"), "bar"); Map<String,Object> newProperties = new HashMap<String, Object>(); newProperties.put("FOOO", "BARRR"); assertNotNull("Couldn't update local doc", db.putLocalDocument("dock", newProperties)); props = db.getExistingLocalDocument("dock"); assertNull(props.get("foo")); assertEquals(props.get("FOOO"), "BARRR"); assertNotNull("Couldn't delete local doc", db.deleteLocalDocument("dock")); props = db.getExistingLocalDocument("dock"); assertNull(props); assertNotNull("Second delete should have failed", !db.deleteLocalDocument("dock")); //TODO issue: deleteLocalDocument should return error.code( see ios) } // HISTORY public void testHistory() throws Exception{ Map<String,Object> properties = new HashMap<String, Object>(); properties.put("testName", "test06_History"); properties.put("tag", 1); Database db = startDatabase(); Document doc = createDocumentWithProperties(db, properties); String rev1ID = doc.getCurrentRevisionId(); Log.i(TAG, "1st revision: "+ rev1ID); assertNotNull("1st revision looks wrong: " + rev1ID, rev1ID.startsWith("1-")); assertEquals(doc.getUserProperties(), properties); properties = new HashMap<String, Object>(); properties.putAll(doc.getProperties()); properties.put("tag", 2); assertNotNull(!properties.equals(doc.getProperties())); assertNotNull(doc.putProperties(properties)); String rev2ID = doc.getCurrentRevisionId(); Log.i(TAG, "rev2ID" + rev2ID); assertNotNull("2nd revision looks wrong:" + rev2ID, rev2ID.startsWith("2-")); List<SavedRevision> revisions = doc.getRevisionHistory(); Log.i(TAG, "Revisions = " + revisions); assertEquals(revisions.size(), 2); SavedRevision rev1 = revisions.get(0); assertEquals(rev1.getId(), rev1ID); Map<String,Object> gotProperties = rev1.getProperties(); assertEquals(1, gotProperties.get("tag")); SavedRevision rev2 = revisions.get(1); assertEquals(rev2.getId(), rev2ID); assertEquals(rev2, doc.getCurrentRevision()); gotProperties = rev2.getProperties(); assertEquals(2, gotProperties.get("tag")); List<SavedRevision> tmp = new ArrayList<SavedRevision>(); tmp.add(rev2); assertEquals(doc.getConflictingRevisions(), tmp); assertEquals(doc.getLeafRevisions(), tmp); } public void testHistoryAfterDocDeletion() throws Exception{ Map<String,Object> properties = new HashMap<String, Object>(); String docId = "testHistoryAfterDocDeletion"; properties.put("tag", 1); Database db = startDatabase(); Document doc = db.getDocument(docId); assertEquals(docId, doc.getId()); doc.putProperties(properties); String revID = doc.getCurrentRevisionId(); for(int i=2; i<6; i++){ properties.put("tag", i); properties.put("_rev", revID ); doc.putProperties(properties); revID = doc.getCurrentRevisionId(); Log.i(TAG, i + " revision: " + revID); assertTrue("revision is not correct:" + revID + ", should be with prefix " + i +"-", revID.startsWith(String.valueOf(i) +"-")); assertEquals("Doc Id is not correct ", docId, doc.getId()); } // now delete the doc and clear it from the cache so we // make sure we are reading a fresh copy doc.delete(); database.clearDocumentCache(); // get doc from db with same ID as before, and the current rev should be null since the // last update was a deletion Document docPostDelete = db.getDocument(docId); assertNull(docPostDelete.getCurrentRevision()); // save a new revision properties = new HashMap<String, Object>(); properties.put("tag", 6); UnsavedRevision newRevision = docPostDelete.createRevision(); newRevision.setProperties(properties); SavedRevision newSavedRevision = newRevision.save(); // make sure the current revision of doc matches the rev we just saved assertEquals(newSavedRevision, docPostDelete.getCurrentRevision()); // make sure the rev id is 7- assertTrue(docPostDelete.getCurrentRevisionId().startsWith("7-")); } public void testConflict() throws Exception{ Map<String,Object> prop = new HashMap<String, Object>(); prop.put("foo", "bar"); Database db = startDatabase(); Document doc = createDocumentWithProperties(db, prop); SavedRevision rev1 = doc.getCurrentRevision(); Map<String,Object> properties = new HashMap<String, Object>(); properties.putAll(doc.getProperties()); properties.put("tag", 2); SavedRevision rev2a = doc.putProperties(properties); properties = new HashMap<String, Object>(); properties.putAll(rev1.getProperties()); properties.put("tag", 3); UnsavedRevision newRev = rev1.createRevision(); newRev.setProperties(properties); boolean allowConflict = true; SavedRevision rev2b = newRev.save(allowConflict); assertNotNull("Failed to create a a conflict", rev2b); List<SavedRevision> confRevs = new ArrayList<SavedRevision>(); confRevs.add(rev2b); confRevs.add(rev2a); assertEquals(doc.getConflictingRevisions(), confRevs); assertEquals(doc.getLeafRevisions(), confRevs); SavedRevision defaultRev, otherRev; if (rev2a.getId().compareTo(rev2b.getId()) > 0) { defaultRev = rev2a; otherRev = rev2b; } else { defaultRev = rev2b; otherRev = rev2a; } assertEquals(doc.getCurrentRevision(), defaultRev); Query query = db.createAllDocumentsQuery(); query.setAllDocsMode(Query.AllDocsMode.SHOW_CONFLICTS); QueryEnumerator rows = query.run(); assertEquals(rows.getCount(), 1); QueryRow row = rows.getRow(0); List<SavedRevision> revs = row.getConflictingRevisions(); assertEquals(revs.size(), 2); assertEquals(revs.get(0), defaultRev); assertEquals(revs.get(1), otherRev); } //ATTACHMENTS public void testAttachments() throws Exception, IOException { Map<String,Object> properties = new HashMap<String, Object>(); properties.put("testName", "testAttachments"); Database db = startDatabase(); Document doc = createDocumentWithProperties(db, properties); SavedRevision rev = doc.getCurrentRevision(); assertEquals(rev.getAttachments().size(), 0); assertEquals(rev.getAttachmentNames().size(), 0); assertNull(rev.getAttachment("index.html")); String content = "This is a test attachment!"; ByteArrayInputStream body = new ByteArrayInputStream(content.getBytes()); UnsavedRevision rev2 = doc.createRevision(); rev2.setAttachment("index.html", "text/plain; charset=utf-8", body); SavedRevision rev3 = rev2.save(); assertNotNull(rev3); assertEquals(rev3.getAttachments().size(), 1); assertEquals(rev3.getAttachmentNames().size(), 1); Attachment attach = rev3.getAttachment("index.html"); assertNotNull(attach); assertEquals(doc, attach.getDocument()); assertEquals("index.html", attach.getName()); List<String> attNames = new ArrayList<String>(); attNames.add("index.html"); assertEquals(rev3.getAttachmentNames(), attNames); assertEquals("text/plain; charset=utf-8", attach.getContentType()); assertEquals(IOUtils.toString(attach.getContent(), "UTF-8"), content); assertEquals(content.getBytes().length, attach.getLength()); UnsavedRevision newRev = rev3.createRevision(); newRev.removeAttachment(attach.getName()); SavedRevision rev4 = newRev.save(); assertNotNull(rev4); assertEquals(0, rev4.getAttachmentNames().size()); } //CHANGE TRACKING public void testChangeTracking() throws Exception{ final CountDownLatch doneSignal = new CountDownLatch(1); Database db = startDatabase(); db.addChangeListener(new Database.ChangeListener() { @Override public void changed(Database.ChangeEvent event) { doneSignal.countDown(); } }); createDocumentsAsync(db, 5); // We expect that the changes reported by the server won't be notified, because those revisions // are already cached in memory. boolean success = doneSignal.await(300, TimeUnit.SECONDS); assertTrue(success); assertEquals(5, db.getLastSequenceNumber()); } //VIEWS public void testCreateView() throws Exception{ Database db = startDatabase(); View view = db.getView("vu"); assertNotNull(view); assertEquals(db, view.getDatabase()); assertEquals("vu", view.getName()); assertNull(view.getMap()); assertNull(view.getReduce()); view.setMap(new Mapper() { @Override public void map(Map<String, Object> document, Emitter emitter) { emitter.emit(document.get("sequence"), null); } }, "1"); assertNotNull(view.getMap() != null); int kNDocs = 50; createDocuments(db, kNDocs); Query query = view.createQuery(); assertEquals(db, query.getDatabase()); query.setStartKey(23); query.setEndKey(33); QueryEnumerator rows = query.run(); assertNotNull(rows); assertEquals(11, rows.getCount()); int expectedKey = 23; for (Iterator<QueryRow> it = rows; it.hasNext();) { QueryRow row = it.next(); assertEquals(expectedKey, row.getKey()); assertEquals(expectedKey+1, row.getSequenceNumber()); ++expectedKey; } } //API_RunSlowView commented on IOS public void testValidation() throws Exception{ Database db = startDatabase(); db.setValidation("uncool", new Validator() { @Override public void validate(Revision newRevision, ValidationContext context) { { if (newRevision.getProperty("groovy") ==null) { context.reject("uncool"); } } } }); Map<String,Object> properties = new HashMap<String,Object>(); properties.put("groovy", "right on"); properties.put( "foo", "bar"); Document doc = db.createDocument(); assertNotNull(doc.putProperties(properties)); properties = new HashMap<String,Object>(); properties.put( "foo", "bar"); doc = db.createDocument(); try{ assertNull(doc.putProperties(properties)); } catch (CouchbaseLiteException e){ //TODO assertEquals(e.getCBLStatus().getCode(), Status.FORBIDDEN); // assertEquals(e.getLocalizedMessage(), "forbidden: uncool"); //TODO: Not hooked up yet } } public void testViewWithLinkedDocs() throws Exception{ Database db = startDatabase(); int kNDocs = 50; Document[] docs = new Document[50]; String lastDocID = ""; for (int i=0; i<kNDocs; i++) { Map<String,Object> properties = new HashMap<String,Object>(); properties.put("sequence", i); properties.put("prev", lastDocID); Document doc = createDocumentWithProperties(db, properties); docs[i]=doc; lastDocID = doc.getId(); } Query query = db.slowQuery(new Mapper() { @Override public void map(Map<String, Object> document, Emitter emitter) { emitter.emit(document.get("sequence"), new Object[]{"_id" , document.get("prev") }); } }); query.setStartKey(23); query.setEndKey(33); query.setPrefetch(true); QueryEnumerator rows = query.run(); assertNotNull(rows); assertEquals(rows.getCount(), 11); int rowNumber = 23; for (Iterator<QueryRow> it = rows; it.hasNext();) { QueryRow row = it.next(); assertEquals(row.getKey(), rowNumber); Document prevDoc = docs[rowNumber]; assertEquals(row.getDocumentId(), prevDoc.getId()); assertEquals(row.getDocument(), prevDoc); ++rowNumber; } } public void testLiveQueryRun() throws Exception { runLiveQuery("run"); } public void testLiveQueryStart() throws Exception { runLiveQuery("start"); } public void testLiveQueryStartWaitForRows() throws Exception { runLiveQuery("startWaitForRows"); } public void testLiveQueryStop() throws Exception { final int kNDocs = 100; final CountDownLatch doneSignal = new CountDownLatch(1); final Database db = startDatabase(); // run a live query View view = db.getView("vu"); view.setMap(new Mapper() { @Override public void map(Map<String, Object> document, Emitter emitter) { emitter.emit(document.get("sequence"), null); } }, "1"); final LiveQuery query = view.createQuery().toLiveQuery(); final AtomicInteger atomicInteger = new AtomicInteger(0); // install a change listener which decrements countdown latch when it sees a new // key from the list of expected keys final LiveQuery.ChangeListener changeListener = new LiveQuery.ChangeListener() { @Override public void changed(LiveQuery.ChangeEvent event) { Log.d(TAG, "changed called, atomicInteger.incrementAndGet"); atomicInteger.incrementAndGet(); assertNull(event.getError()); if (event.getRows().getCount() == kNDocs) { doneSignal.countDown(); } } }; query.addChangeListener(changeListener); // create the docs that will cause the above change listener to decrement countdown latch Log.d(Database.TAG, "testLiveQueryStop: createDocumentsAsync()"); createDocumentsAsync(db, kNDocs); Log.d(Database.TAG, "testLiveQueryStop: calling query.start()"); query.start(); // wait until the livequery is called back with kNDocs docs Log.d(Database.TAG, "testLiveQueryStop: waiting for doneSignal"); boolean success = doneSignal.await(120, TimeUnit.SECONDS); assertTrue(success); Log.d(Database.TAG, "testLiveQueryStop: waiting for query.stop()"); query.stop(); // after stopping the query, we should not get any more livequery callbacks, even // if we add more docs to the database and pause (to give time for potential callbacks) int numTimesCallbackCalled = atomicInteger.get(); Log.d(Database.TAG, "testLiveQueryStop: numTimesCallbackCalled is: " + numTimesCallbackCalled + ". Now adding docs"); for (int i=0; i<10; i++) { createDocuments(db, 1); Log.d(Database.TAG, "testLiveQueryStop: add a document. atomicInteger.get(): " + atomicInteger.get()); assertEquals(numTimesCallbackCalled, atomicInteger.get()); Thread.sleep(200); } assertEquals(numTimesCallbackCalled, atomicInteger.get()); } public void testLiveQueryRestart() throws Exception { // kick something off that will s } public void runLiveQuery(String methodNameToCall) throws Exception { final Database db = startDatabase(); final CountDownLatch doneSignal = new CountDownLatch(11); // 11 corresponds to startKey=23; endKey=33 // run a live query View view = db.getView("vu"); view.setMap(new Mapper() { @Override public void map(Map<String, Object> document, Emitter emitter) { emitter.emit(document.get("sequence"), null); } }, "1"); final LiveQuery query = view.createQuery().toLiveQuery(); query.setStartKey(23); query.setEndKey(33); Log.i(TAG, "Created " + query); // these are the keys that we expect to see in the livequery change listener callback final Set<Integer> expectedKeys = new HashSet<Integer>(); for (int i=23; i<34; i++) { expectedKeys.add(i); } // install a change listener which decrements countdown latch when it sees a new // key from the list of expected keys final LiveQuery.ChangeListener changeListener = new LiveQuery.ChangeListener() { @Override public void changed(LiveQuery.ChangeEvent event) { QueryEnumerator rows = event.getRows(); for (Iterator<QueryRow> it = rows; it.hasNext(); ) { QueryRow row = it.next(); if (expectedKeys.contains(row.getKey())) { expectedKeys.remove(row.getKey()); doneSignal.countDown(); } } } }; query.addChangeListener(changeListener); // create the docs that will cause the above change listener to decrement countdown latch int kNDocs = 50; createDocumentsAsync(db, kNDocs); if (methodNameToCall.equals("start")) { // start the livequery running asynchronously query.start(); } else if (methodNameToCall.equals("startWaitForRows")) { query.start(); query.waitForRows(); } else { assertNull(query.getRows()); query.run(); // this will block until the query completes assertNotNull(query.getRows()); } // wait for the doneSignal to be finished boolean success = doneSignal.await(300, TimeUnit.SECONDS); assertTrue("Done signal timed out, live query never ran", success); // stop the livequery since we are done with it query.removeChangeListener(changeListener); query.stop(); } public void testAsyncViewQuery() throws Exception { final CountDownLatch doneSignal = new CountDownLatch(1); final Database db = startDatabase(); View view = db.getView("vu"); view.setMap(new Mapper() { @Override public void map(Map<String, Object> document, Emitter emitter) { emitter.emit(document.get("sequence"), null); } }, "1"); int kNDocs = 50; createDocuments(db, kNDocs); Query query = view.createQuery(); query.setStartKey(23); query.setEndKey(33); query.runAsync(new Query.QueryCompleteListener() { @Override public void completed(QueryEnumerator rows, Throwable error) { Log.i(TAG, "Async query finished!"); assertNotNull(rows); assertNull(error); assertEquals(rows.getCount(), 11); int expectedKey = 23; for (Iterator<QueryRow> it = rows; it.hasNext(); ) { QueryRow row = it.next(); assertEquals(row.getDocument().getDatabase(), db); assertEquals(row.getKey(), expectedKey); ++expectedKey; } doneSignal.countDown(); } }); Log.i(TAG, "Waiting for async query to finish..."); boolean success = doneSignal.await(300, TimeUnit.SECONDS); assertTrue("Done signal timed out, async query never ran", success); } /** * Make sure that a database's map/reduce functions are shared with the shadow database instance * running in the background server. */ public void testSharedMapBlocks() throws Exception { Manager mgr = new Manager(new File(getRootDirectory(), "API_SharedMapBlocks"), Manager.DEFAULT_OPTIONS); Database db = mgr.getDatabase("db"); db.open(); db.setFilter("phil", new ReplicationFilter() { @Override public boolean filter(SavedRevision revision, Map<String, Object> params) { return true; } }); db.setValidation("val", new Validator() { @Override public void validate(Revision newRevision, ValidationContext context) { } }); View view = db.getView("view"); boolean ok = view.setMapReduce(new Mapper() { @Override public void map(Map<String, Object> document, Emitter emitter) { } }, new Reducer() { @Override public Object reduce(List<Object> keys, List<Object> values, boolean rereduce) { return null; } }, "1" ); assertNotNull("Couldn't set map/reduce", ok); final Mapper map = view.getMap(); final Reducer reduce = view.getReduce(); final ReplicationFilter filter = db.getFilter("phil"); final Validator validation = db.getValidation("val"); Future result = mgr.runAsync("db", new AsyncTask() { @Override public void run(Database database) { assertNotNull(database); View serverView = database.getExistingView("view"); assertNotNull(serverView); assertEquals(database.getFilter("phil"), filter); assertEquals(database.getValidation("val"), validation); assertEquals(serverView.getMap(), map); assertEquals(serverView.getReduce(), reduce); } }); result.get(); // blocks until async task has run db.close(); mgr.close(); } public void testChangeUUID() throws Exception{ Manager mgr = new Manager(new File(getRootDirectory(), "ChangeUUID"), Manager.DEFAULT_OPTIONS); Database db = mgr.getDatabase("db"); db.open(); String pub = db.publicUUID(); String priv = db.privateUUID(); assertTrue(pub.length() > 10); assertTrue(priv.length() > 10); assertTrue("replaceUUIDs failed", db.replaceUUIDs()); assertFalse(pub.equals(db.publicUUID())); assertFalse(priv.equals(db.privateUUID())); mgr.close(); } public void failingTestDocumentUpdate() throws Exception { final int numberOfDocuments = 10; final int numberOfUpdates = 10; final Document[] docs = new Document[numberOfDocuments]; database.runInTransaction(new TransactionalTask() { @Override public boolean run() { for (int j = 0; j < numberOfDocuments; j++) { Map<String,Object> prop = new HashMap<String, Object>(); prop.put("foo", "bar"); prop.put("toogle", true); Document document = createDocumentWithProperties(database, prop); docs[j] = document; } return true; } }); final AtomicInteger numDocsUpdated = new AtomicInteger(0); final AtomicInteger numExceptions = new AtomicInteger(0); database.runInTransaction(new TransactionalTask() { @Override public boolean run() { for (int j = 0; j < numberOfDocuments; j++) { Document doc = docs[j]; for(int k=0; k < numberOfUpdates; k++) { Map<String, Object> contents = new HashMap(doc.getProperties()); Boolean wasChecked = (Boolean) contents.get("toogle"); //toggle value of check property contents.put("toogle",!wasChecked); try { doc.putProperties(contents); numDocsUpdated.incrementAndGet(); } catch (CouchbaseLiteException cblex) { Log.e(TAG, "Document update failed", cblex); numExceptions.incrementAndGet(); } } } return true; } }); assertEquals(numberOfDocuments * numberOfUpdates, numDocsUpdated.get()); assertEquals(0, numExceptions.get()); } }
package gov.nih.nci.calab.service.util; public class CalabConstants { public static final String DATE_FORMAT = "mm/dd/yyyy"; public static final String STORAGE_BOX = "Box"; public static final String STORAGE_SHELF = "Shelf"; public static final String STORAGE_RACK = "Rack"; public static final String STORAGE_FREEZER = "Freezer"; public static final String STORAGE_ROOM = "Room"; public static final String STORAGE_LAB = "Lab"; }
package com.couchbase.lite; import com.couchbase.lite.internal.RevisionInternal; import com.couchbase.lite.util.Log; import junit.framework.Assert; import org.apache.commons.io.IOUtils; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class ApiTest extends LiteTestCase { static void createDocuments(Database db, int n) { //TODO should be changed to use db.runInTransaction for (int i=0; i<n; i++) { Map<String,Object> properties = new HashMap<String,Object>(); properties.put("testName", "testDatabase"); properties.put("sequence", i); createDocumentWithProperties(db, properties); } }; static Document createDocumentWithProperties(Database db, Map<String,Object> properties) { Document doc = db.createDocument(); Assert.assertNotNull(doc); Assert.assertNull(doc.getCurrentRevisionId()); Assert.assertNull(doc.getCurrentRevision()); Assert.assertNotNull("Document has no ID", doc.getId()); // 'untitled' docs are no longer untitled (8/10/12) try{ doc.putProperties(properties); } catch( Exception e){ assertTrue("can't create new document in db:"+db.getName() + " with properties:"+ properties.toString(), false); } Assert.assertNotNull(doc.getId()); Assert.assertNotNull(doc.getCurrentRevisionId()); Assert.assertNotNull(doc.getUserProperties()); Assert.assertEquals(db.getDocument(doc.getId()), doc); return doc; } //SERVER & DOCUMENTS public void testAPIManager() { Manager manager = this.manager; Assert.assertTrue(manager!=null); for(String dbName : manager.getAllDatabaseNames()){ Database db = manager.getDatabase(dbName); Log.i(TAG, "Database '" + dbName + "':" + db.getDocumentCount() + " documents"); } ManagerOptions options= new ManagerOptions(true, false); Manager roManager=new Manager(new File(manager.getDirectory()), options); Assert.assertTrue(roManager!=null); Database db =roManager.getDatabase("foo"); Assert.assertNull(db); List<String> dbNames=manager.getAllDatabaseNames(); Assert.assertFalse(dbNames.contains("foo")); Assert.assertTrue(dbNames.contains(DEFAULT_TEST_DB)); } public void testCreateDocument() { Map<String,Object> properties = new HashMap<String,Object>(); properties.put("testName", "testCreateDocument"); properties.put("tag", 1337); Database db = startDatabase(); Document doc=createDocumentWithProperties(db, properties); String docID=doc.getId(); assertTrue("Invalid doc ID: " +docID , docID.length()>10); String currentRevisionID=doc.getCurrentRevisionId(); assertTrue("Invalid doc revision: " +docID , currentRevisionID.length()>10); assertEquals(doc.getUserProperties(), properties); assertEquals(db.getDocument(docID), doc); db.clearDocumentCache();// so we can load fresh copies Document doc2 = db.getExistingDocument(docID); assertEquals(doc2.getId(), docID); assertEquals(doc2.getCurrentRevisionId(), currentRevisionID); assertNull(db.getExistingDocument("b0gus")); } public void testCreateRevisions() throws Exception{ Map<String,Object> properties = new HashMap<String,Object>(); properties.put("testName", "testCreateRevisions"); properties.put("tag", 1337); Database db = startDatabase(); Document doc=createDocumentWithProperties(db, properties); SavedRevision rev1 = doc.getCurrentRevision(); assertTrue(rev1.getId().startsWith("1-")); assertEquals(1, rev1.getSequence()); assertEquals(0, rev1.getAttachments().size()); // Test -createRevisionWithProperties: Map<String,Object> properties2 = new HashMap<String,Object>(properties); properties2.put("tag", 4567); SavedRevision rev2 = rev1.createRevision(properties2); assertNotNull("Put failed", rev2); assertTrue("Document revision ID is still " + doc.getCurrentRevisionId(), doc.getCurrentRevisionId().startsWith("2-")); assertEquals(rev2.getId(), doc.getCurrentRevisionId()); assertNotNull(rev2.arePropertiesAvailable()); assertEquals(rev2.getUserProperties(), properties2); assertEquals(rev2.getDocument(), doc); assertEquals(rev2.getProperty("_id"), doc.getId()); assertEquals(rev2.getProperty("_rev"), rev2.getId()); // Test -createRevision: UnsavedRevision newRev = rev2.createRevision(); assertNull(newRev.getId()); assertEquals(newRev.getParentRevision(), rev2); assertEquals(newRev.getParentRevisionId(), rev2.getId()); List<SavedRevision> listRevs=new ArrayList<SavedRevision>(); listRevs.add(rev1); listRevs.add(rev2); assertEquals(newRev.getRevisionHistory(), listRevs); assertEquals(newRev.getProperties(), rev2.getProperties()); assertEquals(newRev.getUserProperties(), rev2.getUserProperties()); Map<String,Object> userProperties=new HashMap<String, Object>(); userProperties.put("because", "NoSQL"); newRev.setUserProperties(userProperties); assertEquals(newRev.getUserProperties(), userProperties); Map<String,Object> expectProperties=new HashMap<String, Object>(); expectProperties.put("because", "NoSQL"); expectProperties.put("_id", doc.getId()); expectProperties.put("_rev", rev2.getId()); assertEquals(newRev.getProperties(),expectProperties); SavedRevision rev3 = newRev.save(); assertNotNull(rev3); assertEquals(rev3.getUserProperties(), newRev.getUserProperties()); } public void testCreateNewRevisions() throws Exception{ Map<String,Object> properties = new HashMap<String,Object>(); properties.put("testName", "testCreateRevisions"); properties.put("tag", 1337); Database db = startDatabase(); Document doc=db.createDocument(); UnsavedRevision newRev =doc.createRevision(); Document newRevDocument = newRev.getDocument(); assertEquals(doc, newRevDocument); assertEquals(db, newRev.getDatabase()); assertNull(newRev.getParentRevisionId()); assertNull(newRev.getParentRevision()); Map<String,Object> expectProperties=new HashMap<String, Object>(); expectProperties.put("_id", doc.getId()); assertEquals(expectProperties, newRev.getProperties()); assertTrue(!newRev.isDeletion()); assertEquals(newRev.getSequence(), 0); //ios support another approach to set properties:: //newRev.([@"testName"] = @"testCreateRevisions"; //newRev[@"tag"] = @1337; newRev.setUserProperties(properties); assertEquals(newRev.getUserProperties(), properties); SavedRevision rev1 = newRev.save(); assertNotNull("Save 1 failed", rev1); assertEquals(doc.getCurrentRevision(), rev1); assertNotNull(rev1.getId().startsWith("1-")); assertEquals(1, rev1.getSequence()); assertNull(rev1.getParentRevisionId()); assertNull(rev1.getParentRevision()); newRev = rev1.createRevision(); newRevDocument = newRev.getDocument(); assertEquals(doc, newRevDocument); assertEquals(db, newRev.getDatabase()); assertEquals(rev1.getId(), newRev.getParentRevisionId()); assertEquals(rev1, newRev.getParentRevision()); assertEquals(rev1.getProperties(), newRev.getProperties()); assertEquals(rev1.getUserProperties(), newRev.getUserProperties()); assertNotNull(!newRev.isDeletion()); // we can't add/modify one property as on ios. need to add separate method? // newRev[@"tag"] = @4567; properties.put("tag", 4567); newRev.setUserProperties(properties); SavedRevision rev2 = newRev.save(); assertNotNull( "Save 2 failed", rev2); assertEquals(doc.getCurrentRevision(), rev2); assertNotNull(rev2.getId().startsWith("2-")); assertEquals(2, rev2.getSequence()); assertEquals(rev1.getId(), rev2.getParentRevisionId()); assertEquals(rev1, rev2.getParentRevision()); assertNotNull("Document revision ID is still " + doc.getCurrentRevisionId(), doc.getCurrentRevisionId().startsWith("2-")); // Add a deletion/tombstone revision: newRev = doc.createRevision(); assertEquals(rev2.getId(), newRev.getParentRevisionId()); assertEquals(rev2, newRev.getParentRevision()); newRev.setIsDeletion(true); SavedRevision rev3 = newRev.save(); assertNotNull("Save 3 failed", rev3); assertEquals(doc.getCurrentRevision(), rev3); assertNotNull("Unexpected revID " + rev3.getId(), rev3.getId().startsWith("3-")); assertEquals(3, rev3.getSequence()); assertTrue(rev3.isDeletion()); assertTrue(doc.isDeleted()); db.getDocumentCount(); Document doc2 = db.getExistingDocument(doc.getId()); // BUG ON IOS! assertNull(doc2); } //API_SaveMultipleDocuments on IOS //API_SaveMultipleUnsavedDocuments on IOS //API_DeleteMultipleDocuments commented on IOS public void testDeleteDocument() throws Exception{ Map<String,Object> properties = new HashMap<String, Object>(); properties.put("testName", "testDeleteDocument"); Database db = startDatabase(); Document doc=createDocumentWithProperties(db, properties); assertTrue(!doc.isDeleted()); assertTrue(!doc.getCurrentRevision().isDeletion()); assertTrue(doc.delete()); assertTrue(doc.isDeleted()); assertNotNull(doc.getCurrentRevision().isDeletion()); } public void testPurgeDocument() throws Exception{ Map<String,Object> properties = new HashMap<String, Object>(); properties.put("testName", "testPurgeDocument"); Database db = startDatabase(); Document doc=createDocumentWithProperties(db, properties); assertNotNull(doc); assertNotNull(doc.purge()); Document redoc = db.getCachedDocument(doc.getId()); assertNull(redoc); } public void testAllDocuments() throws Exception{ Database db = startDatabase(); int kNDocs = 5; createDocuments(db, kNDocs); // clear the cache so all documents/revisions will be re-fetched: db.clearDocumentCache(); Log.i(TAG," Query query = db.createAllDocumentsQuery(); //query.prefetch = YES; Log.i(TAG, "Getting all documents: " + query); QueryEnumerator rows = query.run(); assertEquals(rows.getCount(), kNDocs); int n = 0; for (Iterator<QueryRow> it = rows; it.hasNext();) { QueryRow row = it.next(); Log.i(TAG, " --> " + row); Document doc = row.getDocument(); assertNotNull("Couldn't get doc from query", doc ); assertNotNull("QueryRow should have preloaded revision contents", doc.getCurrentRevision().arePropertiesAvailable()); Log.i(TAG, " Properties =" + doc.getProperties()); assertNotNull("Couldn't get doc properties", doc.getProperties()); assertEquals(doc.getProperty("testName"), "testDatabase"); n++; } assertEquals(n, kNDocs); } public void testLocalDocs() throws Exception{ Map<String,Object> properties = new HashMap<String, Object>(); properties.put("foo", "bar"); Database db = startDatabase(); Map<String,Object> props = db.getExistingLocalDocument("dock"); assertNull(props); assertNotNull("Couldn't put new local doc", db.putLocalDocument(properties, "dock")); props = db.getExistingLocalDocument("dock"); assertEquals(props.get("foo"), "bar"); Map<String,Object> newProperties = new HashMap<String, Object>(); newProperties.put("FOOO", "BARRR"); assertNotNull("Couldn't update local doc", db.putLocalDocument(newProperties, "dock")); props = db.getExistingLocalDocument("dock"); assertNull(props.get("foo")); assertEquals(props.get("FOOO"), "BARRR"); assertNotNull("Couldn't delete local doc", db.deleteLocalDocument("dock")); props = db.getExistingLocalDocument("dock"); assertNull(props); assertNotNull("Second delete should have failed", !db.deleteLocalDocument("dock")); //TODO issue: deleteLocalDocument should return error.code( see ios) } // HISTORY public void testHistory() throws Exception{ Map<String,Object> properties = new HashMap<String, Object>(); properties.put("testName", "test06_History"); properties.put("tag", 1); Database db = startDatabase(); Document doc = createDocumentWithProperties(db, properties); String rev1ID = doc.getCurrentRevisionId(); Log.i(TAG, "1st revision: "+ rev1ID); assertNotNull("1st revision looks wrong: " + rev1ID, rev1ID.startsWith("1-")); assertEquals(doc.getUserProperties(), properties); properties = new HashMap<String, Object>(); properties.putAll(doc.getProperties()); properties.put("tag", 2); assertNotNull(!properties.equals(doc.getProperties())); assertNotNull(doc.putProperties(properties)); String rev2ID = doc.getCurrentRevisionId(); Log.i(TAG, "rev2ID" + rev2ID); assertNotNull("2nd revision looks wrong:" + rev2ID, rev2ID.startsWith("2-")); List<SavedRevision> revisions = doc.getRevisionHistory(); Log.i(TAG, "Revisions = " + revisions); assertEquals(revisions.size(), 2); SavedRevision rev1 = revisions.get(0); assertEquals(rev1.getId(), rev1ID); Map<String,Object> gotProperties = rev1.getProperties(); assertEquals(gotProperties.get("tag"), 1); SavedRevision rev2 = revisions.get(1); assertEquals(rev2.getId(), rev2ID); assertEquals(rev2, doc.getCurrentRevision()); gotProperties = rev2.getProperties(); assertEquals(gotProperties.get("tag"), 2); List<SavedRevision> tmp = new ArrayList<SavedRevision>(); tmp.add(rev2); assertEquals(doc.getConflictingRevisions(), tmp); assertEquals(doc.getLeafRevisions(), tmp); } /* TODO conflict is not supported now? public void testConflict() throws Exception{ Map<String,Object> prop = new HashMap<String, Object>(); prop.put("foo", "bar"); Database db = startDatabase(); Document doc = createDocumentWithProperties(db, prop); SavedRevision rev1 = doc.getCurrentRevision(); Map<String,Object> properties = doc.getProperties(); properties.put("tag", 2); SavedRevision rev2a = doc.putProperties(properties); properties = rev1.getProperties(); properties.put("tag", 3); UnsavedRevision newRev = rev1.createRevision(); newRev.setProperties(properties); //TODO ? saveAllowingConflict not found, see ios SavedRevision rev2b = newRev.save(); assertNotNull("Failed to create a a conflict", rev2b); List<SavedRevision> confRevs = new ArrayList<SavedRevision>(); confRevs.add(rev2b); confRevs.add(rev2a); assertEquals(doc.getConflictingRevisions(), confRevs); assertEquals(doc.getLeafRevisions(), confRevs); SavedRevision defaultRev, otherRev; if (rev2a.getId().compareTo(rev2b.getId()) > 0) { defaultRev = rev2a; otherRev = rev2b; } else { defaultRev = rev2b; otherRev = rev2a; } assertEquals(doc.getCurrentRevision(), defaultRev); Query query = db.createAllDocumentsQuery(); // TODO allDocsMode? query.allDocsMode = kCBLShowConflicts; QueryEnumerator rows = query.getRows(); assertEquals(rows.getCount(), 1); QueryRow row = rows.getRow(0); // TODO conflictingRevisions? List<SavedRevision> revs = row.conflictingRevisions; assertEquals(revs.size(), 2); assertEquals(revs.get(0), defaultRev); assertEquals(revs.get(1), otherRev); } */ //ATTACHMENTS public void testAttachments() throws Exception, IOException { Map<String,Object> properties = new HashMap<String, Object>(); properties.put("testName", "testAttachments"); Database db = startDatabase(); Document doc = createDocumentWithProperties(db, properties); SavedRevision rev = doc.getCurrentRevision(); assertEquals(rev.getAttachments().size(), 0); assertEquals(rev.getAttachmentNames().size(), 0); assertNull(rev.getAttachment("index.html")); String content = "This is a test attachment!"; ByteArrayInputStream body = new ByteArrayInputStream(content.getBytes()); UnsavedRevision rev2 = doc.createRevision(); rev2.setAttachment("index.html", "text/plain; charset=utf-8", body); SavedRevision rev3 = rev2.save(); assertNotNull(rev3); assertEquals(rev3.getAttachments().size(), 1); assertEquals(rev3.getAttachmentNames().size(), 1); Attachment attach = rev3.getAttachment("index.html"); assertNotNull(attach); assertEquals(doc, attach.getDocument()); assertEquals("index.html", attach.getName()); List<String> attNames = new ArrayList<String>(); attNames.add("index.html"); assertEquals(rev3.getAttachmentNames(), attNames); assertEquals("text/plain; charset=utf-8", attach.getContentType()); assertEquals(IOUtils.toString(attach.getContent(), "UTF-8"), content); assertEquals(attach.getLength(), content.getBytes().length); // TODO getcontentURL was not implemented? // NSURL* bodyURL = attach.getcontentURL; // assertNotNull(bodyURL.isFileURL); // assertEquals([NSData dataWithContentsOfURL: bodyURL], body); // UnsavedRevision *newRev = [rev3 createRevision]; // [newRev removeAttachmentNamed: attach.name]; // CBLRevision* rev4 = [newRev save: &error]; // assertNotNull(!error); // assertNotNull(rev4); // assertEquals([rev4.attachmentNames count], (NSUInteger)0); } //CHANGE TRACKING //VIEWS public void testCreateView() throws Exception{ Database db = startDatabase(); View view = db.getView("vu"); assertNotNull(view); assertEquals(view.getDatabase(), db); assertEquals(view.getName(), "vu"); assertNull(view.getMap()); assertNull(view.getReduce()); view.setMap(new Mapper() { @Override public void map(Map<String, Object> document, Emitter emitter) { emitter.emit(document.get("sequence"), null); } }, "1"); assertNotNull(view.getMap() != null); int kNDocs = 50; createDocuments(db, kNDocs); Query query = view.createQuery(); assertEquals(query.getDatabase(), db); query.setStartKey(23); query.setEndKey(33); QueryEnumerator rows = query.run(); assertNotNull(rows); assertEquals(rows.getCount(), 11); int expectedKey = 23; for (Iterator<QueryRow> it = rows; it.hasNext();) { QueryRow row = it.next(); assertEquals(row.getKey(), expectedKey); assertEquals(row.getSequenceNumber(), expectedKey+1); ++expectedKey; } } //API_RunSlowView commented on IOS public void testValidation() throws Exception{ Database db = startDatabase(); db.setValidation("uncool", new ValidationBlock() { @Override public boolean validate(RevisionInternal newRevision, ValidationContext context) { { if (newRevision.getPropertyForKey("groovy") ==null) { context.setErrorMessage("uncool"); return false; } return true; } } }); Map<String,Object> properties = new HashMap<String,Object>(); properties.put("groovy", "right on"); properties.put( "foo", "bar"); Document doc = db.createDocument(); assertNotNull(doc.putProperties(properties)); properties = new HashMap<String,Object>(); properties.put( "foo", "bar"); doc = db.createDocument(); try{ assertNull(doc.putProperties(properties)); } catch (CouchbaseLiteException e){ //TODO assertEquals(e.getCBLStatus().getCode(), Status.FORBIDDEN); // assertEquals(e.getLocalizedMessage(), "forbidden: uncool"); //TODO: Not hooked up yet } } public void testViewWithLinkedDocs() throws Exception{ Database db = startDatabase(); int kNDocs = 50; Document[] docs = new Document[50]; String lastDocID = ""; for (int i=0; i<kNDocs; i++) { Map<String,Object> properties = new HashMap<String,Object>(); properties.put("sequence", i); properties.put("prev", lastDocID); Document doc = createDocumentWithProperties(db, properties); docs[i]=doc; lastDocID = doc.getId(); } Query query = db.slowQuery(new Mapper() { @Override public void map(Map<String, Object> document, Emitter emitter) { emitter.emit(document.get("sequence"), new Object[]{"_id" , document.get("prev") }); } }); query.setStartKey(23); query.setEndKey(33); query.setPrefetch(true); QueryEnumerator rows = query.run(); assertNotNull(rows); assertEquals(rows.getCount(), 11); int rowNumber = 23; for (Iterator<QueryRow> it = rows; it.hasNext();) { QueryRow row = it.next(); assertEquals(row.getKey(), rowNumber); Document prevDoc = docs[rowNumber]; assertEquals(row.getDocumentId(), prevDoc.getId()); assertEquals(row.getDocument(), prevDoc); ++rowNumber; } } /* public void testLiveQuery() throws Exception{ final Database db = startDatabase(); View view = db.getView("vu"); view.setMap(new Mapper() { @Override public void map(Map<String, Object> document, Emitter emitter) { emitter.emit(document.get("sequence"), null); } }, "1"); int kNDocs = 50; createDocuments(db, kNDocs); final CBLLiveQuery query = view.createQuery().toLiveQuery();; query.setStartKey(23); query.setEndKey(33); Log.i(TAG, "Created " + query); assertNull(query.getRows()); Log.i(TAG, "Waiting for live query to update..."); boolean finished = false; query.start(); //TODO temp solution for infinite loop int i=0; while (!finished && i <100){ QueryEnumerator rows = query.getRows(); Log.i(TAG, "Live query rows = " + rows); i++; if (rows != null) { assertEquals(rows.getCount(), 11); int expectedKey = 23; for (Iterator<QueryRow> it = rows; it.hasNext();) { QueryRow row = it.next(); assertEquals(row.getDocument().getDatabase(), db); assertEquals(row.getKey(), expectedKey); ++expectedKey; } finished = true; } } query.stop(); assertTrue("Live query timed out!", finished); } public void testAsyncViewQuery() throws Exception, InterruptedException { final Database db = startDatabase(); View view = db.getView("vu"); view.setMap(new Mapper() { @Override public void map(Map<String, Object> document, Emitter emitter) { emitter.emit(document.get("sequence"), null); } }, "1"); int kNDocs = 50; createDocuments(db, kNDocs); Query query = view.createQuery(); query.setStartKey(23); query.setEndKey(33); final boolean[] finished = {false}; final Thread curThread = Thread.currentThread(); query.runAsync(new Query.QueryCompleteListener() { @Override public void queryComplete(QueryEnumerator rows, Throwable error) { Log.i(TAG, "Async query finished!"); //TODO Failed! assertEquals(Thread.currentThread().getId(), curThread.getId()); assertNotNull(rows); assertNull(error); assertEquals(rows.getCount(), 11); int expectedKey = 23; for (Iterator<QueryRow> it = rows; it.hasNext();) { QueryRow row = it.next(); assertEquals(row.getDocument().getDatabase(), db); assertEquals(row.getKey(), expectedKey); ++expectedKey; } finished[0] = true; } }); Log.i(TAG, "Waiting for async query to finish..."); assertTrue("Async query timed out!", finished[0]); } // Make sure that a database's map/reduce functions are shared with the shadow database instance // running in the background server. public void testSharedMapBlocks() throws Exception, ExecutionException, InterruptedException { Manager mgr = new Manager(new File(getInstrumentation().getContext().getFilesDir(), "API_SharedMapBlocks")); Database db = mgr.getDatabase("db"); db.open(); db.setFilter("phil", new CBLFilterDelegate() { @Override public boolean filter(RevisionInternal revision, Map<String, Object> params) { return true; } }); db.setValidation("val", new ValidationBlock() { @Override public boolean validate(RevisionInternal newRevision, ValidationContext context) { return true; } }); View view = db.getView("view"); boolean ok = view.setMapAndReduce(new Mapper() { @Override public void map(Map<String, Object> document, Emitter emitter) { }}, new CBLReducer() { @Override public Object reduce(List<Object> keys, List<Object> values, boolean rereduce) { return null; } }, "1"); assertNotNull("Couldn't set map/reduce", ok); final Mapper map = view.getMap(); final CBLReducer reduce = view.getReduce(); final CBLFilterDelegate filter = db.getFilter("phil"); final ValidationBlock validation = db.getValidation("val"); Future result = mgr.runAsync("db", new DatabaseAsyncFunction() { @Override public boolean performFunction(Database database) { assertNotNull(database); View serverView = database.getExistingView("view"); assertNotNull(serverView); assertEquals(database.getFilter("phil"), filter); assertEquals(database.getValidation("val"), validation); assertEquals(serverView.getMap(), map); assertEquals(serverView.getReduce(), reduce); return true; } }); Thread.sleep(20000); assertEquals(result.get(), true); db.close(); mgr.close(); } */ public void testChangeUUID() throws Exception{ Manager mgr = new Manager(new File(getInstrumentation().getContext().getFilesDir(), "ChangeUUID"), Manager.DEFAULT_OPTIONS); Database db = mgr.getDatabase("db"); db.open(); String pub = db.publicUUID(); String priv = db.privateUUID(); assertTrue(pub.length() > 10); assertTrue(priv.length() > 10); assertTrue("replaceUUIDs failed", db.replaceUUIDs()); assertFalse(pub.equals(db.publicUUID())); assertFalse(priv.equals(db.privateUUID())); mgr.close(); } }
package org.apache.commons.lang.exception; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.io.PrintWriter; import java.io.StringWriter; import java.sql.SQLException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; /** * Utility routines for manipulating <code>Throwable</code> objects. * * @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a> * @since 1.0 */ public class ExceptionUtils { /** * The names of methods commonly used to access a wrapped * exception. */ protected static final String[] CAUSE_METHOD_NAMES = { "getCause", "getNextException", "getTargetException", "getException", "getSourceException" }; /** * The empty parameter list passed to methods used to access a * wrapped exception. */ protected static final Object[] CAUSE_METHOD_PARAMS = {}; /** * Constructs a new <code>ExceptionUtils</code>. Protected to * discourage instantiation. */ protected ExceptionUtils() { } /** * Introspects the specified <code>Throwable</code> for a * <code>getCause()</code>, <code>getNextException()</code>, * <code>getTargetException()</code>, or * <code>getException()</code> method which returns a * <code>Throwable</code> object (standard as of JDK 1.4, and part * of the {@link * org.apache.commons.lang.exception.NestableException} API), * extracting and returning the cause of the exception. In the * absence of any such method, the object is inspected for a * <code>detail</code> field assignable to a * <code>Throwable</code>. If none of the above is found, returns * <code>null</code>. * * @param t The exception to introspect for a cause. * @return The cause of the <code>Throwable</code>. */ public static Throwable getCause(Throwable t) { return getCause(t, CAUSE_METHOD_NAMES); } /** * Extends the API of {@link #getCause(Throwable)} by * introspecting for only user-specified method names. * * @see #getCause(Throwable) */ public static Throwable getCause(Throwable t, String[] methodNames) { Throwable cause = getCauseUsingWellKnownTypes(t); if (cause == null) { for (int i = 0; i < methodNames.length; i++) { cause = getCauseUsingMethodName(t, methodNames[i]); if (cause != null) { break; } } if (cause == null) { cause = getCauseUsingFieldName(t, "detail"); } } return cause; } /** * Walks through the exception chain to the last element -- the * "root" of the tree -- using {@link #getCause(Throwable)}, and * returns that exception. * * @return The root cause of the <code>Throwable</code>. * @see #getCause(Throwable) */ public static Throwable getRootCause(Throwable t) { Throwable cause = getCause(t); if (cause != null) { t = cause; while ((t = getCause(t)) != null) { cause = t; } } return cause; } /** * Uses <code>instanceof</code> checks to examine the exception, * looking for well known types which could contain chained or * wrapped exceptions. * * @param t The exception to examine. * @return The wrapped exception, or <code>null</code> if not * found. */ private static Throwable getCauseUsingWellKnownTypes(Throwable t) { if (t instanceof Nestable) { return ((Nestable) t).getCause(); } else if (t instanceof SQLException) { return ((SQLException) t).getNextException(); } else if (t instanceof InvocationTargetException) { return ((InvocationTargetException) t).getTargetException(); } else { return null; } } /** * @param t The exception to examine. * @param methodName The name of the method to find and invoke. * @return The wrapped exception, or <code>null</code> if not * found. */ private static Throwable getCauseUsingMethodName(Throwable t, String methodName) { Method method = null; try { method = t.getClass().getMethod(methodName, null); } catch (NoSuchMethodException ignored) { } catch (SecurityException ignored) { } if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) { try { return (Throwable) method.invoke(t, CAUSE_METHOD_PARAMS); } catch (IllegalAccessException ignored) { } catch (IllegalArgumentException ignored) { } catch (InvocationTargetException ignored) { } } return null; } /** * @param t The exception to examine. * @param fieldName The name of the attribute to examine. * @return The wrapped exception, or <code>null</code> if not * found. */ private static Throwable getCauseUsingFieldName(Throwable t, String fieldName) { Field field = null; try { field = t.getClass().getField(fieldName); } catch (NoSuchFieldException ignored) { } catch (SecurityException ignored) { } if (field != null && Throwable.class.isAssignableFrom(field.getType())) { try { return (Throwable) field.get(t); } catch (IllegalAccessException ignored) { } catch (IllegalArgumentException ignored) { } } return null; } /** * Returns the number of <code>Throwable</code> objects in the * exception chain. * * @param t The exception to inspect. * @return The throwable count. */ public static int getThrowableCount(Throwable t) { // Count the number of throwables int count = 0; while (t != null) { count++; t = ExceptionUtils.getCause(t); } return count; } /** * Returns the list of <code>Throwable</code> objects in the * exception chain. * * @param t The exception to inspect. * @return The list of <code>Throwable</code> objects. */ public static Throwable[] getThrowables(Throwable t) { List list = new ArrayList(); while (t != null) { list.add(t); t = ExceptionUtils.getCause(t); } return (Throwable []) list.toArray(new Throwable[list.size()]); } /** * Delegates to {@link #indexOfThrowable(Throwable, Class, int)}, * starting the search at the beginning of the exception chain. * * @see #indexOfThrowable(Throwable, Class, int) */ public static int indexOfThrowable(Throwable t, Class type) { return indexOfThrowable(t, type, 0); } /** * Returns the (zero based) index, of the first * <code>Throwable</code> that matches the specified type in the * exception chain of <code>Throwable</code> objects with an index * greater than or equal to the specified index, or * <code>-1</code> if the type is not found. * * @param t The exception to inspect. * @param type <code>Class</code> to look for. * @param fromIndex The (zero based) index of the starting * position in the chain to be searched. * @return index The first occurrence of the type in the chain, or * <code>-1</code> if the type is not found. * @throws IndexOutOfBoundsException If the <code>fromIndex</code> * argument is negative or not less than the count of * <code>Throwable</code>s in the chain. */ public static int indexOfThrowable(Throwable t, Class type, int fromIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException ("Throwable index out of range: " + fromIndex); } Throwable[] throwables = ExceptionUtils.getThrowables(t); if (fromIndex >= throwables.length) { throw new IndexOutOfBoundsException ("Throwable index out of range: " + fromIndex); } for (int i = fromIndex; i < throwables.length; i++) { if (throwables[i].getClass().equals(type)) { return i; } } return -1; } /** * A convenient way of extracting the stack trace from an * exception. * * @param t The <code>Throwable</code>. * @return The stack trace as generated by the exception's * <code>printStackTrace(PrintWriter)</code> method. */ public static String getStackTrace(Throwable t) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); t.printStackTrace(pw); return sw.getBuffer().toString(); } /** * Captures the stack trace associated with the specified * <code>Throwable</code> object, decomposing it into a list of * stack frames. * * @param t The <code>Throwable</code>. * @return An array of strings describing each stack frame. */ public static String[] getStackFrames(Throwable t) { return getStackFrames(getStackTrace(t)); } /** * Functionality shared between the * <code>getStackFrames(Throwable)</code> methods of this and the * {@link org.apache.commons.lang.exception.NestableDelegate} * classes. */ static String[] getStackFrames(String stackTrace) { // TODO: Use constant from org.apache.commons.lang.SystemUtils. String linebreak = System.getProperty("line.separator"); StringTokenizer frames = new StringTokenizer(stackTrace, linebreak); List list = new LinkedList(); while (frames.hasMoreTokens()) { list.add(frames.nextToken()); } return (String []) list.toArray(new String[] {}); } }
package ibis.ipl.support.management; import java.io.IOException; import ibis.io.Conversion; import ibis.ipl.IbisIdentifier; import ibis.ipl.server.ManagementServiceInterface; import ibis.ipl.support.Connection; import ibis.smartsockets.virtual.VirtualSocketFactory; import ibis.util.TypedProperties; public class ManagementService implements ibis.ipl.server.Service, ManagementServiceInterface { private static final int CONNECT_TIMEOUT = 10000; private final VirtualSocketFactory factory; public ManagementService(TypedProperties properties, VirtualSocketFactory factory) { this.factory = factory; } public void end(long deadline) { // NOTHING } public String getServiceName() { return "management"; } /* * (non-Javadoc) * * @see * ibis.ipl.management.ManagementServerInterface#getAttributes(ibis.ipl. * IbisIdentifier, ibis.ipl.management.AttributeDescription) */ public Object[] getAttributes(IbisIdentifier ibis, AttributeDescription... descriptions) throws IOException { ibis.ipl.impl.IbisIdentifier identifier; try { identifier = (ibis.ipl.impl.IbisIdentifier) ibis; } catch (ClassCastException e) { throw new IOException( "cannot cast given identifier to implementation identifier: " + e); } Connection connection = new Connection(identifier, CONNECT_TIMEOUT, false, factory, Protocol.VIRTUAL_PORT); connection.out().writeByte(Protocol.MAGIC_BYTE); connection.out().writeByte(Protocol.OPCODE_GET_MONITOR_INFO); connection.out().writeInt(descriptions.length); for (int i = 0; i < descriptions.length; i++) { connection.out().writeUTF(descriptions[i].getBeanName()); connection.out().writeUTF(descriptions[i].getAttribute()); } connection.getAndCheckReply(); int length = connection.in().readInt(); if (length < 0) { connection.close(); throw new IOException("End of Stream on reading from connection"); } byte[] resultBytes = new byte[length]; connection.in().readFully(resultBytes); Object[] reply; try { reply = (Object[]) Conversion.byte2object(resultBytes); } catch (ClassNotFoundException e) { throw new IOException("Cannot cast result " + e); } connection.close(); return reply; } public String toString() { return "Management service on virtual port " + Protocol.VIRTUAL_PORT; } }
package org.xins.util.text; import org.xins.util.MandatoryArgumentChecker; /** * Exception thrown if a character string does not match a certain format. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) */ public final class FormatException extends RuntimeException { // Class fields // Class functions private static final String createMessage(String string, String reason) throws IllegalArgumentException { // Check the precondition MandatoryArgumentChecker.check("string", string); FastStringBuffer buffer = new FastStringBuffer(128); buffer.append("The string \""); buffer.append(string); buffer.append("\" is invalid."); if (reason != null) { buffer.append(" Reason: "); buffer.append(reason); } return buffer.toString(); } // Constructors public FormatException(String string, String reason) throws IllegalArgumentException { // Call superclass super(createMessage(string, reason)); // Store information _string = string; _reason = reason; } // Fields /** * The string that is considered invalid. Cannot be <code>null</code>. */ private final String _string; /** * The reason for the string to be considered invalid. Can be * <code>null</code>. */ private final String _reason; // Methods /** * Returns the string that is considered invalid. * * @return * the string that is considered invalid, cannot be <code>null</code>. */ public String getString() { return _string; } /** * Returns the reason. * * @return * the reason for the string to be considered invalid, can be * <code>null</code>. */ public String getReason() { return _reason; } }
package org.xins.server; import java.util.List; import org.xins.util.MandatoryArgumentChecker; import org.xins.util.text.ParseException; /** * Authorization filter for IP addresses. An <code>IPFilter</code> object is * created and used as follows: * * <blockquote><code>IPFilter filter = IPFilter.parseFilter("10.0.0.0/24"); * <br>if (filter.isAuthorized("10.0.0.1")) { * <br>&nbsp;&nbsp;&nbsp;// IP is granted access * <br>} else { * <br>&nbsp;&nbsp;&nbsp;// IP is denied access * <br>}</code></blockquote> * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) */ public final class IPFilter extends Object { // Class fields // Class functions public static final IPFilter parseFilter(String expression) throws IllegalArgumentException, ParseException { MandatoryArgumentChecker.check("expression", expression); return new IPFilter(expression); } // Constructors /** * Creates an <code>IPFilter</code> object for the specified filter * expression. The expression consists of a base IP address and a bit * count. The bit count indicates how many bits in an IP address must match * the bits in the base IP address. * * @param expression * the filter expression, cannot be <code>null</code> and must match the * form: * <code><em>a</em>.<em>a</em>.<em>a</em>.<em>a</em>/<em>n</em></code>, * where <em>a</em> is a number between 0 and 255, with no leading * zeroes, and <em>n</em> is a number between <em>0</em> and * <em>32</em>, no leading zeroes. */ private IPFilter(String expression) { _expression = expression; } // Fields /** * The expression of this filter. */ private final String _expression; // Methods /** * Returns the filter expression. * * @return * the original filter expression, never <code>null</code>. */ public final String getExpression() { return _expression; } public final boolean isAuthorized(String ip) throws IllegalArgumentException, ParseException { return false; // TODO } /** * Returns a textual representation of this filter. The implementation of * this method returns the filter expression passed. * * @return * a textual presentation, never <code>null</code>. */ public final String toString() { return getExpression(); } }
// samskivert library - useful routines for java programs // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.jdbc.depot; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.logging.Level; import com.samskivert.io.PersistenceException; import com.samskivert.jdbc.depot.annotation.Computed; import com.samskivert.jdbc.depot.annotation.Entity; import com.samskivert.jdbc.depot.annotation.FullTextIndex; import com.samskivert.jdbc.depot.annotation.GeneratedValue; import com.samskivert.jdbc.depot.annotation.Id; import com.samskivert.jdbc.depot.annotation.Index; import com.samskivert.jdbc.depot.annotation.Table; import com.samskivert.jdbc.depot.annotation.TableGenerator; import com.samskivert.jdbc.depot.annotation.Transient; import com.samskivert.jdbc.depot.annotation.UniqueConstraint; import com.samskivert.jdbc.DatabaseLiaison; import com.samskivert.util.ArrayUtil; import static com.samskivert.jdbc.depot.Log.log; /** * Handles the marshalling and unmarshalling of persistent instances to JDBC primitives ({@link * PreparedStatement} and {@link ResultSet}). */ public class DepotMarshaller<T extends PersistentRecord> { /** The name of a private static field that must be defined for all persistent object classes. * It is used to handle schema migration. If automatic schema migration is not desired, define * this field and set its value to -1. */ public static final String SCHEMA_VERSION_FIELD = "SCHEMA_VERSION"; /** * Creates a marshaller for the specified persistent object class. */ public DepotMarshaller (Class<T> pclass, PersistenceContext context) { _pclass = pclass; Entity entity = pclass.getAnnotation(Entity.class); // see if this is a computed entity Computed computed = pclass.getAnnotation(Computed.class); if (computed == null) { // if not, this class has a corresponding SQL table _tableName = _pclass.getName(); _tableName = _tableName.substring(_tableName.lastIndexOf(".")+1); // see if there are Entity values specified if (entity != null) { if (entity.name().length() > 0) { _tableName = entity.name(); } } } // if the entity defines a new TableGenerator, map that in our static table as those are // shared across all entities TableGenerator generator = pclass.getAnnotation(TableGenerator.class); if (generator != null) { context.tableGenerators.put(generator.name(), generator); } // if there are FTS indexes in the Table, map those out here for future use Table table = pclass.getAnnotation(Table.class); if (table != null) { for (FullTextIndex fts : table.fullTextIndexes()) { _fullTextIndexes.put(fts.name(), fts); } } // introspect on the class and create marshallers for persistent fields ArrayList<String> fields = new ArrayList<String>(); for (Field field : _pclass.getFields()) { int mods = field.getModifiers(); // check for a static constant schema version if (java.lang.reflect.Modifier.isStatic(mods) && field.getName().equals(SCHEMA_VERSION_FIELD)) { try { _schemaVersion = (Integer)field.get(null); } catch (Exception e) { log.log(Level.WARNING, "Failed to read schema version " + "[class=" + _pclass + "].", e); } } // the field must be public, non-static and non-transient if (!java.lang.reflect.Modifier.isPublic(mods) || java.lang.reflect.Modifier.isStatic(mods) || field.getAnnotation(Transient.class) != null) { continue; } FieldMarshaller fm = FieldMarshaller.createMarshaller(field); _fields.put(field.getName(), fm); fields.add(field.getName()); // check to see if this is our primary key if (field.getAnnotation(Id.class) != null) { if (_pkColumns == null) { _pkColumns = new ArrayList<FieldMarshaller>(); } _pkColumns.add(fm); // check if this field defines a new TableGenerator generator = field.getAnnotation(TableGenerator.class); if (generator != null) { context.tableGenerators.put(generator.name(), generator); } } } // if the entity defines a single-columnar primary key, figure out if we will be generating // values for it if (_pkColumns != null) { GeneratedValue gv = null; FieldMarshaller keyField = null; // loop over fields to see if there's a @GeneratedValue at all for (FieldMarshaller field : _pkColumns) { gv = field.getGeneratedValue(); if (gv != null) { keyField = field; break; } } if (keyField != null) { // and if there is, make sure we've a single-column id if (_pkColumns.size() > 1) { throw new IllegalArgumentException( "Cannot use @GeneratedValue on multiple-column @Id's"); } // the primary key must be numeric if we are to auto-assign it Class<?> ftype = keyField.getField().getType(); boolean isNumeric = ( ftype.equals(Byte.TYPE) || ftype.equals(Byte.class) || ftype.equals(Short.TYPE) || ftype.equals(Short.class) || ftype.equals(Integer.TYPE) || ftype.equals(Integer.class) || ftype.equals(Long.TYPE) || ftype.equals(Long.class)); if (!isNumeric) { throw new IllegalArgumentException( "Cannot use @GeneratedValue on non-numeric column"); } switch(gv.strategy()) { case AUTO: case IDENTITY: _keyGenerator = new IdentityKeyGenerator( gv, getTableName(), keyField.getColumnName()); break; case TABLE: String name = gv.generator(); generator = context.tableGenerators.get(name); if (generator == null) { throw new IllegalArgumentException( "Unknown generator [generator=" + name + "]"); } _keyGenerator = new TableKeyGenerator( generator, gv, getTableName(), keyField.getColumnName()); break; } } } // generate our full list of fields/columns for use in queries _allFields = fields.toArray(new String[fields.size()]); } /** * Returns the persistent class this is object is a marshaller for. */ public Class<T> getPersistentClass () { return _pclass; } /** * Returns the name of the table in which persistent instances of our class are stored. By * default this is the classname of the persistent object without the package. */ public String getTableName () { return _tableName; } /** * Returns all the persistent fields of our class, in definition order. */ public String[] getFieldNames () { return _allFields; } /** * Returns all the persistent fields that correspond to concrete table columns. */ public String[] getColumnFieldNames () { return _columnFields; } /** * Return the {@link FullTextIndex} registered under the given name, or null if none. */ public FullTextIndex getFullTextIndex (String name) { return _fullTextIndexes.get(name); } /** * Returns the {@link FieldMarshaller} for a named field on our persistent class. */ public FieldMarshaller getFieldMarshaller (String fieldName) { return _fields.get(fieldName); } /** * Returns true if our persistent object defines a primary key. */ public boolean hasPrimaryKey () { return (_pkColumns != null); } /** * Returns the {@link KeyGenerator} used to generate primary keys for this persistent object, * or null if it does not use a key generator. */ public KeyGenerator getKeyGenerator () { return _keyGenerator; } /** * Return the names of the columns that constitute the primary key of our associated persistent * record. */ public String[] getPrimaryKeyFields () { String[] pkcols = new String[_pkColumns.size()]; for (int ii = 0; ii < pkcols.length; ii ++) { pkcols[ii] = _pkColumns.get(ii).getField().getName(); } return pkcols; } /** * Returns a key configured with the primary key of the supplied object. If all the fields are * null, this method returns null. An exception is thrown if some of the fields are null and * some are not, or if the object does not declare a primary key. */ public Key<T> getPrimaryKey (Object object) { return getPrimaryKey(object, true); } /** * Returns a key configured with the primary key of the supplied object. If all the fields are * null, this method returns null. If some of the fields are null and some are not, an * exception is thrown. If the object does not declare a primary key and the second argument is * true, this method throws an exception; if it's false, the method returns null. */ public Key<T> getPrimaryKey (Object object, boolean requireKey) { if (!hasPrimaryKey()) { if (requireKey) { throw new UnsupportedOperationException( _pclass.getName() + " does not define a primary key"); } return null; } try { Comparable[] values = new Comparable[_pkColumns.size()]; boolean hasNulls = false; for (int ii = 0; ii < _pkColumns.size(); ii++) { FieldMarshaller field = _pkColumns.get(ii); values[ii] = (Comparable) field.getField().get(object); if (values[ii] == null || Integer.valueOf(0).equals(values[ii])) { // if this is the first null we see but not the first field, freak out if (!hasNulls && ii > 0) { throw new IllegalArgumentException( "Persistent object's primary key fields are mixed null and non-null."); } hasNulls = true; } else if (hasNulls) { // if this is a non-null field and we've previously seen nulls, also freak throw new IllegalArgumentException( "Persistent object's primary key fields are mixed null and non-null."); } } // if all the fields were null, return null, else build a key return hasNulls ? null : makePrimaryKey(values); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } } /** * Creates a primary key record for the type of object handled by this marshaller, using the * supplied primary key value. */ public Key<T> makePrimaryKey (Comparable... values) { if (!hasPrimaryKey()) { throw new UnsupportedOperationException( getClass().getName() + " does not define a primary key"); } String[] fields = new String[_pkColumns.size()]; for (int ii = 0; ii < _pkColumns.size(); ii++) { fields[ii] = _pkColumns.get(ii).getField().getName(); } return new Key<T>(_pclass, fields, values); } /** * Creates a primary key record for the type of object handled by this marshaller, using the * supplied result set. */ public Key<T> makePrimaryKey (ResultSet rs) throws SQLException { if (!hasPrimaryKey()) { throw new UnsupportedOperationException( getClass().getName() + " does not define a primary key"); } Comparable[] values = new Comparable[_pkColumns.size()]; for (int ii = 0; ii < _pkColumns.size(); ii++) { Object keyValue = _pkColumns.get(ii).getFromSet(rs); if (!(keyValue instanceof Comparable)) { throw new IllegalArgumentException("Key field must be Comparable [field=" + _pkColumns.get(ii).getColumnName() + "]"); } values[ii] = (Comparable) keyValue; } return makePrimaryKey(values); } /** * Returns true if this marshaller has been initialized ({@link #init} has been called), its * migrations run and it is ready for operation. False otherwise. */ public boolean isInitialized () { return _initialized; } /** * Creates a persistent object from the supplied result set. The result set must have come from * a query provided by {@link #createQuery}. */ public T createObject (ResultSet rs) throws SQLException { try { // first, build a set of the fields that we actually received Set<String> fields = new HashSet<String>(); ResultSetMetaData metadata = rs.getMetaData(); for (int ii = 1; ii <= metadata.getColumnCount(); ii ++) { fields.add(metadata.getColumnName(ii)); } // then create and populate the persistent object T po = _pclass.newInstance(); for (FieldMarshaller fm : _fields.values()) { if (!fields.contains(fm.getColumnName())) { // this field was not in the result set, make sure that's OK if (fm.getComputed() != null && !fm.getComputed().required()) { continue; } throw new SQLException("ResultSet missing field: " + fm.getField().getName()); } fm.writeToObject(rs, po); } return po; } catch (SQLException sqe) { // pass this on through throw sqe; } catch (Exception e) { String errmsg = "Failed to unmarshall persistent object [pclass=" + _pclass.getName() + "]"; throw (SQLException)new SQLException(errmsg).initCause(e); } } /** * Fills in the primary key just assigned to the supplied persistence object by the execution * of the results of {@link #createInsert}. * * @return the newly assigned primary key or null if the object does not use primary keys or * this is not the right time to assign the key. */ public Key assignPrimaryKey ( Connection conn, DatabaseLiaison liaison, Object po, boolean postFactum) throws SQLException { // if we have no primary key or no generator, then we're done if (!hasPrimaryKey() || _keyGenerator == null) { return null; } // run this generator either before or after the actual insertion if (_keyGenerator.isPostFactum() != postFactum) { return null; } try { int nextValue = _keyGenerator.nextGeneratedValue(conn, liaison); _pkColumns.get(0).getField().set(po, nextValue); return makePrimaryKey(nextValue); } catch (Exception e) { String errmsg = "Failed to assign primary key [type=" + _pclass + "]"; throw (SQLException) new SQLException(errmsg).initCause(e); } } /** * This is called by the persistence context to register a migration for the entity managed by * this marshaller. */ protected void registerMigration (EntityMigration migration) { _migrations.add(migration); } /** * Initializes the table used by this marshaller. This is called automatically by the {@link * PersistenceContext} the first time an entity is used. If the table does not exist, it will * be created. If the schema version specified by the persistent object is newer than the * database schema, it will be migrated. */ protected void init (final PersistenceContext ctx) throws PersistenceException { if (_initialized) { // sanity check throw new IllegalStateException( "Cannot re-initialize marshaller [type=" + _pclass + "]."); } _initialized = true; final SQLBuilder builder = ctx.getSQLBuilder(new DepotTypes(ctx, _pclass)); // perform the context-sensitive initialization of the field marshallers for (FieldMarshaller fm : _fields.values()) { fm.init(builder); } // figure out the list of fields that correspond to actual table columns and generate the // SQL used to create and migrate our table (unless we're a computed entity) _columnFields = new String[_allFields.length]; String[] declarations = new String[_allFields.length]; int jj = 0; for (int ii = 0; ii < _allFields.length; ii++) { @SuppressWarnings("unchecked") FieldMarshaller<T> fm = _fields.get(_allFields[ii]); // include all persistent non-computed fields String colDef = fm.getColumnDefinition(); if (colDef != null) { _columnFields[jj] = _allFields[ii]; declarations[jj] = colDef; jj ++; } } _columnFields = ArrayUtil.splice(_columnFields, jj); declarations = ArrayUtil.splice(declarations, jj); // if we have no table (i.e. we're a computed entity), we have nothing to create if (getTableName() == null) { return; } // add any additional unique constraints String[][] uniqueConstraintColumns = null; Table table = _pclass.getAnnotation(Table.class); if (table != null) { UniqueConstraint[] uCons = table.uniqueConstraints(); uniqueConstraintColumns = new String[uCons.length][]; for (int kk = 0; kk < uCons.length; kk ++) { String[] columns = uCons[kk].fieldNames(); for (int ii = 0; ii < columns.length; ii ++) { FieldMarshaller fm = getFieldMarshaller(columns[ii]); if (fm == null) { throw new IllegalArgumentException( "Unknown field in @UniqueConstraint: " + columns[ii]); } columns[ii] = fm.getColumnName(); } uniqueConstraintColumns[kk] = columns; } } // if we did not find a schema version field, complain if (_schemaVersion < 0) { log.warning("Unable to read " + _pclass.getName() + "." + SCHEMA_VERSION_FIELD + ". Schema migration disabled."); } // check to see if our schema version table exists, create it if not ctx.invoke(new Modifier() { public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { liaison.createTableIfMissing( conn, SCHEMA_VERSION_TABLE, new String[] { "persistentClass", "version" }, new String[] { "VARCHAR(255) NOT NULL", "INTEGER NOT NULL" }, null, new String[] { "persistentClass" }); return 0; } }); // fetch all relevant information regarding our table from the database final TableMetaData metaData = ctx.invoke(new Query.TrivialQuery<TableMetaData>() { public TableMetaData invoke (Connection conn, DatabaseLiaison dl) throws SQLException { return new TableMetaData(conn.getMetaData()); } }); final Entity entity = _pclass.getAnnotation(Entity.class); // if the table does not exist, create it if (!metaData.tableExists) { final String[] fDeclarations = declarations; final String[][] fUniqueConstraintColumns = uniqueConstraintColumns; ctx.invoke(new Modifier() { public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { // create the table String[] columns = new String[_columnFields.length]; for (int ii = 0; ii < columns.length; ii ++) { columns[ii] = _fields.get(_columnFields[ii]).getColumnName(); } String[] primaryKeyColumns = null; if (_pkColumns != null) { primaryKeyColumns = new String[_pkColumns.size()]; for (int ii = 0; ii < primaryKeyColumns.length; ii ++) { primaryKeyColumns[ii] = _pkColumns.get(ii).getColumnName(); } } liaison.createTableIfMissing(conn, getTableName(), columns, fDeclarations, fUniqueConstraintColumns, primaryKeyColumns); // add its indexen if (entity != null) { for (Index idx : entity.indices()) { liaison.addIndexToTable( conn, getTableName(), idx.columns(), idx.name(), idx.unique()); } } if (_keyGenerator != null) { _keyGenerator.init(conn, liaison); } for (FullTextIndex fti : _fullTextIndexes.values()) { builder.addFullTextSearch(conn, DepotMarshaller.this, fti); } updateVersion(conn, liaison, _schemaVersion); return 0; } }); // and we're done return; } // if the table exists, see if should attempt automatic schema migration if (_schemaVersion < 0) { // nope, versioning disabled verifySchemasMatch(metaData, ctx); return; } // make sure the versions match int currentVersion = ctx.invoke(new Modifier() { public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { String query = " select " + liaison.columnSQL("version") + " from " + liaison.tableSQL(SCHEMA_VERSION_TABLE) + " where " + liaison.columnSQL("persistentClass") + " = '" + getTableName() + "'"; Statement stmt = conn.createStatement(); try { ResultSet rs = stmt.executeQuery(query); return (rs.next()) ? rs.getInt(1) : 1; } finally { stmt.close(); } } }); if (currentVersion == _schemaVersion) { verifySchemasMatch(metaData, ctx); return; } // otherwise try to migrate the schema log.info("Migrating " + getTableName() + " from " + currentVersion + " to " + _schemaVersion + "..."); // run our pre-default-migrations for (EntityMigration migration : _migrations) { if (migration.runBeforeDefault() && migration.shouldRunMigration(currentVersion, _schemaVersion)) { migration.init(getTableName(), _fields); ctx.invoke(migration); } } // this is a little silly, but we need a copy for name disambiguation later Set<String> indicesCopy = new HashSet<String>(metaData.indexColumns.keySet()); // add any missing columns for (String fname : _columnFields) { @SuppressWarnings("unchecked") final FieldMarshaller<T> fmarsh = _fields.get(fname); if (metaData.tableColumns.remove(fmarsh.getColumnName())) { continue; } // otherwise add the column final String coldef = fmarsh.getColumnDefinition(); log.info("Adding column to " + getTableName() + ": " + fmarsh.getColumnName() + " " + coldef); ctx.invoke(new Modifier.Simple() { protected String createQuery (DatabaseLiaison liaison) { return "alter table " + liaison.tableSQL(getTableName()) + " add column " + liaison.columnSQL(fmarsh.getColumnName()) + " " + coldef; } }); // if the column is a TIMESTAMP or DATETIME column, we need to run a special query to // update all existing rows to the current time because MySQL annoyingly assigns // TIMESTAMP columns a value of "0000-00-00 00:00:00" regardless of whether we // explicitly provide a "DEFAULT" value for the column or not, and DATETIME columns // cannot accept CURRENT_TIME or NOW() defaults at all. if (coldef.toLowerCase().indexOf(" timestamp") != -1 || coldef.toLowerCase().indexOf(" datetime") != -1) { log.info("Assigning current time to " + fmarsh.getColumnName() + "."); ctx.invoke(new Modifier.Simple() { protected String createQuery (DatabaseLiaison liaison) { // TODO: is NOW() standard SQL? return "update " + liaison.tableSQL(getTableName()) + " set " + liaison.columnSQL(fmarsh.getColumnName()) + " = NOW()"; } }); } } // add or remove the primary key as needed if (hasPrimaryKey() && metaData.pkName == null) { log.info("Adding primary key."); ctx.invoke(new Modifier() { public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { liaison.addPrimaryKey(conn, getTableName(), getPrimaryKeyFields()); return 0; } }); } else if (!hasPrimaryKey() && metaData.pkName != null) { log.info("Dropping primary key."); ctx.invoke(new Modifier() { public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { liaison.dropPrimaryKey(conn, getTableName(), metaData.pkName); return 0; } }); } // add any missing indices for (final Index index : (entity == null ? new Index[0] : entity.indices())) { if (metaData.indexColumns.containsKey(index.name())) { metaData.indexColumns.remove(index.name()); continue; } ctx.invoke(new Modifier() { public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { liaison.addIndexToTable( conn, getTableName(), index.columns(), index.name(), index.unique()); return 0; } }); } // to get the @Table(uniqueIndices...) indices, we use our clever set of column name sets Set<Set<String>> uniqueIndices = new HashSet<Set<String>>(metaData.indexColumns.values()); if (getTableName() != null && table != null) { for (UniqueConstraint constraint : table.uniqueConstraints()) { // for each given UniqueConstraint, build a new column set Set<String> colSet = new HashSet<String>(Arrays.asList(constraint.fieldNames())); // and check if the table contained this set if (uniqueIndices.contains(colSet)) { continue; // good, carry on } // else build the index; we'll use mysql's convention of naming it after a column, // with possible _N disambiguation; luckily we made a copy of the index names! String indexName = colSet.iterator().next(); if (indicesCopy.contains(indexName)) { int num = 1; indexName += "_"; while (indicesCopy.contains(indexName + num)) { num ++; } indexName += num; } final String[] colArr = colSet.toArray(new String[colSet.size()]); final String fName = indexName; ctx.invoke(new Modifier() { public int invoke (Connection conn, DatabaseLiaison dl) throws SQLException { dl.addIndexToTable(conn, getTableName(), colArr, fName, true); return 0; } }); } } // we do not auto-remove columns but rather require that EntityMigration.Drop records be // registered by hand to avoid accidentally causing the loss of data // we don't auto-remove indices either because we'd have to sort out the potentially // complex origins of an index (which might be because of a @Unique column or maybe the // index was hand defined in a @Column clause) // run our post-default-migrations for (EntityMigration migration : _migrations) { if (!migration.runBeforeDefault() && migration.shouldRunMigration(currentVersion, _schemaVersion)) { migration.init(getTableName(), _fields); ctx.invoke(migration); } } // record our new version in the database ctx.invoke(new Modifier() { public int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { updateVersion(conn, liaison, _schemaVersion); return 0; } }); } protected class TableMetaData { public boolean tableExists; public Set<String> tableColumns = new HashSet<String>(); public Map<String, Set<String>> indexColumns = new HashMap<String, Set<String>>(); public String pkName; public Set<String> pkColumns = new HashSet<String>(); public TableMetaData (DatabaseMetaData meta) throws SQLException { tableExists = meta.getTables("", "", getTableName(), null).next(); if (!tableExists) { return; } ResultSet rs = meta.getColumns(null, null, getTableName(), "%"); while (rs.next()) { tableColumns.add(rs.getString("COLUMN_NAME")); } rs = meta.getIndexInfo(null, null, getTableName(), false, false); while (rs.next()) { String indexName = rs.getString("INDEX_NAME"); Set<String> set = indexColumns.get(indexName); if (rs.getBoolean("NON_UNIQUE")) { // not a unique index: just make sure there's an entry in the keyset if (set == null) { indexColumns.put(indexName, null); } } else { // for unique indices we collect the column names if (set == null) { set = new HashSet<String>(); indexColumns.put(indexName, set); } set.add(rs.getString("COLUMN_NAME")); } } rs = meta.getPrimaryKeys(null, null, getTableName()); while (rs.next()) { pkName = rs.getString("PK_NAME"); pkColumns.add(rs.getString("COLUMN_NAME")); } } } /** * Checks that there are no database columns for which we no longer have Java fields. */ protected void verifySchemasMatch (TableMetaData meta, PersistenceContext ctx) throws PersistenceException { for (String fname : _columnFields) { FieldMarshaller fmarsh = _fields.get(fname); meta.tableColumns.remove(fmarsh.getColumnName()); } for (String column : meta.tableColumns) { log.warning(getTableName() + " contains stale column '" + column + "'."); } } protected void updateVersion (Connection conn, DatabaseLiaison liaison, int version) throws SQLException { String update = "update " + liaison.tableSQL(SCHEMA_VERSION_TABLE) + " set " + liaison.columnSQL("version") + " = " + version + " where " + liaison.columnSQL("persistentClass") + " = '" + getTableName() + "'"; Statement stmt = conn.createStatement(); try { if (stmt.executeUpdate(update) == 0) { String insert = "insert into " + liaison.tableSQL(SCHEMA_VERSION_TABLE) + " values('" + getTableName() + "', " + version + ")"; stmt.executeUpdate(insert); } } finally { stmt.close(); } } /** The persistent object class that we manage. */ protected Class<T> _pclass; /** The name of our persistent object table. */ protected String _tableName; /** A field marshaller for each persistent field in our object. */ protected Map<String, FieldMarshaller> _fields = new HashMap<String, FieldMarshaller>(); /** The field marshallers for our persistent object's primary key columns or null if it did not * define a primary key. */ protected ArrayList<FieldMarshaller> _pkColumns; /** The generator to use for auto-generating primary key values, or null. */ protected KeyGenerator _keyGenerator; /** The persisent fields of our object, in definition order. */ protected String[] _allFields; /** The fields of our object with directly corresponding table columns. */ protected String[] _columnFields; /** A mapping of all of the full text index annotations for our persistent record. */ protected Map<String, FullTextIndex> _fullTextIndexes = new HashMap<String, FullTextIndex>(); /** The version of our persistent object schema as specified in the class definition. */ protected int _schemaVersion = -1; /** Indicates that we have been initialized (created or migrated our tables). */ protected boolean _initialized; /** A list of hand registered entity migrations to run prior to doing the default migration. */ protected ArrayList<EntityMigration> _migrations = new ArrayList<EntityMigration>(); /** The name of the table we use to track schema versions. */ protected static final String SCHEMA_VERSION_TABLE = "DepotSchemaVersion"; }
// samskivert library - useful routines for java programs // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.util; /** * A result listener that contains another result listener to which failure is * passed directly, but allows for success to be handled in whatever way is * desired by the chaining result listener. */ public abstract class ChainedResultListener<T> implements ResultListener<T> { /** * Creates a chained result listener that will pass failure through to the * specified target. */ public ChainedResultListener (ResultListener<T> target) { _target = target; } // documentation inherited from interface ResultListener public void requestFailed (Exception cause) { _target.requestFailed(cause); } protected ResultListener<T> _target; }
package net.cloudapp.wcnjenkins; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; public class TestBankAccount { @Test public void testDebitWithSufficientFunds(){ BankAccount account = new BankAccount(10); double amount = account.debit(5); Assert.assertEquals(5.0,amount); } @Test public void testDebitWithInsufficientFunds(){ BankAccount account = new BankAccount(10); double amount = account.debit(11); Assert.assertEquals(10,amount); } @Test public void testDebitWithNegativeFunds(){ BankAccount account = new BankAccount(-10); double amount = account.debit(5); Assert.assertEquals(-10,amount); } }