lang
stringclasses
1 value
license
stringclasses
13 values
stderr
stringlengths
0
350
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
7
45.1k
new_contents
stringlengths
0
1.87M
new_file
stringlengths
6
292
old_contents
stringlengths
0
1.87M
message
stringlengths
6
9.26k
old_file
stringlengths
6
292
subject
stringlengths
0
4.45k
Java
bsd-2-clause
error: pathspec 'plugins/scripting/jruby/src/test/java/imagej/script/JRubyTest.java' did not match any file(s) known to git
8f5b644bc4d3d7a32b19f731667ec9e6f0342ee0
1
biovoxxel/imagej,TehSAUCE/imagej,biovoxxel/imagej,TehSAUCE/imagej,TehSAUCE/imagej,biovoxxel/imagej
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2013 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of any organization. * #L% */ package imagej.script; import static org.junit.Assert.assertEquals; import java.io.StringReader; import javax.script.Bindings; import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.ScriptEngineFactory; import org.junit.Test; import org.scijava.Context; /** * JRuby unit tests. * * @author Johannes Schindelin */ public class JRubyTest { @Test public void testBasic() throws Exception { final Context context = new Context(ScriptService.class); final ScriptService scriptService = context.getService(ScriptService.class); String script = "$x = 1 + 2;"; final ScriptEngine engine = (ScriptEngine)scriptService.eval("add.rb", new StringReader(script)); assertEquals("3", engine.get("$x").toString()); } @Test public void testLocals() throws Exception { final Context context = new Context(ScriptService.class); final ScriptService scriptService = context.getService(ScriptService.class); final ScriptEngineFactory factory = scriptService.getByFileExtension("rb"); final ScriptEngine engine = factory.getScriptEngine(); assertEquals(JRubyScriptEngine.class, engine.getClass()); engine.put("$hello", 17); assertEquals("17", engine.eval("$hello").toString()); assertEquals("17", engine.get("$hello").toString()); Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE); bindings.clear(); assertEquals("", engine.get("$hello").toString()); } }
plugins/scripting/jruby/src/test/java/imagej/script/JRubyTest.java
Add simple unit tests for JRuby Signed-off-by: Johannes Schindelin <53fb8db7833fca1e1746dd8592f61048d350f64c@gmx.de>
plugins/scripting/jruby/src/test/java/imagej/script/JRubyTest.java
Add simple unit tests for JRuby
Java
bsd-2-clause
error: pathspec 'src/main/java/fape/core/planning/planninggraph/RelaxedPlanExtractor.java' did not match any file(s) known to git
0fe769f5d30a6340d9c673bcfccb9570576e96bc
1
athy/fape,athy/fape,athy/fape,athy/fape
package fape.core.planning.planninggraph; import fape.core.inference.HLeveledReasoner; import fape.core.planning.grounding.*; import fape.core.planning.planner.APlanner; import fape.core.planning.states.State; import fape.core.planning.timelines.Timeline; import fape.exceptions.FAPEException; import fape.exceptions.NoSolutionException; import planstack.anml.model.concrete.Action; import planstack.anml.model.concrete.ActionCondition; import java.util.Collection; import java.util.HashSet; import java.util.Set; public class RelaxedPlanExtractor { final APlanner planner; final HLeveledReasoner<GAction,GTaskCond> decompReas; final HLeveledReasoner<GAction,GTaskCond> derivReaas; final HLeveledReasoner<GAction,Fluent> baseCausalReas; final State st; final Set<GAction> allowedActions; final Set<GAction> inPlanActions; public RelaxedPlanExtractor(APlanner planner, State st) { this.planner = planner; this.st = st; allowedActions = new HashSet<>(planner.reachability.getAllActions(st)); inPlanActions = new HashSet<>(); for(Action a : st.getAllActions()) { for(GAction ga : planner.reachability.groundedVersions(a, st)) inPlanActions.add(ga); } decompReas = decomposabilityReasoner(st); derivReaas = derivabilityReasoner(st); baseCausalReas = new HLeveledReasoner<>(); for (GAction ga : planner.reachability.getAllActions(st)) { baseCausalReas.addClause(ga.pre, ga.add, ga); } } /** initial "facts" are actions with no subtasks */ public HLeveledReasoner<GAction, GTaskCond> decomposabilityReasoner(State st) { HLeveledReasoner<GAction, GTaskCond> baseHLR = new HLeveledReasoner<>(); for (GAction ga : planner.reachability.getAllActions(st)) { GTaskCond[] effect = new GTaskCond[1]; effect[0] = ga.task; baseHLR.addClause(ga.subTasks.toArray(new GTaskCond[ga.subTasks.size()]), effect, ga); } baseHLR.infer(); for(GAction ga : allowedActions) { if(!(baseHLR.levelOfClause(ga) > -1) && !inPlanActions.contains(ga)) System.out.println(baseHLR.report()); assert baseHLR.levelOfClause(ga) > -1 || inPlanActions.contains(ga); } return baseHLR; } /** initial facts opened tasks and initial clauses are non-motivated actions*/ public HLeveledReasoner<GAction, GTaskCond> derivabilityReasoner(State st) { HLeveledReasoner<GAction, GTaskCond> baseHLR = new HLeveledReasoner<>(); for (GAction ga : planner.reachability.getAllActions(st)) { if(ga.abs.motivated()) { GTaskCond[] condition = new GTaskCond[1]; condition[0] = ga.task; baseHLR.addClause(condition, ga.subTasks.toArray(new GTaskCond[ga.subTasks.size()]), ga); } else { baseHLR.addClause(new GTaskCond[0], ga.subTasks.toArray(new GTaskCond[ga.subTasks.size()]), ga); } } for(GTaskCond tc : planner.reachability.getDerivableTasks(st)) { baseHLR.set(tc); } baseHLR.infer(); for(GAction ga : allowedActions) { assert baseHLR.levelOfClause(ga) > -1 || inPlanActions.contains(ga); } return baseHLR; } public HLeveledReasoner<GAction,Fluent> causalReasonerForOpenGoal(State st, Timeline consumer) { HLeveledReasoner<GAction, Fluent> hlr = baseCausalReas.clone(); Collection<Fluent> init = GroundProblem.fluentsBefore(st, consumer.getFirstTimePoints()); for (Fluent i : init) { hlr.set(i); } hlr.infer(); return hlr; } private int costOfAction(GAction ga, HLeveledReasoner<GAction,Fluent> causalReas) { assert ga != null; // System.out.println(causalReas.levelOfClause(ga) +" "+ derivReaas.levelOfClause(ga)+" "+ decompReas.levelOfClause(ga)); if(causalReas.levelOfClause(ga) <0 || derivReaas.levelOfClause(ga)<0 || decompReas.levelOfClause(ga)<0) return -1; // impossible in at least one return causalReas.levelOfClause(ga) + derivReaas.levelOfClause(ga) -1 + decompReas.levelOfClause(ga) -1; } private int costOfTask(GTaskCond t, HLeveledReasoner<GAction,Fluent> causalReas) { assert t != null; if(!derivReaas.knowsFact(t)) return -1; if(!decompReas.knowsFact(t)) return -1; if(derivReaas.levelOfFact(t) == -1 || decompReas.levelOfFact(t) == -1) return -1; return derivReaas.levelOfFact(t) + decompReas.levelOfFact(t); } public Fluent selectMostInterestingFluent(Collection<Fluent> fluents, HLeveledReasoner<GAction,Fluent> causalReas) throws NoSolutionException { Fluent bestFluent = null; int bestFluentCost = Integer.MAX_VALUE; for(Fluent f : fluents) { if(causalReas.knowsFact(f) && causalReas.levelOfFact(f) != -1) { int bestEnablerCost = Integer.MAX_VALUE; for(GAction ga : causalReas.candidatesFor(f)) { if(ga == null) return f; // init fact, we can not do better assert allowedActions.contains(ga); int cost = costOfAction(ga, causalReas); if(cost >= 0 && cost < bestEnablerCost) bestEnablerCost = cost; } assert bestEnablerCost >= 0; if(bestEnablerCost < bestFluentCost) { bestFluent = f; bestFluentCost = bestEnablerCost; } } } if(bestFluent != null) return bestFluent; else throw new NoSolutionException(); } public GAction selectMostInterestingAction(Collection<GAction> actions, HLeveledReasoner<GAction,Fluent> causalReas) throws NoSolutionException { GAction bestAction = null; int bestActionCost = Integer.MAX_VALUE; for(GAction ga : actions) { if(ga == null) return null; // init fact, we can not do better int cost = costOfAction(ga, causalReas); if(cost >= 0 && cost < bestActionCost) { bestActionCost = cost; bestAction = ga; } } if(bestAction != null) return bestAction; else if(planner.breakIfNoSolution) { throw new NoSolutionException(); } else throw new NoSolutionException(); } public GTaskCond selectMostInterestingTask(Collection<GTaskCond> tasks, HLeveledReasoner<GAction,Fluent> causalReas) { GTaskCond best = null; int bestCost = Integer.MAX_VALUE; for(GTaskCond t : tasks) { int cost = costOfTask(t, causalReas); if(cost != -1 && cost < bestCost) { best = t; bestCost = cost; } } if(best == null) throw new FAPEException("OUPSI"); return best; } public int numAdditionalStepWithReasoner() { try { Collection<GAction> alreadyUsed = new HashSet<>(); Set<GTaskCond> derivPending = new HashSet<>(); Set<GTaskCond> decompPending = new HashSet<>(); for (Timeline tl : st.tdb.getConsumers()) { HLeveledReasoner<GAction, Fluent> hlr = causalReasonerForOpenGoal(st, tl); Set<Fluent> causalPending = new HashSet<>(); Collection<Fluent> goals = DisjunctiveFluent.fluentsOf(tl.stateVariable, tl.getGlobalConsumeValue(), st, true); causalPending.add(selectMostInterestingFluent(goals, hlr)); while (!causalPending.isEmpty()) { Fluent og = causalPending.iterator().next(); causalPending.remove(og); GAction ga = selectMostInterestingAction(hlr.candidatesFor(og), hlr); // if we need action (ga !=null) and we didn't already used it if(ga != null && !alreadyUsed.contains(ga)) { causalPending.addAll(ga.pre); derivPending.addAll(derivReaas.conditionsOf(ga)); decompPending.addAll(decompReas.conditionsOf(ga)); alreadyUsed.add(ga); } } } Set<Fluent> causalPending = new HashSet<>(); HLeveledReasoner<GAction, Fluent> hlr = baseCausalReas.clone(); Collection<Fluent> init = GroundProblem.allFluents(st); //GroundProblem.fluentsBefore(st, consumer.getFirstTimePoints()); for (Fluent i : init) { hlr.set(i); } hlr.infer(); for(ActionCondition liftedTask : st.getOpenTaskConditions()) { Collection<GTaskCond> tasks = planner.reachability.getGroundedTasks(liftedTask, st); decompPending.add(selectMostInterestingTask(tasks, hlr)); } while(!causalPending.isEmpty() || !derivPending.isEmpty() || !decompPending.isEmpty()) { GAction ga = null; if(!causalPending.isEmpty()) { Fluent og = causalPending.iterator().next(); causalPending.remove(og); ga = selectMostInterestingAction(hlr.candidatesFor(og), hlr); } else if(!derivPending.isEmpty()) { GTaskCond task = derivPending.iterator().next(); derivPending.remove(task); ga = selectMostInterestingAction(derivReaas.candidatesFor(task), hlr); } else { assert !decompPending.isEmpty(); GTaskCond task = decompPending.iterator().next(); decompPending.remove(task); ga = selectMostInterestingAction(decompReas.candidatesFor(task), hlr); } // if we need action (ga !=null) and we didn't already used it if(ga != null && !alreadyUsed.contains(ga)) { causalPending.addAll(ga.pre); derivPending.addAll(derivReaas.conditionsOf(ga)); decompPending.addAll(decompReas.conditionsOf(ga)); alreadyUsed.add(ga); } } return alreadyUsed.size(); } catch (NoSolutionException e) { if (planner.breakIfNoSolution) { e.printStackTrace(); System.out.println("BREAK"); } return 9999999; } } }
src/main/java/fape/core/planning/planninggraph/RelaxedPlanExtractor.java
Initial version of the relaxed plan extractor.
src/main/java/fape/core/planning/planninggraph/RelaxedPlanExtractor.java
Initial version of the relaxed plan extractor.
Java
bsd-3-clause
5dd3ad3ecb9c7c83c2b8811096eb081e7987e32c
0
krieger-od/nwjs_chromium.src,Chilledheart/chromium,Fireblend/chromium-crosswalk,dednal/chromium.src,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,ondra-novak/chromium.src,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,M4sse/chromium.src,Just-D/chromium-1,M4sse/chromium.src,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,ltilve/chromium,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk,dednal/chromium.src,dednal/chromium.src,dednal/chromium.src,ondra-novak/chromium.src,dednal/chromium.src,dednal/chromium.src,littlstar/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,jaruba/chromium.src,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,Just-D/chromium-1,Jonekee/chromium.src,fujunwei/chromium-crosswalk,Just-D/chromium-1,M4sse/chromium.src,ltilve/chromium,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,Chilledheart/chromium,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,M4sse/chromium.src,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,littlstar/chromium.src,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ltilve/chromium,littlstar/chromium.src,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,Jonekee/chromium.src,dushu1203/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,jaruba/chromium.src,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,jaruba/chromium.src,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,Chilledheart/chromium,Just-D/chromium-1,bright-sparks/chromium-spacewalk,ltilve/chromium,markYoungH/chromium.src,axinging/chromium-crosswalk,dushu1203/chromium.src,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,ltilve/chromium,Fireblend/chromium-crosswalk,M4sse/chromium.src,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ltilve/chromium,Jonekee/chromium.src,jaruba/chromium.src,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,ltilve/chromium,Jonekee/chromium.src,ltilve/chromium,M4sse/chromium.src,jaruba/chromium.src,dednal/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,markYoungH/chromium.src,fujunwei/chromium-crosswalk,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,M4sse/chromium.src,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,markYoungH/chromium.src,littlstar/chromium.src,jaruba/chromium.src,Just-D/chromium-1,markYoungH/chromium.src,ltilve/chromium,Chilledheart/chromium,dednal/chromium.src,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,littlstar/chromium.src,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,Just-D/chromium-1,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,dushu1203/chromium.src,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,Jonekee/chromium.src,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,markYoungH/chromium.src,Jonekee/chromium.src,chuan9/chromium-crosswalk
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.util; /** * Contains various math utilities used throughout Chrome Mobile. */ public class MathUtils { private MathUtils() {} /** * Returns the passed in value if it resides within the specified range (inclusive). If not, * it will return the closest boundary from the range. The ordering of the boundary values does * not matter. * * @param value The value to be compared against the range. * @param a First boundary range value. * @param b Second boundary range value. * @return The passed in value if it is within the range, otherwise the closest boundary value. */ public static int clamp(int value, int a, int b) { int min = (a > b) ? b : a; int max = (a > b) ? a : b; if (value < min) value = min; else if (value > max) value = max; return value; } /** * Returns the passed in value if it resides within the specified range (inclusive). If not, * it will return the closest boundary from the range. The ordering of the boundary values does * not matter. * * @param value The value to be compared against the range. * @param a First boundary range value. * @param b Second boundary range value. * @return The passed in value if it is within the range, otherwise the closest boundary value. */ public static long clamp(long value, long a, long b) { long min = (a > b) ? b : a; long max = (a > b) ? a : b; if (value < min) value = min; else if (value > max) value = max; return value; } /** * Returns the passed in value if it resides within the specified range (inclusive). If not, * it will return the closest boundary from the range. The ordering of the boundary values does * not matter. * * @param value The value to be compared against the range. * @param a First boundary range value. * @param b Second boundary range value. * @return The passed in value if it is within the range, otherwise the closest boundary value. */ public static float clamp(float value, float a, float b) { float min = (a > b) ? b : a; float max = (a > b) ? a : b; if (value < min) value = min; else if (value > max) value = max; return value; } /** * Computes a%b that is positive. Note that result of % operation is not always positive. * @return a%b >= 0 ? a%b : a%b + b */ public static int positiveModulo(int a, int b) { int mod = a % b; return mod >= 0 ? mod : mod + b; } }
chrome/android/java/src/org/chromium/chrome/browser/util/MathUtils.java
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.util; /** * Contains various math utilities used throughout Chrome Mobile. */ public class MathUtils { private MathUtils() {} /** * Returns the passed in value if it resides within the specified range (inclusive). If not, * it will return the closest boundary from the range. The ordering of the boundary values does * not matter. * * @param value The value to be compared against the range. * @param a First boundary range value. * @param b Second boundary range value. * @return The passed in value if it is within the range, otherwise the closest boundary value. */ public static int clamp(int value, int a, int b) { int min = (a > b) ? b : a; int max = (a > b) ? a : b; if (value < min) value = min; else if (value > max) value = max; return value; } /** * Returns the passed in value if it resides within the specified range (inclusive). If not, * it will return the closest boundary from the range. The ordering of the boundary values does * not matter. * * @param value The value to be compared against the range. * @param a First boundary range value. * @param b Second boundary range value. * @return The passed in value if it is within the range, otherwise the closest boundary value. */ public static long clamp(long value, long a, long b) { long min = (a > b) ? b : a; long max = (a > b) ? a : b; if (value < min) value = min; else if (value > max) value = max; return value; } /** * Returns the passed in value if it resides within the specified range (inclusive). If not, * it will return the closest boundary from the range. The ordering of the boundary values does * not matter. * * @param value The value to be compared against the range. * @param a First boundary range value. * @param b Second boundary range value. * @return The passed in value if it is within the range, otherwise the closest boundary value. */ public static float clamp(float value, float a, float b) { float min = (a > b) ? b : a; float max = (a > b) ? a : b; if (value < min) value = min; else if (value > max) value = max; return value; } }
[Android] Add positive modulo method in MathUtils class. BUG=386785 Review URL: https://codereview.chromium.org/394353003 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@283860 0039d316-1c4b-4281-b951-d872f2087c98
chrome/android/java/src/org/chromium/chrome/browser/util/MathUtils.java
[Android] Add positive modulo method in MathUtils class.
Java
bsd-3-clause
8d16912fb99149fd303c4317fad6203eb58215ec
0
hce/antlr4,parrt/antlr4,chienjchienj/antlr4,chandler14362/antlr4,sidhart/antlr4,joshids/antlr4,Pursuit92/antlr4,sidhart/antlr4,Pursuit92/antlr4,ericvergnaud/antlr4,worsht/antlr4,cooperra/antlr4,krzkaczor/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,jvanzyl/antlr4,chandler14362/antlr4,mcanthony/antlr4,antlr/antlr4,parrt/antlr4,antlr/antlr4,chandler14362/antlr4,Distrotech/antlr4,Distrotech/antlr4,antlr/antlr4,Pursuit92/antlr4,chandler14362/antlr4,wjkohnen/antlr4,cocosli/antlr4,Distrotech/antlr4,parrt/antlr4,lncosie/antlr4,lncosie/antlr4,mcanthony/antlr4,cocosli/antlr4,worsht/antlr4,krzkaczor/antlr4,joshids/antlr4,antlr/antlr4,cocosli/antlr4,lncosie/antlr4,supriyantomaftuh/antlr4,supriyantomaftuh/antlr4,antlr/antlr4,joshids/antlr4,wjkohnen/antlr4,jvanzyl/antlr4,lncosie/antlr4,mcanthony/antlr4,mcanthony/antlr4,ericvergnaud/antlr4,antlr/antlr4,Pursuit92/antlr4,supriyantomaftuh/antlr4,parrt/antlr4,krzkaczor/antlr4,ericvergnaud/antlr4,chandler14362/antlr4,hce/antlr4,wjkohnen/antlr4,antlr/antlr4,wjkohnen/antlr4,antlr/antlr4,chandler14362/antlr4,joshids/antlr4,cocosli/antlr4,Pursuit92/antlr4,ericvergnaud/antlr4,mcanthony/antlr4,lncosie/antlr4,parrt/antlr4,jvanzyl/antlr4,ericvergnaud/antlr4,wjkohnen/antlr4,chienjchienj/antlr4,supriyantomaftuh/antlr4,parrt/antlr4,jvanzyl/antlr4,cooperra/antlr4,Pursuit92/antlr4,joshids/antlr4,Distrotech/antlr4,ericvergnaud/antlr4,chienjchienj/antlr4,chienjchienj/antlr4,Distrotech/antlr4,hce/antlr4,sidhart/antlr4,krzkaczor/antlr4,antlr/antlr4,cooperra/antlr4,wjkohnen/antlr4,parrt/antlr4,krzkaczor/antlr4,worsht/antlr4,joshids/antlr4,worsht/antlr4,Pursuit92/antlr4,chandler14362/antlr4,Pursuit92/antlr4,hce/antlr4,supriyantomaftuh/antlr4,wjkohnen/antlr4,parrt/antlr4,sidhart/antlr4,sidhart/antlr4,chienjchienj/antlr4,joshids/antlr4,worsht/antlr4,ericvergnaud/antlr4,wjkohnen/antlr4,antlr/antlr4,joshids/antlr4,parrt/antlr4,chandler14362/antlr4,deveshg/antlr4,cooperra/antlr4,wjkohnen/antlr4,parrt/antlr4,Pursuit92/antlr4,chandler14362/antlr4,ericvergnaud/antlr4
package org.antlr.v4.test; import org.junit.Test; /** */ public class TestLeftRecursion extends BaseTest { protected boolean debug = false; @Test public void testSimple() throws Exception { String grammar = "grammar T;\n" + "s @after {System.out.println($ctx.toStringTree(this));} : a ;\n" + "a : a ID\n" + " | ID" + " ;\n" + "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "s", "x", debug); String expecting = "(s (a x))\n"; assertEquals(expecting, found); found = execParser("T.g", grammar, "TParser", "TLexer", "s", "x y", debug); expecting = "(s (a (a x) y))\n"; assertEquals(expecting, found); found = execParser("T.g", grammar, "TParser", "TLexer", "s", "x y z", debug); expecting = "(s (a (a (a x) y) z))\n"; assertEquals(expecting, found); } @Test public void testSemPred() throws Exception { String grammar = "grammar T;\n" + "s @after {System.out.println($ctx.toStringTree(this));} : a ;\n" + "a : a {true}? ID\n" + " | ID" + " ;\n" + "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "s", "x y z", debug); String expecting = "(s (a (a (a x) y) z))\n"; assertEquals(expecting, found); } @Test public void testTernaryExpr() throws Exception { String grammar = "grammar T;\n" + "s @after {System.out.println($ctx.toStringTree(this));} : e EOF ;\n" + // must indicate EOF can follow or 'a<EOF>' won't match "e : e '*' e" + " | e '+' e" + " | e '?'<assoc=right> e ':' e" + " | e '='<assoc=right> e" + " | ID" + " ;\n" + "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; String[] tests = { "a", "(s (e a) <EOF>)", "a+b", "(s (e (e a) + (e b)) <EOF>)", "a*b", "(s (e (e a) * (e b)) <EOF>)", "a?b:c", "(s (e (e a) ? (e b) : (e c)) <EOF>)", "a=b=c", "(s (e (e a) = (e (e b) = (e c))) <EOF>)", "a?b+c:d", "(s (e (e a) ? (e (e b) + (e c)) : (e d)) <EOF>)", "a?b=c:d", "(s (e (e a) ? (e (e b) = (e c)) : (e d)) <EOF>)", "a? b?c:d : e", "(s (e (e a) ? (e (e b) ? (e c) : (e d)) : (e e)) <EOF>)", "a?b: c?d:e", "(s (e (e a) ? (e b) : (e (e c) ? (e d) : (e e))) <EOF>)", }; runTests(grammar, tests, "s"); } @Test public void testExpressions() throws Exception { String grammar = "grammar T;\n" + "s @after {System.out.println($ctx.toStringTree(this));} : e EOF ;\n" + // must indicate EOF can follow "e : e '.' ID\n" + " | e '.' 'this'\n" + " | '-' e\n" + " | e '*' e\n" + " | e ('+'|'-') e\n" + " | INT\n" + " | ID\n" + " ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+ ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; String[] tests = { "a", "(s (e a) <EOF>)", "1", "(s (e 1) <EOF>)", "a-1", "(s (e (e a) - (e 1)) <EOF>)", "a.b", "(s (e (e a) . b) <EOF>)", "a.this", "(s (e (e a) . this) <EOF>)", "-a", "(s (e - (e a)) <EOF>)", "-a+b", "(s (e (e - (e a)) + (e b)) <EOF>)", }; runTests(grammar, tests, "s"); } @Test public void testJavaExpressions() throws Exception { // Generates about 7k in bytecodes for generated e_ rule; // Well within the 64k method limit. e_primary compiles // to about 2k in bytecodes. // this is simplified from real java String grammar = "grammar T;\n" + "s @after {System.out.println($ctx.toStringTree(this));} : e EOF ;\n" + // must indicate EOF can follow "expressionList\n" + " : e (',' e)*\n" + " ;\n" + "e : '(' e ')'\n" + " | 'this' \n" + " | 'super'\n" + " | INT\n" + " | ID\n" + " | type '.' 'class'\n" + " | e '.' ID\n" + " | e '.' 'this'\n" + " | e '.' 'super' '(' expressionList? ')'\n" + " | e '.' 'new' ID '(' expressionList? ')'\n" + " | 'new' type ( '(' expressionList? ')' | ('[' e ']')+)\n" + " | e '[' e ']'\n" + " | '(' type ')' e\n" + " | e ('++' | '--')\n" + " | e '(' expressionList? ')'\n" + " | ('+'|'-'|'++'|'--') e\n" + " | ('~'|'!') e\n" + " | e ('*'|'/'|'%') e\n" + " | e ('+'|'-') e\n" + " | e ('<<' | '>>>' | '>>') e\n" + " | e ('<=' | '>=' | '>' | '<') e\n" + " | e 'instanceof' e\n" + " | e ('==' | '!=') e\n" + " | e '&' e\n" + " | e '^'<assoc=right> e\n" + " | e '|' e\n" + " | e '&&' e\n" + " | e '||' e\n" + " | e '?' e ':' e\n" + " | e ('='<assoc=right>\n" + " |'+='<assoc=right>\n" + " |'-='<assoc=right>\n" + " |'*='<assoc=right>\n" + " |'/='<assoc=right>\n" + " |'&='<assoc=right>\n" + " |'|='<assoc=right>\n" + " |'^='<assoc=right>\n" + " |'>>='<assoc=right>\n" + " |'>>>='<assoc=right>\n" + " |'<<='<assoc=right>\n" + " |'%='<assoc=right>) e\n" + " ;\n" + "type: ID \n" + " | ID '[' ']'\n" + " | 'int'\n" + " | 'int' '[' ']' \n" + " ;\n" + "ID : ('a'..'z'|'A'..'Z'|'_'|'$')+;\n" + "INT : '0'..'9'+ ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; String[] tests = { "a|b&c", "(s (e (e a) | (e (e b) & (e c))) <EOF>)", "(a|b)&c", "(s (e (e ( (e (e a) | (e b)) )) & (e c)) <EOF>)", "a > b", "(s (e (e a) > (e b)) <EOF>)", "a >> b", "(s (e (e a) >> (e b)) <EOF>)", "(T)x", "(s (e ( (type T) ) (e x)) <EOF>)", "new A().b", "(s (e (e new (type A) ( )) . b) <EOF>)", "(T)t.f()", "(s (e (e ( (type T) ) (e (e t) . f)) ( )) <EOF>)", "a.f(x)==T.c", "(s (e (e (e (e a) . f) ( (expressionList (e x)) )) == (e (e T) . c)) <EOF>)", "a.f().g(x,1)", "(s (e (e (e (e (e a) . f) ( )) . g) ( (expressionList (e x) , (e 1)) )) <EOF>)", "new T[((n-1) * x) + 1]", "(s (e new (type T) [ (e (e ( (e (e ( (e (e n) - (e 1)) )) * (e x)) )) + (e 1)) ]) <EOF>)", }; runTests(grammar, tests, "s"); } @Test public void testDeclarations() throws Exception { String grammar = "grammar T;\n" + "s @after {System.out.println($ctx.toStringTree(this));} : declarator EOF ;\n" + // must indicate EOF can follow "declarator\n" + " : declarator '[' e ']'\n" + " | declarator '[' ']'\n" + " | declarator '(' ')'\n" + " | '*' declarator\n" + // binds less tight than suffixes " | '(' declarator ')'\n" + " | ID\n" + " ;\n" + "e : INT ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+ ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; String[] tests = { "a", "(s (declarator a) <EOF>)", "*a", "(s (declarator * (declarator a)) <EOF>)", "**a", "(s (declarator * (declarator * (declarator a))) <EOF>)", "a[3]", "(s (declarator (declarator a) [ (e 3) ]) <EOF>)", "b[]", "(s (declarator (declarator b) [ ]) <EOF>)", "(a)", "(s (declarator ( (declarator a) )) <EOF>)", "a[]()", "(s (declarator (declarator (declarator a) [ ]) ( )) <EOF>)", "a[][]", "(s (declarator (declarator (declarator a) [ ]) [ ]) <EOF>)", "*a[]", "(s (declarator * (declarator (declarator a) [ ])) <EOF>)", "(*a)[]", "(s (declarator (declarator ( (declarator * (declarator a)) )) [ ]) <EOF>)", }; runTests(grammar, tests, "s"); } @Test public void testReturnValueAndActions() throws Exception { String grammar = "grammar T;\n" + "s : e {System.out.println($e.v);} ;\n" + "e returns [int v, List<String> ignored]\n" + " : a=e '*' b=e {$v = $a.v * $b.v;}\n" + " | a=e '+' b=e {$v = $a.v + $b.v;}\n" + " | INT {$v = $INT.int;}\n" + " | '(' x=e ')' {$v = $x.v;}\n" + " ;\n" + "INT : '0'..'9'+ ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; String[] tests = { "4", "4", "1+2", "3", "1+2*3", "7", "(1+2)*3", "9", }; runTests(grammar, tests, "s"); } @Test public void testReturnValueAndActionsAndLabels() throws Exception { String grammar = "grammar T;\n" + "s : q=e {System.out.println($e.v);} ;\n" + "\n" + "e returns [int v]\n" + " : a=e op='*' b=e {$v = $a.v * $b.v;} -> mult\n" + " | a=e '+' b=e {$v = $a.v + $b.v;} -> add\n" + " | INT {$v = $INT.int;} -> anInt\n" + " | '(' x=e ')' {$v = $x.v;} -> parens\n" + " | x=e '++' {$v = $x.v+1;} -> inc\n" + " | e '--' -> dec\n" + " | ID {$v = 3;} -> anID\n" + " ; \n" + "\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+ ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; String[] tests = { "4", "4", "1+2", "3", "1+2*3", "7", "i++*3", "12", }; runTests(grammar, tests, "s"); } @Test public void testPrefixOpWithActionAndLabel() throws Exception { String grammar = "grammar T;\n" + "s : e {System.out.println($e.result);} ;\n" + "\n" + "e returns [String result]\n" + " : ID '=' e1=e { $result = \"(\" + $ID.getText() + \"=\" + $e1.result + \")\"; }\n" + " | ID { $result = $ID.getText(); }\n" + " | e1=e '+' e2=e { $result = \"(\" + $e1.result + \"+\" + $e2.result + \")\"; }\n" + " ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+ ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; String[] tests = { "a", "a", "a+b", "(a+b)", "a=b+c", "((a=b)+c)", }; runTests(grammar, tests, "s"); } @Test public void testAmbigLR() throws Exception { String grammar = "// START: g\n" + "grammar Expr;\n" + "// END: g\n" + "\n" + "// START:stat\n" + "prog: stat ;\n" + "\n" + "stat: expr NEWLINE -> printExpr\n" + " | ID '=' expr NEWLINE -> assign\n" + " | NEWLINE -> blank\n" + " ;\n" + "// END:stat\n" + "\n" + "// START:expr\n" + "expr: expr ('*'|'/') expr -> MulDiv\n" + " | expr ('+'|'-') expr -> AddSub\n" + " | INT -> int\n" + " | ID -> id\n" + " | '(' expr ')' -> parens\n" + " ;\n" + "// END:expr\n" + "\n" + "// show marginal cost of adding a clear/wipe command for memory\n" + "\n" + "// START:tokens\n" + "MUL : '*' ; // assigns token name to '*' used above in grammar\n" + "DIV : '/' ;\n" + "ADD : '+' ;\n" + "SUB : '-' ;\n" + "ID : [a-zA-Z]+ ; // match identifiers\n" + "INT : [0-9]+ ; // match integers\n" + "NEWLINE:'\\r'? '\\n' ; // return newlines to parser (is end-statement signal)\n" + "WS : [ \\t]+ -> skip ; // toss out whitespace\n" + "// END:tokens\n"; String result = execParser("Expr.g4", grammar, "ExprParser", "ExprLexer", "prog", "1\n", true); assertNull(stderrDuringParse); result = execParser("Expr.g4", grammar, "ExprParser", "ExprLexer", "prog", "a = 5\n", true); assertNull(stderrDuringParse); result = execParser("Expr.g4", grammar, "ExprParser", "ExprLexer", "prog", "b = 6\n", true); assertNull(stderrDuringParse); result = execParser("Expr.g4", grammar, "ExprParser", "ExprLexer", "prog", "a+b*2\n", true); assertEquals("line 1:1 reportAttemptingFullContext d=3, input='+'\n" + "line 1:1 reportContextSensitivity d=3, input='+'\n" + "line 1:3 reportAttemptingFullContext d=3, input='*'\n" + "line 1:3 reportAmbiguity d=3: ambigAlts={1..2}, input='*'\n", stderrDuringParse); result = execParser("Expr.g4", grammar, "ExprParser", "ExprLexer", "prog", "(1+2)*3\n", true); assertEquals("line 1:2 reportAttemptingFullContext d=3, input='+'\n" + "line 1:2 reportContextSensitivity d=3, input='+'\n" + "line 1:5 reportAttemptingFullContext d=3, input='*'\n" + "line 1:5 reportContextSensitivity d=3, input='*'\n", stderrDuringParse); } public void runTests(String grammar, String[] tests, String startRule) { rawGenerateAndBuildRecognizer("T.g", grammar, "TParser", "TLexer"); writeRecognizerAndCompile("TParser", "TLexer", startRule, debug); for (int i=0; i<tests.length; i+=2) { String test = tests[i]; String expecting = tests[i+1]+"\n"; writeFile(tmpdir, "input", test); String found = execRecognizer(); System.out.print(test+" -> "+found); assertEquals(expecting, found); } } }
tool/test/org/antlr/v4/test/TestLeftRecursion.java
package org.antlr.v4.test; import org.junit.Test; /** */ public class TestLeftRecursion extends BaseTest { protected boolean debug = false; @Test public void testSimple() throws Exception { String grammar = "grammar T;\n" + "s @after {System.out.println($ctx.toStringTree(this));} : a ;\n" + "a : a ID\n" + " | ID" + " ;\n" + "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "s", "x", debug); String expecting = "(s (a x))\n"; assertEquals(expecting, found); found = execParser("T.g", grammar, "TParser", "TLexer", "s", "x y", debug); expecting = "(s (a (a x) y))\n"; assertEquals(expecting, found); found = execParser("T.g", grammar, "TParser", "TLexer", "s", "x y z", debug); expecting = "(s (a (a (a x) y) z))\n"; assertEquals(expecting, found); } @Test public void testSemPred() throws Exception { String grammar = "grammar T;\n" + "s @after {System.out.println($ctx.toStringTree(this));} : a ;\n" + "a : a {true}? ID\n" + " | ID" + " ;\n" + "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "s", "x y z", debug); String expecting = "(s (a (a (a x) y) z))\n"; assertEquals(expecting, found); } @Test public void testTernaryExpr() throws Exception { String grammar = "grammar T;\n" + "s @after {System.out.println($ctx.toStringTree(this));} : e EOF ;\n" + // must indicate EOF can follow or 'a<EOF>' won't match "e : e '*' e" + " | e '+' e" + " | e '?'<assoc=right> e ':' e" + " | e '='<assoc=right> e" + " | ID" + " ;\n" + "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; String[] tests = { "a", "(s (e a) <EOF>)", "a+b", "(s (e (e a) + (e b)) <EOF>)", "a*b", "(s (e (e a) * (e b)) <EOF>)", "a?b:c", "(s (e (e a) ? (e b) : (e c)) <EOF>)", "a=b=c", "(s (e (e a) = (e (e b) = (e c))) <EOF>)", "a?b+c:d", "(s (e (e a) ? (e (e b) + (e c)) : (e d)) <EOF>)", "a?b=c:d", "(s (e (e a) ? (e (e b) = (e c)) : (e d)) <EOF>)", "a? b?c:d : e", "(s (e (e a) ? (e (e b) ? (e c) : (e d)) : (e e)) <EOF>)", "a?b: c?d:e", "(s (e (e a) ? (e b) : (e (e c) ? (e d) : (e e))) <EOF>)", }; runTests(grammar, tests, "s"); } @Test public void testExpressions() throws Exception { String grammar = "grammar T;\n" + "s @after {System.out.println($ctx.toStringTree(this));} : e EOF ;\n" + // must indicate EOF can follow "e : e '.' ID\n" + " | e '.' 'this'\n" + " | '-' e\n" + " | e '*' e\n" + " | e ('+'|'-') e\n" + " | INT\n" + " | ID\n" + " ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+ ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; String[] tests = { "a", "(s (e a) <EOF>)", "1", "(s (e 1) <EOF>)", "a-1", "(s (e (e a) - (e 1)) <EOF>)", "a.b", "(s (e (e a) . b) <EOF>)", "a.this", "(s (e (e a) . this) <EOF>)", "-a", "(s (e - (e a)) <EOF>)", "-a+b", "(s (e (e - (e a)) + (e b)) <EOF>)", }; runTests(grammar, tests, "s"); } @Test public void testJavaExpressions() throws Exception { // Generates about 7k in bytecodes for generated e_ rule; // Well within the 64k method limit. e_primary compiles // to about 2k in bytecodes. // this is simplified from real java String grammar = "grammar T;\n" + "s @after {System.out.println($ctx.toStringTree(this));} : e EOF ;\n" + // must indicate EOF can follow "expressionList\n" + " : e (',' e)*\n" + " ;\n" + "e : '(' e ')'\n" + " | 'this' \n" + " | 'super'\n" + " | INT\n" + " | ID\n" + " | type '.' 'class'\n" + " | e '.' ID\n" + " | e '.' 'this'\n" + " | e '.' 'super' '(' expressionList? ')'\n" + " | e '.' 'new' ID '(' expressionList? ')'\n" + " | 'new' type ( '(' expressionList? ')' | ('[' e ']')+)\n" + " | e '[' e ']'\n" + " | '(' type ')' e\n" + " | e ('++' | '--')\n" + " | e '(' expressionList? ')'\n" + " | ('+'|'-'|'++'|'--') e\n" + " | ('~'|'!') e\n" + " | e ('*'|'/'|'%') e\n" + " | e ('+'|'-') e\n" + " | e ('<<' | '>>>' | '>>') e\n" + " | e ('<=' | '>=' | '>' | '<') e\n" + " | e 'instanceof' e\n" + " | e ('==' | '!=') e\n" + " | e '&' e\n" + " | e '^'<assoc=right> e\n" + " | e '|' e\n" + " | e '&&' e\n" + " | e '||' e\n" + " | e '?' e ':' e\n" + " | e ('='<assoc=right>\n" + " |'+='<assoc=right>\n" + " |'-='<assoc=right>\n" + " |'*='<assoc=right>\n" + " |'/='<assoc=right>\n" + " |'&='<assoc=right>\n" + " |'|='<assoc=right>\n" + " |'^='<assoc=right>\n" + " |'>>='<assoc=right>\n" + " |'>>>='<assoc=right>\n" + " |'<<='<assoc=right>\n" + " |'%='<assoc=right>) e\n" + " ;\n" + "type: ID \n" + " | ID '[' ']'\n" + " | 'int'\n" + " | 'int' '[' ']' \n" + " ;\n" + "ID : ('a'..'z'|'A'..'Z'|'_'|'$')+;\n" + "INT : '0'..'9'+ ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; String[] tests = { "a|b&c", "(s (e (e a) | (e (e b) & (e c))) <EOF>)", "(a|b)&c", "(s (e (e ( (e (e a) | (e b)) )) & (e c)) <EOF>)", "a > b", "(s (e (e a) > (e b)) <EOF>)", "a >> b", "(s (e (e a) >> (e b)) <EOF>)", "(T)x", "(s (e ( (type T) ) (e x)) <EOF>)", "new A().b", "(s (e (e new (type A) ( )) . b) <EOF>)", "(T)t.f()", "(s (e (e ( (type T) ) (e (e t) . f)) ( )) <EOF>)", "a.f(x)==T.c", "(s (e (e (e (e a) . f) ( (expressionList (e x)) )) == (e (e T) . c)) <EOF>)", "a.f().g(x,1)", "(s (e (e (e (e (e a) . f) ( )) . g) ( (expressionList (e x) , (e 1)) )) <EOF>)", "new T[((n-1) * x) + 1]", "(s (e new (type T) [ (e (e ( (e (e ( (e (e n) - (e 1)) )) * (e x)) )) + (e 1)) ]) <EOF>)", }; runTests(grammar, tests, "s"); } @Test public void testDeclarations() throws Exception { String grammar = "grammar T;\n" + "s @after {System.out.println($ctx.toStringTree(this));} : declarator EOF ;\n" + // must indicate EOF can follow "declarator\n" + " : declarator '[' e ']'\n" + " | declarator '[' ']'\n" + " | declarator '(' ')'\n" + " | '*' declarator\n" + // binds less tight than suffixes " | '(' declarator ')'\n" + " | ID\n" + " ;\n" + "e : INT ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+ ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; String[] tests = { "a", "(s (declarator a) <EOF>)", "*a", "(s (declarator * (declarator a)) <EOF>)", "**a", "(s (declarator * (declarator * (declarator a))) <EOF>)", "a[3]", "(s (declarator (declarator a) [ (e 3) ]) <EOF>)", "b[]", "(s (declarator (declarator b) [ ]) <EOF>)", "(a)", "(s (declarator ( (declarator a) )) <EOF>)", "a[]()", "(s (declarator (declarator (declarator a) [ ]) ( )) <EOF>)", "a[][]", "(s (declarator (declarator (declarator a) [ ]) [ ]) <EOF>)", "*a[]", "(s (declarator * (declarator (declarator a) [ ])) <EOF>)", "(*a)[]", "(s (declarator (declarator ( (declarator * (declarator a)) )) [ ]) <EOF>)", }; runTests(grammar, tests, "s"); } @Test public void testReturnValueAndActions() throws Exception { String grammar = "grammar T;\n" + "s : e {System.out.println($e.v);} ;\n" + "e returns [int v, List<String> ignored]\n" + " : a=e '*' b=e {$v = $a.v * $b.v;}\n" + " | a=e '+' b=e {$v = $a.v + $b.v;}\n" + " | INT {$v = $INT.int;}\n" + " | '(' x=e ')' {$v = $x.v;}\n" + " ;\n" + "INT : '0'..'9'+ ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; String[] tests = { "4", "4", "1+2", "3", "1+2*3", "7", "(1+2)*3", "9", }; runTests(grammar, tests, "s"); } @Test public void testReturnValueAndActionsAndLabels() throws Exception { String grammar = "grammar T;\n" + "s : q=e {System.out.println($e.v);} ;\n" + "\n" + "e returns [int v]\n" + " : a=e op='*' b=e {$v = $a.v * $b.v;} -> mult\n" + " | a=e '+' b=e {$v = $a.v + $b.v;} -> add\n" + " | INT {$v = $INT.int;} -> anInt\n" + " | '(' x=e ')' {$v = $x.v;} -> parens\n" + " | x=e '++' {$v = $x.v+1;} -> inc\n" + " | e '--' -> dec\n" + " | ID {$v = 3;} -> anID\n" + " ; \n" + "\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+ ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; String[] tests = { "4", "4", "1+2", "3", "1+2*3", "7", "i++*3", "12", }; runTests(grammar, tests, "s"); } @Test public void testPrefixOpWithActionAndLabel() throws Exception { String grammar = "grammar T;\n" + "s : e {System.out.println($e.result);} ;\n" + "\n" + "e returns [String result]\n" + " : ID '=' e1=e { $result = \"(\" + $ID.getText() + \"=\" + $e1.result + \")\"; }\n" + " | ID { $result = $ID.getText(); }\n" + " | e1=e '+' e2=e { $result = \"(\" + $e1.result + \"+\" + $e2.result + \")\"; }\n" + " ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+ ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; String[] tests = { "a", "a", "a+b", "(a+b)", "a=b+c", "((a=b)+c)", }; runTests(grammar, tests, "s"); } @Test public void testAmbigLR() throws Exception { String grammar = "// START: g\n" + "grammar Expr;\n" + "// END: g\n" + "\n" + "// START:stat\n" + "prog: stat ;\n" + "\n" + "stat: expr NEWLINE -> printExpr\n" + " | ID '=' expr NEWLINE -> assign\n" + " | NEWLINE -> blank\n" + " ;\n" + "// END:stat\n" + "\n" + "// START:expr\n" + "expr: expr ('*'|'/') expr -> MulDiv\n" + " | expr ('+'|'-') expr -> AddSub\n" + " | INT -> int\n" + " | ID -> id\n" + " | '(' expr ')' -> parens\n" + " ;\n" + "// END:expr\n" + "\n" + "// show marginal cost of adding a clear/wipe command for memory\n" + "\n" + "// START:tokens\n" + "MUL : '*' ; // assigns token name to '*' used above in grammar\n" + "DIV : '/' ;\n" + "ADD : '+' ;\n" + "SUB : '-' ;\n" + "ID : [a-zA-Z]+ ; // match identifiers\n" + "INT : [0-9]+ ; // match integers\n" + "NEWLINE:'\\r'? '\\n' ; // return newlines to parser (is end-statement signal)\n" + "WS : [ \\t]+ -> skip ; // toss out whitespace\n" + "// END:tokens\n"; String result = execParser("Expr.g4", grammar, "ExprParser", "ExprLexer", "prog", "1\n", true); assertNull(stderrDuringParse); result = execParser("Expr.g4", grammar, "ExprParser", "ExprLexer", "prog", "a = 5\n", true); assertNull(stderrDuringParse); result = execParser("Expr.g4", grammar, "ExprParser", "ExprLexer", "prog", "b = 6\n", true); assertNull(stderrDuringParse); result = execParser("Expr.g4", grammar, "ExprParser", "ExprLexer", "prog", "a+b*2\n", true); assertNull(stderrDuringParse); result = execParser("Expr.g4", grammar, "ExprParser", "ExprLexer", "prog", "(1+2)*3\n", true); assertNull(stderrDuringParse); } public void runTests(String grammar, String[] tests, String startRule) { rawGenerateAndBuildRecognizer("T.g", grammar, "TParser", "TLexer"); writeRecognizerAndCompile("TParser", "TLexer", startRule, debug); for (int i=0; i<tests.length; i+=2) { String test = tests[i]; String expecting = tests[i+1]+"\n"; writeFile(tmpdir, "input", test); String found = execRecognizer(); System.out.print(test+" -> "+found); assertEquals(expecting, found); } } }
Fix expected output for testAmbigLR
tool/test/org/antlr/v4/test/TestLeftRecursion.java
Fix expected output for testAmbigLR
Java
bsd-3-clause
8565d3ebaba7b52297ca1d6955a18dbeec12a79f
0
fujunwei/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,M4sse/chromium.src,markYoungH/chromium.src,ondra-novak/chromium.src,jaruba/chromium.src,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,chuan9/chromium-crosswalk,ondra-novak/chromium.src,ltilve/chromium,jaruba/chromium.src,hgl888/chromium-crosswalk,bright-sparks/chromium-spacewalk,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,dushu1203/chromium.src,chuan9/chromium-crosswalk,littlstar/chromium.src,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,dushu1203/chromium.src,markYoungH/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,ltilve/chromium,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,littlstar/chromium.src,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,markYoungH/chromium.src,fujunwei/chromium-crosswalk,dednal/chromium.src,Chilledheart/chromium,ltilve/chromium,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,markYoungH/chromium.src,ltilve/chromium,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,jaruba/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,Chilledheart/chromium,M4sse/chromium.src,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,M4sse/chromium.src,Fireblend/chromium-crosswalk,dushu1203/chromium.src,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,M4sse/chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,M4sse/chromium.src,dednal/chromium.src,dednal/chromium.src,fujunwei/chromium-crosswalk,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,ltilve/chromium,chuan9/chromium-crosswalk,dushu1203/chromium.src,M4sse/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,Just-D/chromium-1,Jonekee/chromium.src,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,dednal/chromium.src,fujunwei/chromium-crosswalk,littlstar/chromium.src,bright-sparks/chromium-spacewalk,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,ltilve/chromium,Just-D/chromium-1,fujunwei/chromium-crosswalk,Chilledheart/chromium,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,Chilledheart/chromium,ltilve/chromium,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,Jonekee/chromium.src,littlstar/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,M4sse/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk,Jonekee/chromium.src,Chilledheart/chromium,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,M4sse/chromium.src,Just-D/chromium-1,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,dushu1203/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,dednal/chromium.src,jaruba/chromium.src,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,Just-D/chromium-1,markYoungH/chromium.src,Fireblend/chromium-crosswalk,jaruba/chromium.src,axinging/chromium-crosswalk,Just-D/chromium-1,markYoungH/chromium.src,M4sse/chromium.src,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,dushu1203/chromium.src,Fireblend/chromium-crosswalk,ltilve/chromium,dednal/chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,littlstar/chromium.src,Just-D/chromium-1,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,ondra-novak/chromium.src,chuan9/chromium-crosswalk
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.share; import android.app.Activity; import android.app.AlertDialog; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.preference.PreferenceManager; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import org.chromium.chrome.R; import java.util.Collections; import java.util.List; /** * A helper class that helps to start an intent to share titles and URLs. */ public class ShareHelper { private static final String PACKAGE_NAME_KEY = "last_shared_package_name"; private static final String CLASS_NAME_KEY = "last_shared_class_name"; /** * Intent extra for sharing screenshots via the Share intent. * * Copied from {@link android.provider.Browser} as it is marked as {@literal @hide}. */ private static final String EXTRA_SHARE_SCREENSHOT = "share_screenshot"; private ShareHelper() {} /** * Creates and shows a share intent picker dialog or starts a share intent directly with the * activity that was most recently used to share based on shareDirectly value. * * @param shareDirectly Whether it should share directly with the activity that was most * recently used to share. * @param activity Activity that is used to access package manager. * @param title Title of the page to be shared. * @param url URL of the page to be shared. * @param screenshot Screenshot of the page to be shared. */ public static void share(boolean shareDirectly, Activity activity, String title, String url, Bitmap screenshot) { if (shareDirectly) { shareWithLastUsed(activity, title, url, screenshot); } else { showShareDialog(activity, title, url, screenshot); } } /** * Creates and shows a share intent picker dialog. * * @param activity Activity that is used to access package manager. * @param title Title of the page to be shared. * @param url URL of the page to be shared. * @param screenshot Screenshot of the page to be shared. */ private static void showShareDialog(final Activity activity, final String title, final String url, final Bitmap screenshot) { Intent intent = getShareIntent(title, url, screenshot); PackageManager manager = activity.getPackageManager(); List<ResolveInfo> resolveInfoList = manager.queryIntentActivities(intent, 0); assert resolveInfoList.size() > 0; if (resolveInfoList.size() == 0) return; Collections.sort(resolveInfoList, new ResolveInfo.DisplayNameComparator(manager)); final ShareDialogAdapter adapter = new ShareDialogAdapter(activity, manager, resolveInfoList); AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(activity.getString(R.string.share_link_chooser_title)); builder.setAdapter(adapter, null); final AlertDialog dialog = builder.create(); dialog.show(); dialog.getListView().setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ResolveInfo info = adapter.getItem(position); ActivityInfo ai = info.activityInfo; ComponentName component = new ComponentName(ai.applicationInfo.packageName, ai.name); setLastShareComponentName(activity, component); Intent intent = getDirectShareIntentForComponent(title, url, screenshot, component); activity.startActivity(intent); dialog.dismiss(); } }); } /** * Starts a share intent with the activity that was most recently used to share. * If there is no most recently used activity, it does nothing. * @param activity Activity that is used to start the share intent. * @param title Title of the page to be shared. * @param url URL of the page to be shared. * @param screenshot Screenshot of the page to be shared. */ private static void shareWithLastUsed( Activity activity, String title, String url, Bitmap screenshot) { ComponentName component = getLastShareComponentName(activity); if (component == null) return; Intent intent = getDirectShareIntentForComponent(title, url, screenshot, component); activity.startActivity(intent); } /** * Set the icon and the title for the menu item used for direct share. * * @param activity Activity that is used to access the package manager. * @param item The menu item that is used for direct share */ public static void configureDirectShareMenuItem(Activity activity, MenuItem item) { Drawable directShareIcon = null; CharSequence directShareTitle = null; ComponentName component = getLastShareComponentName(activity); if (component != null) { try { directShareIcon = activity.getPackageManager().getActivityIcon(component); ApplicationInfo ai = activity.getPackageManager().getApplicationInfo( component.getPackageName(), 0); directShareTitle = activity.getPackageManager().getApplicationLabel(ai); } catch (NameNotFoundException exception) { // Use the default null values. } } item.setIcon(directShareIcon); if (directShareTitle != null) { item.setTitle(activity.getString(R.string.accessibility_menu_share_via, directShareTitle)); } } private static Intent getShareIntent(String title, String url, Bitmap screenshot) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_SUBJECT, title); intent.putExtra(Intent.EXTRA_TEXT, url); if (screenshot != null) intent.putExtra(EXTRA_SHARE_SCREENSHOT, screenshot); return intent; } private static Intent getDirectShareIntentForComponent(String title, String url, Bitmap screenshot, ComponentName component) { Intent intent = getShareIntent(title, url, screenshot); intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT | Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP); intent.setComponent(component); return intent; } private static ComponentName getLastShareComponentName(Context context) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); String packageName = preferences.getString(PACKAGE_NAME_KEY, null); String className = preferences.getString(CLASS_NAME_KEY, null); if (packageName == null || className == null) return null; return new ComponentName(packageName, className); } private static void setLastShareComponentName(Context context, ComponentName component) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = preferences.edit(); editor.putString(PACKAGE_NAME_KEY, component.getPackageName()); editor.putString(CLASS_NAME_KEY, component.getClassName()); editor.apply(); } }
chrome/android/java/src/org/chromium/chrome/browser/share/ShareHelper.java
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.share; import android.app.Activity; import android.app.AlertDialog; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.preference.PreferenceManager; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import org.chromium.chrome.R; import java.util.List; /** * A helper class that helps to start an intent to share titles and URLs. */ public class ShareHelper { private static final String PACKAGE_NAME_KEY = "last_shared_package_name"; private static final String CLASS_NAME_KEY = "last_shared_class_name"; /** * Intent extra for sharing screenshots via the Share intent. * * Copied from {@link android.provider.Browser} as it is marked as {@literal @hide}. */ private static final String EXTRA_SHARE_SCREENSHOT = "share_screenshot"; private ShareHelper() {} /** * Creates and shows a share intent picker dialog or starts a share intent directly with the * activity that was most recently used to share based on shareDirectly value. * * @param shareDirectly Whether it should share directly with the activity that was most * recently used to share. * @param activity Activity that is used to access package manager. * @param title Title of the page to be shared. * @param url URL of the page to be shared. * @param screenshot Screenshot of the page to be shared. */ public static void share(boolean shareDirectly, Activity activity, String title, String url, Bitmap screenshot) { if (shareDirectly) { shareWithLastUsed(activity, title, url, screenshot); } else { showShareDialog(activity, title, url, screenshot); } } /** * Creates and shows a share intent picker dialog. * * @param activity Activity that is used to access package manager. * @param title Title of the page to be shared. * @param url URL of the page to be shared. * @param screenshot Screenshot of the page to be shared. */ private static void showShareDialog(final Activity activity, final String title, final String url, final Bitmap screenshot) { Intent intent = getShareIntent(title, url, screenshot); PackageManager manager = activity.getPackageManager(); List<ResolveInfo> resolveInfoList = manager.queryIntentActivities(intent, 0); assert resolveInfoList.size() > 0; if (resolveInfoList.size() == 0) return; final ShareDialogAdapter adapter = new ShareDialogAdapter(activity, manager, resolveInfoList); AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(activity.getString(R.string.share_link_chooser_title)); builder.setAdapter(adapter, null); final AlertDialog dialog = builder.create(); dialog.show(); dialog.getListView().setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ResolveInfo info = adapter.getItem(position); ActivityInfo ai = info.activityInfo; ComponentName component = new ComponentName(ai.applicationInfo.packageName, ai.name); setLastShareComponentName(activity, component); Intent intent = getDirectShareIntentForComponent(title, url, screenshot, component); activity.startActivity(intent); dialog.dismiss(); } }); } /** * Starts a share intent with the activity that was most recently used to share. * If there is no most recently used activity, it does nothing. * @param activity Activity that is used to start the share intent. * @param title Title of the page to be shared. * @param url URL of the page to be shared. * @param screenshot Screenshot of the page to be shared. */ private static void shareWithLastUsed( Activity activity, String title, String url, Bitmap screenshot) { ComponentName component = getLastShareComponentName(activity); if (component == null) return; Intent intent = getDirectShareIntentForComponent(title, url, screenshot, component); activity.startActivity(intent); } /** * Set the icon and the title for the menu item used for direct share. * * @param activity Activity that is used to access the package manager. * @param item The menu item that is used for direct share */ public static void configureDirectShareMenuItem(Activity activity, MenuItem item) { Drawable directShareIcon = null; CharSequence directShareTitle = null; ComponentName component = getLastShareComponentName(activity); if (component != null) { try { directShareIcon = activity.getPackageManager().getActivityIcon(component); ApplicationInfo ai = activity.getPackageManager().getApplicationInfo( component.getPackageName(), 0); directShareTitle = activity.getPackageManager().getApplicationLabel(ai); } catch (NameNotFoundException exception) { // Use the default null values. } } item.setIcon(directShareIcon); if (directShareTitle != null) { item.setTitle(activity.getString(R.string.accessibility_menu_share_via, directShareTitle)); } } private static Intent getShareIntent(String title, String url, Bitmap screenshot) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_SUBJECT, title); intent.putExtra(Intent.EXTRA_TEXT, url); if (screenshot != null) intent.putExtra(EXTRA_SHARE_SCREENSHOT, screenshot); return intent; } private static Intent getDirectShareIntentForComponent(String title, String url, Bitmap screenshot, ComponentName component) { Intent intent = getShareIntent(title, url, screenshot); intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT | Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP); intent.setComponent(component); return intent; } private static ComponentName getLastShareComponentName(Context context) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); String packageName = preferences.getString(PACKAGE_NAME_KEY, null); String className = preferences.getString(CLASS_NAME_KEY, null); if (packageName == null || className == null) return null; return new ComponentName(packageName, className); } private static void setLastShareComponentName(Context context, ComponentName component) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = preferences.edit(); editor.putString(PACKAGE_NAME_KEY, component.getPackageName()); editor.putString(CLASS_NAME_KEY, component.getClassName()); editor.apply(); } }
Sort share intents alphabetically. Sort the intents alphabetically to match Android stock intent chooser. BUG=333023 Review URL: https://codereview.chromium.org/220443002 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@260903 0039d316-1c4b-4281-b951-d872f2087c98
chrome/android/java/src/org/chromium/chrome/browser/share/ShareHelper.java
Sort share intents alphabetically.
Java
bsd-3-clause
7d4fa24d85c705e0a86da5d55b6e80abca1bb025
0
dushu1203/chromium.src,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,dednal/chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,Just-D/chromium-1,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,ondra-novak/chromium.src,chuan9/chromium-crosswalk,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk,mogoweb/chromium-crosswalk,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,M4sse/chromium.src,axinging/chromium-crosswalk,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,Just-D/chromium-1,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,ChromiumWebApps/chromium,patrickm/chromium.src,Fireblend/chromium-crosswalk,dednal/chromium.src,dushu1203/chromium.src,littlstar/chromium.src,littlstar/chromium.src,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,Just-D/chromium-1,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,anirudhSK/chromium,fujunwei/chromium-crosswalk,Jonekee/chromium.src,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,dednal/chromium.src,dushu1203/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,markYoungH/chromium.src,jaruba/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,ltilve/chromium,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,anirudhSK/chromium,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,ltilve/chromium,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,anirudhSK/chromium,dednal/chromium.src,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,dednal/chromium.src,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,ondra-novak/chromium.src,chuan9/chromium-crosswalk,littlstar/chromium.src,fujunwei/chromium-crosswalk,dushu1203/chromium.src,jaruba/chromium.src,M4sse/chromium.src,ondra-novak/chromium.src,anirudhSK/chromium,anirudhSK/chromium,krieger-od/nwjs_chromium.src,M4sse/chromium.src,M4sse/chromium.src,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,dushu1203/chromium.src,jaruba/chromium.src,markYoungH/chromium.src,Chilledheart/chromium,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,dednal/chromium.src,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,markYoungH/chromium.src,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,Just-D/chromium-1,ltilve/chromium,littlstar/chromium.src,bright-sparks/chromium-spacewalk,anirudhSK/chromium,Just-D/chromium-1,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,littlstar/chromium.src,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,ltilve/chromium,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,bright-sparks/chromium-spacewalk,patrickm/chromium.src,Jonekee/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,anirudhSK/chromium,Chilledheart/chromium,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,ltilve/chromium,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,jaruba/chromium.src,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,Chilledheart/chromium,patrickm/chromium.src,jaruba/chromium.src,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,dushu1203/chromium.src,dednal/chromium.src,mogoweb/chromium-crosswalk,ltilve/chromium,dednal/chromium.src,ltilve/chromium,ChromiumWebApps/chromium,Chilledheart/chromium,Chilledheart/chromium,jaruba/chromium.src,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,Just-D/chromium-1,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,ltilve/chromium,mogoweb/chromium-crosswalk,dednal/chromium.src,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,Chilledheart/chromium,jaruba/chromium.src,krieger-od/nwjs_chromium.src,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,Jonekee/chromium.src,fujunwei/chromium-crosswalk,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,chuan9/chromium-crosswalk,patrickm/chromium.src,ondra-novak/chromium.src,dushu1203/chromium.src,dushu1203/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,dushu1203/chromium.src
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.content.browser; import android.content.Context; import android.content.pm.PackageManager; import android.media.MediaMetadataRetriever; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import org.chromium.base.CalledByNative; import org.chromium.base.JNINamespace; import org.chromium.base.PathUtils; import java.io.File; import java.util.HashMap; /** * Java counterpart of android MediaResourceGetter. */ @JNINamespace("content") class MediaResourceGetter { private static final String TAG = "MediaResourceGetter"; private static class MediaMetadata { private final int mDurationInMilliseconds; private final int mWidth; private final int mHeight; private final boolean mSuccess; private MediaMetadata(int durationInMilliseconds, int width, int height, boolean success) { mDurationInMilliseconds = durationInMilliseconds; mWidth = width; mHeight = height; mSuccess = success; } @CalledByNative("MediaMetadata") private int getDurationInMilliseconds() { return mDurationInMilliseconds; } @CalledByNative("MediaMetadata") private int getWidth() { return mWidth; } @CalledByNative("MediaMetadata") private int getHeight() { return mHeight; } @CalledByNative("MediaMetadata") private boolean isSuccess() { return mSuccess; } } @CalledByNative private static MediaMetadata extractMediaMetadata(Context context, String url, String cookies) { int durationInMilliseconds = 0; int width = 0; int height = 0; boolean success = false; // TODO(qinmin): use ConnectionTypeObserver to listen to the network type change. ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (mConnectivityManager != null) { if (context.checkCallingOrSelfPermission( android.Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED) { return new MediaMetadata(0, 0, 0, false); } NetworkInfo info = mConnectivityManager.getActiveNetworkInfo(); if (info == null) { return new MediaMetadata(durationInMilliseconds, width, height, success); } switch (info.getType()) { case ConnectivityManager.TYPE_ETHERNET: case ConnectivityManager.TYPE_WIFI: break; case ConnectivityManager.TYPE_WIMAX: case ConnectivityManager.TYPE_MOBILE: default: return new MediaMetadata(durationInMilliseconds, width, height, success); } } MediaMetadataRetriever retriever = new MediaMetadataRetriever(); try { Uri uri = Uri.parse(url); String scheme = uri.getScheme(); if (scheme == null || scheme.equals("file")) { File file = new File(uri.getPath()); String path = file.getAbsolutePath(); if (file.exists() && (path.startsWith("/mnt/sdcard/") || path.startsWith("/sdcard/") || path.startsWith(PathUtils.getExternalStorageDirectory()))) { retriever.setDataSource(path); } else { Log.e(TAG, "Unable to read file: " + url); return new MediaMetadata(durationInMilliseconds, width, height, success); } } else { HashMap<String, String> headersMap = new HashMap<String, String>(); if (!TextUtils.isEmpty(cookies)) { headersMap.put("Cookie", cookies); } retriever.setDataSource(url, headersMap); } durationInMilliseconds = Integer.parseInt( retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)); width = Integer.parseInt( retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)); height = Integer.parseInt( retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)); success = true; } catch (IllegalArgumentException e) { Log.e(TAG, "Invalid url: " + e); } catch (RuntimeException e) { Log.e(TAG, "Invalid url: " + e); } return new MediaMetadata(durationInMilliseconds, width, height, success); } }
content/public/android/java/src/org/chromium/content/browser/MediaResourceGetter.java
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.content.browser; import android.content.Context; import android.media.MediaMetadataRetriever; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import org.chromium.base.CalledByNative; import org.chromium.base.JNINamespace; import org.chromium.base.PathUtils; import java.io.File; import java.util.HashMap; /** * Java counterpart of android MediaResourceGetter. */ @JNINamespace("content") class MediaResourceGetter { private static final String TAG = "MediaResourceGetter"; private static class MediaMetadata { private final int mDurationInMilliseconds; private final int mWidth; private final int mHeight; private final boolean mSuccess; private MediaMetadata(int durationInMilliseconds, int width, int height, boolean success) { mDurationInMilliseconds = durationInMilliseconds; mWidth = width; mHeight = height; mSuccess = success; } @CalledByNative("MediaMetadata") private int getDurationInMilliseconds() { return mDurationInMilliseconds; } @CalledByNative("MediaMetadata") private int getWidth() { return mWidth; } @CalledByNative("MediaMetadata") private int getHeight() { return mHeight; } @CalledByNative("MediaMetadata") private boolean isSuccess() { return mSuccess; } } @CalledByNative private static MediaMetadata extractMediaMetadata(Context context, String url, String cookies) { int durationInMilliseconds = 0; int width = 0; int height = 0; boolean success = false; // TODO(qinmin): use ConnectionTypeObserver to listen to the network type change. ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (mConnectivityManager != null) { NetworkInfo info = mConnectivityManager.getActiveNetworkInfo(); if (info == null) { return new MediaMetadata(durationInMilliseconds, width, height, success); } switch (info.getType()) { case ConnectivityManager.TYPE_ETHERNET: case ConnectivityManager.TYPE_WIFI: break; case ConnectivityManager.TYPE_WIMAX: case ConnectivityManager.TYPE_MOBILE: default: return new MediaMetadata(durationInMilliseconds, width, height, success); } } MediaMetadataRetriever retriever = new MediaMetadataRetriever(); try { Uri uri = Uri.parse(url); String scheme = uri.getScheme(); if (scheme == null || scheme.equals("file")) { File file = new File(uri.getPath()); String path = file.getAbsolutePath(); if (file.exists() && (path.startsWith("/mnt/sdcard/") || path.startsWith("/sdcard/") || path.startsWith(PathUtils.getExternalStorageDirectory()))) { retriever.setDataSource(path); } else { Log.e(TAG, "Unable to read file: " + url); return new MediaMetadata(durationInMilliseconds, width, height, success); } } else { HashMap<String, String> headersMap = new HashMap<String, String>(); if (!TextUtils.isEmpty(cookies)) { headersMap.put("Cookie", cookies); } retriever.setDataSource(url, headersMap); } durationInMilliseconds = Integer.parseInt( retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)); width = Integer.parseInt( retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)); height = Integer.parseInt( retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)); success = true; } catch (IllegalArgumentException e) { Log.e(TAG, "Invalid url: " + e); } catch (RuntimeException e) { Log.e(TAG, "Invalid url: " + e); } return new MediaMetadata(durationInMilliseconds, width, height, success); } }
[Android] Check embedding app permissions in MediaResourceGetter. The Android ConnectivityManager.getActiveNetworkInfo() API requires the ACCESS_NETWORK_STATE permission. BUG=276935 Review URL: https://chromiumcodereview.appspot.com/22929024 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@218897 0039d316-1c4b-4281-b951-d872f2087c98
content/public/android/java/src/org/chromium/content/browser/MediaResourceGetter.java
[Android] Check embedding app permissions in MediaResourceGetter.
Java
bsd-3-clause
error: pathspec 'datasource-rdfizer/src/main/java/edu/ucdenver/ccp/datasource/rdfizer/rdf/ice/RdfRecordWriterImpl.java' did not match any file(s) known to git
e19a6130961fb55b308cc506c3eecadfa64237dd
1
UCDenver-ccp/datasource,UCDenver-ccp/datasource,bill-baumgartner/datasource,bill-baumgartner/datasource
package edu.ucdenver.ccp.rdfizer.rdf; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Set; import java.util.zip.GZIPOutputStream; import org.apache.log4j.Logger; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.Value; import org.openrdf.model.impl.URIImpl; import org.openrdf.rio.RDFHandlerException; import org.openrdf.rio.RDFWriter; import edu.ucdenver.ccp.common.collections.CollectionsUtil; import edu.ucdenver.ccp.common.file.CharacterEncoding; import edu.ucdenver.ccp.common.file.FileUtil; import edu.ucdenver.ccp.common.reflection.PrivateAccessor; import edu.ucdenver.ccp.common.string.StringConstants; import edu.ucdenver.ccp.datasource.fileparsers.DataRecord; import edu.ucdenver.ccp.datasource.fileparsers.RecordReader; import edu.ucdenver.ccp.datasource.fileparsers.RecordUtil; import edu.ucdenver.ccp.datasource.identifiers.DataSourceElement; import edu.ucdenver.ccp.datasource.identifiers.DataSourceIdentifier; import edu.ucdenver.ccp.rdfizer.rdf.RdfUtil.RdfFormat; import edu.ucdenver.ccp.rdfizer.rdf.filter.DuplicateStatementFilter; import edu.ucdenver.ccp.rdfizer.util.InMemoryDuplicateStatementFilter; /** * RDF generator that handles data provided by {@link RecordReader} instances in combination with * reader-specific config files (XML). * * @param <T> * reader type */ public class RdfRecordWriterImpl<T extends RecordReader<?>> { /** * logger */ private static final Logger logger = Logger.getLogger(RdfRecordWriterImpl.class); /** output directory */ private final File outputDirectory; /** file key (specified in config parser config files) to writer map */ private Map<File, RdfWriterResource> file2RdfWriterMap; /** * Part of output file name driven by reader. * <p> * This is useful in places where the same reader class is used to read several files (ex: * multiple species). */ private String readerKey = StringConstants.BLANK; private long createdTime; /** indicator for whether to compress serialized rdf files */ private boolean compress; /** maximum number of statements per output file ; -1 or 0 for unlimited - default */ private long maxStatementsPerFile = -1; /** * tracks the number of statements written to file. This count is used to split files when the * {@link #maxStatementsPerFile} variable is set to a number > 0 */ private long writtenStatementCount; /** * this number will be appended to the output file name to allow multiple stages to process a * single file but output the RDF into distinct files. */ private final int batchNumber; /** * The RDF format to use when writing out RDF */ private final RdfFormat rdfFormat; /** * The default output encoding is UTF-8. This can be changed using the * {@link #setEncoding(CharacterEncoding)} method. */ private CharacterEncoding encoding = CharacterEncoding.UTF_8; /** * A reference to the {@link RecordReader} being processed is stored b/c it is used during the * output file name creation process. See {@link #getOutputFileName()} */ private RecordReader<?> recordReader = null; /** * Stores references to all RDF files generated during processing of a {@link RecordReader} */ private Collection<File> generatedRdfFiles = new ArrayList<File>(); private final DuplicateStatementFilter filter; private final Set<String> rollingCacheSet = new HashSet<String>(); private final LinkedList<String> rollingCacheList = new LinkedList<String>(); private Set<String> primaryKeyFieldNames = null; private static final int ROLLING_CACHE_MAX_SIZE = 1000; /** * @param outputDirectory * @param rdfFormat * @throws FileNotFoundException */ public RdfRecordWriterImpl(File outputDirectory, RdfFormat rdfFormat) throws FileNotFoundException { this(outputDirectory, rdfFormat, 0, new InMemoryDuplicateStatementFilter()); } /** * @param outputDirectory * @param rdfFormat * @param batchNumber * @throws FileNotFoundException */ public RdfRecordWriterImpl(File outputDirectory, RdfFormat rdfFormat, int batchNumber, DuplicateStatementFilter filter) throws FileNotFoundException { this.batchNumber = batchNumber; this.outputDirectory = outputDirectory; this.rdfFormat = rdfFormat; this.filter = filter; if (!this.outputDirectory.exists() && !this.outputDirectory.mkdirs()) { throw new RuntimeException(String.format("Output directory %s does not exist and cannot be created", outputDirectory)); } file2RdfWriterMap = new HashMap<File, RdfWriterResource>(); writtenStatementCount = 0; generatedRdfFiles = new ArrayList<File>(); } /** * * @param outputDirectory * rdf output directory * @param rdfFormat * @param compress * whether to compress (gz) files or not * @param maxStatementsPerFile * maximum number of statements per output file ; -1 for unlimited * @param batchNumber * @throws FileNotFoundException */ public RdfRecordWriterImpl(File outputDirectory, RdfFormat rdfFormat, boolean compress, long maxStatementsPerFile, int batchNumber, DuplicateStatementFilter filter) throws FileNotFoundException { this(outputDirectory, rdfFormat, batchNumber, filter); this.compress = compress; this.maxStatementsPerFile = maxStatementsPerFile > 0 ? maxStatementsPerFile : -1; } /** * @param outputDirectory * @param rdfFormat * @param compress * @throws FileNotFoundException */ public RdfRecordWriterImpl(File outputDirectory, RdfFormat rdfFormat, boolean compress) throws FileNotFoundException { this(outputDirectory, rdfFormat, compress, -1, 0, new InMemoryDuplicateStatementFilter()); } /** * Process file data by converting each item to RDF format and writing it out to an RDF file. * * @param <E> * * @param recordReader * reader * @param rdfSource * rdf source * @throws IOException */ public <E extends DataRecord> void processRecordReader(RecordReader<E> recordReader, long createdTime) throws IOException { // -1 for the outputRecordLimit signifies that all records should be output processRecordReader(recordReader, createdTime, 0, -1); } /** * Process file data by converting each item to RDF format and writing it out to an RDF file. * * @param dataRecordIterator * @param dataSpecificFileSuffix * @param outputRecordLimit * @return * @throws IOException */ private <E extends DataRecord> Collection<File> processRecordReader(RecordReader<E> dataRecordIterator, String dataSpecificFileSuffix, long createdTime, long outputRecordLimit) throws IOException { setReaderKey(dataSpecificFileSuffix); return processRecordReader(dataRecordIterator, createdTime, 0, outputRecordLimit); } /** * Process file data by converting each item to RDF format and writing it out to an RDF file. * * @param <E> * * @param recordReader * reader * @param rdfSource * data source * @param recordSkipCount * the number of records to skip before processing * @param outputRecordLimit * max records to process; -1 for all * @return a collection of references to all generated RDF files * @throws IOException */ public <E extends DataRecord> Collection<File> processRecordReader(RecordReader<E> recordReader, long createdTime, long recordSkipCount, long outputRecordLimit) throws IOException { this.recordReader = recordReader; setCreatedTime(createdTime); setReaderKey(recordReader.getDataSpecificKey()); long instanceCount = 0; /* skip the recordSkipCount */ while (recordReader.hasNext() && instanceCount < recordSkipCount) { DataRecord record = recordReader.next(); if (record != null) { if (instanceCount % 100000 == 0) { logger.info("SKIP PROGRESS: " + instanceCount); } instanceCount++; } } while (recordReader.hasNext()) { DataRecord record = recordReader.next(); if (record != null) { if ((instanceCount - recordSkipCount) % 100000 == 0) { logger.info("RDF GENERATION PROGRESS: " + (instanceCount - recordSkipCount)); // alreadyObservedFieldUris = cullObservedFieldUris(alreadyObservedFieldUris, // (instanceCount - recordSkipCount)); } instanceCount++; if (instanceCount == 1) { primaryKeyFieldNames = RecordUtil.getKeyFieldNames(record.getClass()); writeDataSourceInstanceStatements( RdfRecordUtil.getDataSourceInstanceStatements(record, createdTime), RdfNamespace.getNamespace(RecordUtil.getRecordDataSource(record.getClass()))); writeSchemaDefinitionRdfFile(record.getClass()); } URIImpl recordUri = RdfRecordUriFactory.createRecordUri(record); processRecord(record, recordReader.getDataSpecificKey(), recordUri); } /* * if the outputRecordLimit is > -1 then cap the number or records that are output to * file */ if (outputRecordLimit > -1 && instanceCount >= (outputRecordLimit + recordSkipCount)) { break; } } closeFiles(); filter.shutdown(); logger.info("DUPLICATE TRIPLE FILTER WAS LEAK-PROOF = " + filter.isLeakProof()); return generatedRdfFiles; } /** * @param recordClass * @return a reference to the schema definition RDF file */ private void writeSchemaDefinitionRdfFile(Class<? extends DataRecord> recordClass) { String schemaDefinitionFileName = recordClass.getSimpleName() + ".schema." + rdfFormat.defaultFileExtension(); File schemaDefinitionRdfFile = new File(outputDirectory, schemaDefinitionFileName); Collection<? extends Statement> stmts = RdfRecordUtil.getRecordSchemaStatements(recordClass, null, null, false); RDFWriter rdfWriter = RdfUtil.openWriter(schemaDefinitionRdfFile, encoding, rdfFormat); for (Statement s : stmts) { write(s, rdfWriter); } RdfUtil.closeWriter(rdfWriter); generatedRdfFiles.add(schemaDefinitionRdfFile); } // /** // * @param alreadyObservedFieldUris // * @param processedRecordsCount // * @return a mapping from field uris to observation counts // */ // private static Map<String, ObservationCount> cullObservedFieldUris( // Map<String, ObservationCount> alreadyObservedFieldUris, long processedRecordsCount) { // Map<String, ObservationCount> culledMap = new HashMap<String, ObservationCount>(); // // int beforeSize = alreadyObservedFieldUris.size(); // for (Entry<String, ObservationCount> entry : alreadyObservedFieldUris.entrySet()) { // ObservationCount oc = entry.getValue(); // if (oc.getObservedCount() > 1) { // culledMap.put(entry.getKey(), entry.getValue()); // } // if ((processedRecordsCount - oc.getLastObserved()) < 10000) { // culledMap.put(entry.getKey(), entry.getValue()); // } // } // int afterSize = culledMap.size(); // logger.info("Culled already observed field uris. Size before = " + beforeSize + // " Size after = " + afterSize); // return culledMap; // } /** * Set reader file suffix handling null and empty argument values * * @param readerKey * to set ; if empty or null {@link #readerKey} is set to * {@link StringConstants#BLANK}. */ private void setReaderKey(String readerKey) { this.readerKey = readerKey == null || readerKey.trim().isEmpty() ? StringConstants.BLANK : readerKey; } /** * Get reader-specifix file suffix * * @return suffix */ private String getReaderKey() { return readerKey; } /** * Write data source, and field instantiation statements that records and their fields will * reference. These initialization statements are written out to every output file as specified * in parser configuration file. * * @param rdfFiles * @param dataSourceInstanceStatements */ private void writeDataSourceInstanceStatements(Collection<? extends Statement> dataSourceInstanceStatements, RdfNamespace ns) { for (Statement s : dataSourceInstanceStatements) { write(s, ns); } } /** * Set rdf resource from which a lot of meta-data statements will be derived, including * datasets, records and their fields. * * @param rdfSource */ public void setCreatedTime(long createdTime) { this.createdTime = createdTime; } // /** // * Process record reader // * // * @param <E> // * record type // * @param dataRecordIterator // * iterator // * @param rdfConfigFileStream // * input stream to config file iterator // * @return record // * @throws IOException // */ // public <E extends DataRecord> void processRecordReader(RecordReader<E> dataRecordIterator, // long createdTime) throws IOException { // processRecordReader(dataRecordIterator, StringConstants.BLANK, createdTime, -1); // } /** * Process record reader * * @param <E> * record type * @param dataRecordIterator * iterator * @param rdfConfigFileStream * input stream to config file iterator * @param outputRecordLimit * max number of records to process; -1 for all * @return record * @throws IOException */ public <E extends DataRecord> void processRecordReader(RecordReader<E> dataRecordIterator, long createdTime, long outputRecordLimit) throws IOException { processRecordReader(dataRecordIterator, StringConstants.BLANK, createdTime, outputRecordLimit); } /** * Process file data by converting to RDF format and writing it out to an RDF file. * * @param readerKey * label to differentiate records * @param rdfFiles * output file definitions from parser config file * @param alreadyObservedFieldUris * @param recordIterator * iterator containing file data */ private void processRecord(DataRecord record, String readerKey, URIImpl recordUri) { setReaderKey(readerKey); Collection<? extends Statement> stmts = RdfRecordUtil.getRecordInstanceStatements(record, createdTime, recordUri, null, getReaderKey(), filter); RdfNamespace ns = RdfNamespace.getNamespace(RecordUtil.getRecordDataSource(record.getClass())); for (Statement stmt : stmts) { write(stmt, ns); } } /** * Constant is assumed to be a valid URI String * * @param tripleObj * @param <E> * @return */ private <E extends DataRecord> Map<Class<?>, Collection<Value>> getConstantValues(String value) { Map<Class<?>, Collection<Value>> type2valuesMap = new HashMap<Class<?>, Collection<Value>>(); Value constantValue = new URIImpl(value); CollectionsUtil.addToOne2ManyMap(String.class, constantValue, type2valuesMap); return type2valuesMap; } /** * * @param <E> * @param record * @param tripleObj * @return */ private <E extends DataRecord> Map<Class<?>, Collection<Value>> getLiteralValues(E record, String fieldName) { Map<Class<?>, Collection<Value>> type2valuesMap = new HashMap<Class<?>, Collection<Value>>(); Object fieldValue = PrivateAccessor.getFieldValue(record, fieldName); if (fieldValue == null) return type2valuesMap; if (fieldValue instanceof DataSourceElement<?>) { DataSourceElement<?> element = (DataSourceElement<?>) fieldValue; Value literalValue = RdfUtil.createLiteral(element.getDataElement()); CollectionsUtil.addToOne2ManyMap(fieldValue.getClass(), literalValue, type2valuesMap); return type2valuesMap; } if (fieldValue instanceof Collection<?>) { for (Object value : ((Collection<?>) fieldValue)) if (value instanceof DataSourceElement<?>) { DataSourceElement<?> element = (DataSourceElement<?>) fieldValue; Value literalValue = RdfUtil.createLiteral(element.getDataElement()); CollectionsUtil.addToOne2ManyMap(value.getClass(), literalValue, type2valuesMap); } else throw new RuntimeException(String.format("Unable to extract RDF object from field: %s. " + "Expected Collection<ResourceComponent> but instead observed Collection<%s>.", fieldName, value.getClass().getName())); return type2valuesMap; } throw new RuntimeException(String.format("Unable to extract RDF object from field: %s (observedValue=%s)", fieldName, fieldValue.toString())); } /** * Get values for triple definition where value is specified to use ICE formatting (ex: * {@code <object use-ice-id="true">ensemblGeneId</object>}) * * @param record * @param tripleObj * @return values */ private Map<Class<?>, Collection<Value>> getInformationContentEntityIDValues(DataRecord record, String fieldName) { Map<Class<?>, Collection<Value>> type2valuesMap = new HashMap<Class<?>, Collection<Value>>(); Object fieldValue = PrivateAccessor.getFieldValue(record, fieldName); if (fieldValue == null) return type2valuesMap; if (fieldValue instanceof DataSourceIdentifier<?>) { DataSourceIdentifier<?> id = (DataSourceIdentifier<?>) fieldValue; RdfId rdfId = new RdfId(id); Value iceIdValue = new URIImpl(RdfUtil.createKiaoUri(rdfId.getNamespace(), rdfId.getICE_ID()).toString()); CollectionsUtil.addToOne2ManyMap(fieldValue.getClass(), iceIdValue, type2valuesMap); return type2valuesMap; } if (fieldValue instanceof Collection<?>) { for (Object value : ((Collection<?>) fieldValue)) if (value instanceof DataSourceElement<?>) { DataSourceIdentifier<?> id = (DataSourceIdentifier<?>) value; RdfId rdfId = new RdfId(id); Value iceIdValue = new URIImpl(RdfUtil.createKiaoUri(rdfId.getNamespace(), rdfId.getICE_ID()) .toString()); CollectionsUtil.addToOne2ManyMap(value.getClass(), iceIdValue, type2valuesMap); } else throw new RuntimeException(String.format("Unable to extract RDF object from field: %s. " + "Expected Collection<DataElementIdentifier<?>> but instead observed Collection<%s>.", fieldName, value.getClass().getName())); return type2valuesMap; } throw new RuntimeException(String.format("Unable to extract RDF object from field: %s (observedValue=%s)", fieldName, fieldValue.toString())); } /** * Parser {@link DataRecord} from field of record. * * @param <E> * record type * @param record * instance * @param fieldName * field in record * @return record */ private <E extends DataRecord> Map<Class<?>, Collection<Value>> getValues(E record, String fieldName) { Map<Class<?>, Collection<Value>> type2valuesMap = new HashMap<Class<?>, Collection<Value>>(); Object fieldValue = PrivateAccessor.getFieldValue(record, fieldName); if (fieldValue == null) return type2valuesMap; if (fieldValue instanceof DataSourceElement<?>) { DataSourceElement<?> id = (DataSourceElement<?>) fieldValue; Value rdfValue = null; if (id instanceof DataSourceIdentifier<?>) { RdfId rdfId = new RdfId((DataSourceIdentifier<?>) id); rdfValue = rdfId.getRdfValue(); } else rdfValue = RdfUtil.createLiteral(id.getDataElement()); CollectionsUtil.addToOne2ManyMap(fieldValue.getClass(), rdfValue, type2valuesMap); return type2valuesMap; } if (fieldValue instanceof Collection<?>) { for (Object value : ((Collection<?>) fieldValue)) { if (value instanceof DataSourceElement<?>) { DataSourceElement<?> id = (DataSourceElement<?>) value; Value rdfValue = null; if (id instanceof DataSourceIdentifier<?>) { RdfId rdfId = new RdfId((DataSourceIdentifier<?>) id); rdfValue = rdfId.getRdfValue(); } else rdfValue = RdfUtil.createLiteral(id.getDataElement()); CollectionsUtil.addToOne2ManyMap(value.getClass(), rdfValue, type2valuesMap); } else { throw new RuntimeException(String.format("Unable to extract RDF object from field: %s. " + "Expected Collection<ResourceComponent> but instead observed Collection<%s>.", fieldName, value.getClass().getName())); } } return type2valuesMap; } throw new RuntimeException(String.format("Unable to extract RDF object from field: %s (observedValue=%s)", fieldName, fieldValue.toString())); } /** * Returns the subject Resource representation of the value of the field with the given name * contained in the input DataRecord. The field must be of type ResourceIdentifier. * * @param record * @param fieldName * @return * */ private Collection<Resource> getSubjectResources(DataRecord record, String fieldName) { Collection<Resource> resources = new ArrayList<Resource>(); Object fieldValue = PrivateAccessor.getFieldValue(record, fieldName); if (fieldValue instanceof DataSourceIdentifier<?>) { DataSourceIdentifier<?> id = (DataSourceIdentifier<?>) fieldValue; RdfId rdfId = new RdfId(id); resources.add(new URIImpl(RdfUtil.createKiaoUri(rdfId.getNamespace(), id.toString()).toString())); return resources; } if (fieldValue instanceof Collection<?>) { for (Object resource : ((Collection<?>) fieldValue)) if (resource instanceof DataSourceIdentifier<?>) { DataSourceIdentifier<?> id = (DataSourceIdentifier<?>) resource; RdfId rdfId = new RdfId(id); resources.add(new URIImpl(RdfUtil.createKiaoUri(rdfId.getNamespace(), id.toString()).toString())); } else { String message = String.format("Unable to extract RDF subject from field: %s. " + "Expected Collection<ResourceIdentifier> but instead observed Collection<%s>.", fieldName, resource.getClass().getName()); throw new RuntimeException(message); } return resources; } throw new RuntimeException(String.format("Unable to extract RDF subject from field: %s (observedValue=%s)", fieldName, fieldValue.toString())); } /** * Output RDF record to a file based on record's file key. * * @param ns * * @param rdfTriple * to output */ private void write(Statement stmt, RdfNamespace ns) { RDFWriter rdfWriter = getWriter(ns); // primary key field values will always be printed, so there's no reason to check and store // them in the filter. This saves some memory and also the time needed to check for // something that is guaranteed to not be already observed boolean checkFilter = needToCheckFilter(stmt.getSubject()); if (!checkFilter || (checkFilter && !filter.alreadyObservedStatement(stmt))) { if (!rollingCacheContains(stmt)) { write(stmt, rdfWriter); writtenStatementCount++; } } } /** * if the input subject matches one of the prefixes for a primary key field then we do not need * to check the filter b/c there is no way that field has been previously observed. Aside from * saving time, this will also save on memory b/c there's no point in caching this field since * it should not be observed again given its "primary key" status * * @param subject * @param primaryKeyFieldValues * will contain things like: F_SparseUniProtDatFileRecord_accession_ * @return true if the filter should be checked, false otherwise */ private boolean needToCheckFilter(Resource subject) { String sub = subject.toString(); for (String key : primaryKeyFieldNames) { if (sub.contains(key)) { return false; } } return true; } /** * keeps track of the most recent 1000 statements and returns true if the input statement is in * the cache * * @param stmt * @return */ private boolean rollingCacheContains(Statement stmt) { String stmtStr = stmt.toString(); if (rollingCacheSet.contains(stmtStr)) { return true; } int currentSize = rollingCacheList.size(); if (currentSize >= ROLLING_CACHE_MAX_SIZE) { String removed = rollingCacheList.removeLast(); rollingCacheSet.remove(removed); } rollingCacheSet.add(stmtStr); rollingCacheList.addFirst(stmtStr); return false; } /** * Write statement using provided writer. * * @param s * statement * @param rdfWriter * writer */ private static void write(Statement s, RDFWriter rdfWriter) { try { rdfWriter.handleStatement(s); } catch (RDFHandlerException e) { throw new RuntimeException(e); } } /** * Initialize lazily and return rdf writer. * * @param ns * * @param rdfFile * key to use when generating and storing rdf writer * @return rdf writer * @throws FileNotFoundException * @throws RDFHandlerException */ private RDFWriter getWriter(RdfNamespace ns) { File outputFile = getOutputFile(ns); if (!file2RdfWriterMap.containsKey(outputFile)) { generatedRdfFiles.add(outputFile); Writer writer = null; try { logger.info("Initializing new RDF writer. Compress flag = " + compress + " Output file = " + outputFile); OutputStream os = new FileOutputStream(outputFile); if (compress) { os = new GZIPOutputStream(os); } writer = new BufferedWriter(new OutputStreamWriter(os, Charset.forName(encoding.getCharacterSetName()) .newEncoder())); } catch (IOException e) { throw new RuntimeException("Error occured while creating rdf writer to " + getOutputFile(ns), e); } // ensure calls to Rio.createWriter are synchronized on class creating concurrent rdf // writers synchronized (RdfRecordWriterImpl.class) { RDFWriter rdfWriter = rdfFormat.createWriter(writer); try { rdfWriter.startRDF(); } catch (RDFHandlerException e) { throw new RuntimeException("Error occured while starting rdf writer to " + getOutputFile(ns), e); } file2RdfWriterMap.put(outputFile, new RdfWriterResource(rdfWriter, writer)); } } return file2RdfWriterMap.get(outputFile).rw; } /** * Get file index derived from total # of statements writtent to a file and * {@link #maxStatementsPerFile} value. * * @param rdfFile * file * @return file index */ private long getOutFileIndex() { return maxStatementsPerFile > 0 ? writtenStatementCount / maxStatementsPerFile : 0; } // /** // * Opens an OutputStream based on the fileKey and {@link #baseRdfFileName} // * // * @param rdfFile // * @return // * @throws FileNotFoundException // */ // private OutputStream getOutputStream() throws IOException { // File outputFile = getOutputFile(); // generatedRdfFiles.add(outputFile); // if (compress) { // logger.info("RDF output stream will be a GZIPOutputStream"); // return new GZIPOutputStream(new FileOutputStream(outputFile)); // } // logger.info("RDF output stream will NOT be a compressed."); // return new FileOutputStream(outputFile); // } /** * Creates a reference to the RDF output File * * @param ns * * @param rdfFile * to use in file name generation * @return full rdf file path */ private File getOutputFile(RdfNamespace ns) { return FileUtil.appendPathElementsToDirectory(outputDirectory, getOutputFileName(ns)); } /** * Compiles the name of the output file * * @param ns * * @return */ private String getOutputFileName(RdfNamespace ns) { String recordReaderClass = recordReader.getClass().getSimpleName(); recordReaderClass = (recordReader.getDataSpecificKey().isEmpty()) ? recordReaderClass : recordReaderClass + StringConstants.HYPHEN_MINUS + recordReader.getDataSpecificKey(); String fileName = ns.name().toLowerCase() + StringConstants.HYPHEN_MINUS + recordReaderClass + (getReaderKey().isEmpty() ? StringConstants.BLANK : StringConstants.HYPHEN_MINUS) + getReaderKey() + StringConstants.PERIOD + getOutFileIndex() + StringConstants.HYPHEN_MINUS + batchNumber + StringConstants.PERIOD + rdfFormat.defaultFileExtension(); fileName = (compress) ? fileName + ".gz" : fileName; return fileName; } /** * Closes the RDFWriters * * @param rdfWriters * @throws RDFHandlerException */ private void closeFiles() throws IOException { try { for (RdfWriterResource rdfWriterResource : file2RdfWriterMap.values()) { rdfWriterResource.rw.endRDF(); rdfWriterResource.w.close(); } } catch (RDFHandlerException e) { throw new IOException("Exception while closing RDF Writers.", e); } } // /** // * By convention, the configuration file directing RDF output lives on the classpath in the // same // * package as the parser to which it belongs. The name of the configuration file is the name // of // * the parser lowercased with the .rdf-config.xml suffix. // * // * @param recordReader // * @return // * @throws IOException // */ // private List<RdfFile> getRdfFilesToCreate(InputStream configStream) throws IOException { // return RdfConfigFileReader.parseRdfConfig(configStream); // } // // /** // * Definition for rdf instance and target file key. // * // * @author bill // */ // protected static class RdfTriple { // /** triple statement */ // private final Statement statement; // /** config rdf file definition; contains output file key */ // private final RdfFile rdfFile; // // /** // * Constructor // * // * @param statement // * triple // * @param rdfFile // * rdf file from which statement was derived // */ // public RdfTriple(Statement statement, RdfFile rdfFile) { // super(); // this.statement = statement; // this.rdfFile = rdfFile; // } // // /** // * Get statement. // * // * @return statement // */ // public Statement getStatement() { // return statement; // } // // /** // * Get rdf file configuration. // * // * @return config // */ // public RdfFile getRdfFile() { // return rdfFile; // } // } /** * @return the encoding */ public CharacterEncoding getEncoding() { return encoding; } /** * @param encoding * the encoding to set */ public void setEncoding(CharacterEncoding encoding) { this.encoding = encoding; } /** * Wrapper that captures {@link RDFWriter} and underlying {@link Writer} for post processing. */ private static class RdfWriterResource { /** rdf writer */ private final RDFWriter rw; /** underlying writer used by rdf writer */ private final Writer w; /** * Constructor . * * @param rw * rdf writer * @param w * java writer */ public RdfWriterResource(RDFWriter rw, Writer w) { this.rw = rw; this.w = w; } } }
datasource-rdfizer/src/main/java/edu/ucdenver/ccp/datasource/rdfizer/rdf/ice/RdfRecordWriterImpl.java
Migrating from rdfizer to datasource
datasource-rdfizer/src/main/java/edu/ucdenver/ccp/datasource/rdfizer/rdf/ice/RdfRecordWriterImpl.java
Migrating from rdfizer to datasource
Java
mit
9c69f133a988c00392229e7cb38ba03323faa8e1
0
martinsawicki/azure-sdk-for-java,navalev/azure-sdk-for-java,selvasingh/azure-sdk-for-java,Azure/azure-sdk-for-java,hovsepm/azure-sdk-for-java,Azure/azure-sdk-for-java,navalev/azure-sdk-for-java,hovsepm/azure-sdk-for-java,selvasingh/azure-sdk-for-java,martinsawicki/azure-sdk-for-java,martinsawicki/azure-sdk-for-java,navalev/azure-sdk-for-java,jianghaolu/azure-sdk-for-java,navalev/azure-sdk-for-java,ljhljh235/azure-sdk-for-java,Azure/azure-sdk-for-java,hovsepm/azure-sdk-for-java,Azure/azure-sdk-for-java,Azure/azure-sdk-for-java,hovsepm/azure-sdk-for-java,navalev/azure-sdk-for-java,jianghaolu/azure-sdk-for-java,jianghaolu/azure-sdk-for-java,hovsepm/azure-sdk-for-java,selvasingh/azure-sdk-for-java,ljhljh235/azure-sdk-for-java
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. */ package com.microsoft.azure.management.documentdb.samples; import com.microsoft.azure.credentials.ApplicationTokenCredentials; import com.microsoft.azure.management.Azure; import com.microsoft.azure.management.documentdb.DatabaseAccountKind; import com.microsoft.azure.management.documentdb.DocumentDBAccount; import com.microsoft.azure.management.resources.fluentcore.arm.Region; import com.microsoft.azure.management.resources.fluentcore.utils.SdkContext; import com.microsoft.azure.management.samples.Utils; import com.microsoft.rest.LogLevel; import java.io.File; /** * Azure DocumentDB sample for high availability. * - Create a DocumentDB configured with IP range filter * - Delete the DocumentDB. */ public final class CreateDocumentDBWithIPRange { /** * Main function which runs the actual sample. * @param azure instance of the azure client * @param clientId client id * @return true if sample runs successfully */ public static boolean runSample(Azure azure, String clientId) { final String docDBName = SdkContext.randomResourceName("docDb", 10); final String rgName = SdkContext.randomResourceName("rgNEMV", 24); try { //============================================================ // Create a DocumentDB System.out.println("Creating a DocumentDB..."); DocumentDBAccount documentDBAccount = azure.documentDBs().define(docDBName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withKind(DatabaseAccountKind.GLOBAL_DOCUMENT_DB) .withSessionConsistency() .withWriteReplication(Region.US_WEST) .withReadReplication(Region.US_CENTRAL) .withIpRangeFilter("13.91.6.132,13.91.6.1/24") .create(); System.out.println("Created DocumentDB"); Utils.print(documentDBAccount); //============================================================ // Delete DocumentDB System.out.println("Deleting the DocumentDB"); azure.documentDBs().deleteById(documentDBAccount.id()); System.out.println("Deleted the DocumentDB"); return true; } catch (Exception e) { System.err.println(e.getMessage()); } finally { try { System.out.println("Deleting resource group: " + rgName); azure.resourceGroups().deleteByName(rgName); System.out.println("Deleted resource group: " + rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } return false; } /** * Main entry point. * @param args the parameters */ public static void main(String[] args) { try { //============================================================= // Authenticate final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION")); Azure azure = Azure.configure() .withLogLevel(LogLevel.BASIC) .authenticate(credFile) .withDefaultSubscription(); // Print selected subscription System.out.println("Selected subscription: " + azure.subscriptionId()); runSample(azure, ApplicationTokenCredentials.fromFile(credFile).clientId()); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private CreateDocumentDBWithIPRange() { } }
azure-samples/src/main/java/com/microsoft/azure/management/documentdb/samples/CreateDocumentDBWithIPRange.java
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. */ package com.microsoft.azure.management.documentdb.samples; import com.microsoft.azure.credentials.ApplicationTokenCredentials; import com.microsoft.azure.management.Azure; import com.microsoft.azure.management.documentdb.DatabaseAccountKind; import com.microsoft.azure.management.documentdb.DocumentDBAccount; import com.microsoft.azure.management.resources.fluentcore.arm.Region; import com.microsoft.azure.management.resources.fluentcore.utils.SdkContext; import com.microsoft.azure.management.samples.Utils; import com.microsoft.rest.LogLevel; import java.io.File; /** * Azure DocumentDB sample for high availability - * - Create a DocumentDB configured with IP range filter * - Delete the DocumentDB. */ public final class CreateDocumentDBWithIPRange { /** * Main function which runs the actual sample. * @param azure instance of the azure client * @param clientId client id * @return true if sample runs successfully */ public static boolean runSample(Azure azure, String clientId) { final String docDBName = SdkContext.randomResourceName("docDb", 10); final String rgName = SdkContext.randomResourceName("rgNEMV", 24); try { //============================================================ // Create a DocumentDB System.out.println("Creating a DocumentDB..."); DocumentDBAccount documentDBAccount = azure.documentDBs().define(docDBName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withKind(DatabaseAccountKind.GLOBAL_DOCUMENT_DB) .withSessionConsistency() .withWriteReplication(Region.US_WEST) .withReadReplication(Region.US_CENTRAL) .withIpRangeFilter("13.91.6.132,13.91.6.1/24") .create(); System.out.println("Created DocumentDB"); Utils.print(documentDBAccount); //============================================================ // Delete DocumentDB System.out.println("Deleting the DocumentDB"); azure.documentDBs().deleteById(documentDBAccount.id()); System.out.println("Deleted the DocumentDB"); return true; } catch (Exception e) { System.err.println(e.getMessage()); } finally { try { System.out.println("Deleting resource group: " + rgName); azure.resourceGroups().deleteByName(rgName); System.out.println("Deleted resource group: " + rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } return false; } /** * Main entry point. * @param args the parameters */ public static void main(String[] args) { try { //============================================================= // Authenticate final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION")); Azure azure = Azure.configure() .withLogLevel(LogLevel.BASIC) .authenticate(credFile) .withDefaultSubscription(); // Print selected subscription System.out.println("Selected subscription: " + azure.subscriptionId()); runSample(azure, ApplicationTokenCredentials.fromFile(credFile).clientId()); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private CreateDocumentDBWithIPRange() { } }
Update CreateDocumentDBWithIPRange.java
azure-samples/src/main/java/com/microsoft/azure/management/documentdb/samples/CreateDocumentDBWithIPRange.java
Update CreateDocumentDBWithIPRange.java
Java
mit
error: pathspec 'calculate_average.java' did not match any file(s) known to git
03520a5187cea3ef7172f9c14a75579252b34a56
1
brdavis/Algorithms-and-Data-Structures---Java
public class calculate_average{ public static void main(String[] args) { //set variables int[] numbers = {1, 3, 5, 7, 9}; int total = 0; int i; //calculate average for(i = 0; i < numbers.length; i++) { total += numbers[i]; } int average = total/numbers.length; //print result System.out.printf("The average of:\n"); for(i = 0; i < numbers.length; i++) { System.out.printf("%d ", numbers[i]); } System.out.printf("\nis %d \n", average); } }
calculate_average.java
calculates the average of a set of numbers
calculate_average.java
calculates the average of a set of numbers
Java
mit
error: pathspec 'iq/src/datastructures/LRUCache.java' did not match any file(s) known to git
0e8154c190a3427204fd27d9a9c76b884a9a110b
1
vadadler/java
package datastructures; import java.util.HashMap; /** * Design and implement a data structure for Least Recently Used (LRU) cache. It should * support the following operations: get and set. * get(key) - Get the value (will always be positive) of the key if the key * exists in the cache, otherwise return -1. * set(key, value) - Set or insert the value if the key is not already present. When the * cache reached its capacity, it should invalidate the least recently * used item before inserting a new * * Implementation: The LRU cache is a hash table of keys and double linked nodes. * The hashtable makes the time of get() to be O(1). The list of double * linked nodes make the nodes adding/removal operations O(1). */ public class LRUCache { // Maximum values to stored in cache. public static final int MAX_CAPACITY = 10; HashMap<Integer, Node> mValues = new HashMap<Integer, Node>(); Node mHead=null; Node mEnd=null; public void setHead(Node n) { n.next = mHead; n.previous = null; if(mHead!=null) { mHead.previous = n; } mHead = n; if(mEnd == null) { mEnd = mHead; } } /** * Get value from cache. * @param key of the value. * @return value or -1 if element does not exist. */ public int get(int key) { if(mValues.containsKey(key) == true) { Node node = mValues.get(key); remove(node); setHead(node); return node.mValue; } return -1; } public void remove(Node n) { if(n.previous != null) { n.previous.next = n.next; } else { mHead = n.next; } if(n.next!=null) { n.next.previous = n.previous; } else { mEnd = n.previous; } } public void set(int key, int value) { if(mValues.containsKey(key) == true) { Node node = mValues.get(key); node.mValue = value; remove(node); setHead(node); } else { Node node = new Node(key, value); if(mValues.size() >= MAX_CAPACITY){ mValues.remove(node.mKey); remove(node); setHead(node); } else { setHead(node); } mValues.put(key, node); } } private class Node { int mKey; int mValue; Node next; Node previous; public Node(int k, int v) { mKey = k; mValue = v; } } }
iq/src/datastructures/LRUCache.java
Initial revision of LRUCache.
iq/src/datastructures/LRUCache.java
Initial revision of LRUCache.
Java
mit
error: pathspec 'ev3classes/src/lejos/robotics/filter/AzimuthFilter.java' did not match any file(s) known to git
7ea31fe4d8ca71612d63ee1148b70bdc51d64c2d
1
rafalmag/EV3-projects
//package lejos.robotics.filter; // //import lejos.robotics.SampleProvider; // ///** // * This SampleProvider converts magnetic field strengths from a magnetometer // * (triaxis compass sensor) into azimuth.<br> // * Azimuth (expressed in radians) is the angle between North and the X-axis of // * the magnetometer. // * <p> // * To apply tilt correction specify an accelerometer in the constructor of this // * class. // * // * @author Aswin // * // */ //public class AzimuthFilter extends AbstractFilter { // float[] m = new float[3]; // SampleProvider accelerometer = null; // float[] t; // Vector3f magneto, accel, west; // // /** // * Constructor for the Azimuth filter without tilt correction. // * <p> // * // * @param source // * SampleProvider that provides magnetic field strength over X, Y and // * Z // */ // public AzimuthFilter(SampleProvider source) { // super(source); // sampleSize = 1; // } // // /** // * Constructor for the Azimuth filter with tilt correction. // * // * @param source // * SampleProvider that provides magnetic field strength over X, Y and // * Z // * @param accelerometer // * ampleProvider that provides acceleration over X, Y and Z // */ // public AzimuthFilter(SampleProvider source, SampleProvider accelerometer) { // this(source); // this.accelerometer = accelerometer; // t = new float[3]; // magneto = new Vector3f(); // accel = new Vector3f(); // west = new Vector3f(); // } // // @Override // public void fetchSample(float[] sample, int offset) { // double direction; // source.fetchSample(m, 0); // if (accelerometer == null) { // direction = Math.atan2(m[1], m[0]); // } // else { // /** // * Apply tilt correction. Tilt correction is based on the fact that the // * cross product of two vectors gives a vector perpendicular to the other // * two vectors. A vector perpendicular to the gravity vector (down) and // * the magnetic field vector (north) points east/west. // */ // accelerometer.fetchSample(t, 0); // magneto.set(m); // accel.set(t); // west.cross(magneto, accel); // direction = Math.atan2(west.y, west.x) + .5 * Math.PI; // } // if (direction < 0) // direction += 2 * Math.PI; // sample[offset] = (float) direction; // } // //}
ev3classes/src/lejos/robotics/filter/AzimuthFilter.java
Added (experimental) azimuth filter to convert magnetic data to azimuth
ev3classes/src/lejos/robotics/filter/AzimuthFilter.java
Added (experimental) azimuth filter to convert magnetic data to azimuth
Java
mit
error: pathspec 'src/test/java/org/tendiwa/lexeme/ParsedWordFormTest.java' did not match any file(s) known to git
1adb5d98c13b6edf4939f3d4d0988f1736daa68d
1
Suseika/liblexeme,Suseika/inflectible
package org.tendiwa.lexeme; import com.google.common.collect.ImmutableSet; import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Test; import org.tendiwa.lexeme.implementations.English; /** * @since 0.1 */ public final class ParsedWordFormTest { @Test public void hasSpelling() throws Exception { MatcherAssert.assertThat( this.wordFormBears().spelling(), CoreMatchers.equalTo("bears") ); } @Test public void computesSimilarity() throws Exception { MatcherAssert.assertThat( this.wordFormBears() .similarity(ImmutableSet.of(English.Grammemes.Plur)), CoreMatchers.equalTo(1) ); } private ParsedWordForm wordFormBears() { return new ParsedWordForm( new English().grammar(), new BasicWordBundleParser( ParsedWordFormTest.class.getResourceAsStream( "characters.en_US.words" ) ) .word_bundle() .word() .get(0) .word_forms() .entry() .get(1) ); } }
src/test/java/org/tendiwa/lexeme/ParsedWordFormTest.java
#59 Create test for ParsedWordForm
src/test/java/org/tendiwa/lexeme/ParsedWordFormTest.java
#59 Create test for ParsedWordForm
Java
mit
error: pathspec 'src/main/java/org/nunnerycode/bukkit/mobbountyreloaded/events/MobBountyReloadedRewardEvent.java' did not match any file(s) known to git
51233ddbedc35d00ffeaccfd13634ff1608466c0
1
Nunnery/MobBountyReloaded
package org.nunnerycode.bukkit.mobbountyreloaded.events; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; public final class MobBountyReloadedRewardEvent { private final Player player; private final LivingEntity entity; private double amount; public MobBountyReloadedRewardEvent(Player player, LivingEntity entity, double amount) { this.player = player; this.entity = entity; this.amount = amount; } public LivingEntity getEntity() { return entity; } public Player getPlayer() { return player; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } }
src/main/java/org/nunnerycode/bukkit/mobbountyreloaded/events/MobBountyReloadedRewardEvent.java
adding MobBountyReloadedRewardEvent class
src/main/java/org/nunnerycode/bukkit/mobbountyreloaded/events/MobBountyReloadedRewardEvent.java
adding MobBountyReloadedRewardEvent class
Java
mit
error: pathspec 'QuizRouletteServer-build/QuizRouletteServer-test/src/test/java/ch/heigvd/res/labs/roulette/net/client/RouletteV2QuentingigonTest.java' did not match any file(s) known to git
21f42f5af5791f13ab0e21d7598390f50874c6f1
1
IamFonky/Teaching-HEIGVD-RES-2017-Labo-02,IamFonky/Teaching-HEIGVD-RES-2017-Labo-02
package ch.heigvd.res.labs.roulette.net.client; import ch.heigvd.res.labs.roulette.data.EmptyStoreException; import ch.heigvd.res.labs.roulette.data.Student; import ch.heigvd.res.labs.roulette.net.protocol.RouletteV2Protocol; import ch.heigvd.schoolpulse.TestAuthor; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.IOException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * This class contains automated tests to validate the client and the server * implementation of the Roulette Protocol (version 1) * * @author Olivier Liechti */ @Ignore public class RouletteV2QuentingigonTest { @Rule public ExpectedException exception = ExpectedException.none(); @Rule public EphemeralClientServerPair roulettePair = new EphemeralClientServerPair(RouletteV2Protocol.VERSION); @Test @TestAuthor(githubId = {"quentingigon", "MathiasGilson"}) public void theServerShouldHaveZeroStudentsAfterAClear() throws IOException { IRouletteV2Client client = new RouletteV2ClientImpl(); int port = roulettePair.getServer().getPort(); client.connect("localhost", port); client.loadStudent("sacha"); client.loadStudent("olivier"); client.loadStudent("fabienne"); client.clearDataStore(); assertEquals(0, client.getNumberOfStudents()); } @Test @TestAuthor(githubId = {"quentingigon", "MathiasGilson"}) public void theServerShouldListAllStudentsLoaded() throws IOException, EmptyStoreException { IRouletteV2Client client = new RouletteV2ClientImpl(); int port = roulettePair.getServer().getPort(); client.connect("localhost", port); client.loadStudent("sacha"); client.loadStudent("olivier"); client.loadStudent("fabienne"); assertEquals(client.listStudents().size(), client.getNumberOfStudents()); } @Test @TestAuthor(githubId = {"quentingigon", "MathiasGilson"}) public void theServerShouldContainAllStudentsLoaded() throws IOException, EmptyStoreException { IRouletteV2Client client = new RouletteV2ClientImpl(); int port = roulettePair.getServer().getPort(); client.connect("localhost", port); client.loadStudent("sacha"); client.loadStudent("olivier"); client.loadStudent("fabienne"); assertTrue(client.listStudents().contains(new Student("sasha"))); assertTrue(client.listStudents().contains(new Student("olivier"))); assertTrue(client.listStudents().contains(new Student("fabienne"))); } @Test @TestAuthor(githubId = {"quentingigon", "MathiasGilson"}) public void theServerShouldGiveTheCorrectVersionNumber() throws IOException { assertEquals(RouletteV2Protocol.VERSION, roulettePair.getClient().getProtocolVersion()); } }
QuizRouletteServer-build/QuizRouletteServer-test/src/test/java/ch/heigvd/res/labs/roulette/net/client/RouletteV2QuentingigonTest.java
tests for v2 (#155)
QuizRouletteServer-build/QuizRouletteServer-test/src/test/java/ch/heigvd/res/labs/roulette/net/client/RouletteV2QuentingigonTest.java
tests for v2 (#155)
Java
mpl-2.0
error: pathspec 'qadevOOo/tests/java/ifc/form/_XConfirmDeleteBroadcaster.java' did not match any file(s) known to git
e2d78feb069983320a46c1a6c9f7e6a798cf3954
1
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
/************************************************************************* * * $RCSfile: _XConfirmDeleteBroadcaster.java,v $ * * $Revision: 1.2 $ * * last change:$Date: 2003-11-18 16:22:17 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ package ifc.form; import com.sun.star.form.XConfirmDeleteBroadcaster; import com.sun.star.form.XConfirmDeleteListener; import com.sun.star.lang.EventObject; import com.sun.star.sdb.RowChangeEvent; import lib.MultiMethodTest; /** * Testing <code>com.sun.star.util.XConfirmDeleteBroadcaster</code> * interface methods : * <ul> * <li><code>addConfirmDeleteListener()</code></li> * <li><code>removeConfirmDeleteListener()</code></li> * </ul> <p> * * Result checking is not performed. Confirm delete * listeners are called only in case of * interaction with UI. <p> * * Test is <b> NOT </b> multithread compilant. <p> * @see com.sun.star.util.XConfirmDeleteBroadcaster */ public class _XConfirmDeleteBroadcaster extends MultiMethodTest { public XConfirmDeleteBroadcaster oObj = null; protected boolean confirmed = false; protected XConfirmDeleteListener mxConfirmDeleteListener = new ConfirmDeleteImpl(); private class ConfirmDeleteImpl implements XConfirmDeleteListener { public boolean confirmDelete(RowChangeEvent rowChangeEvent) { confirmed = true; return true; } public void disposing(EventObject eventObject) { } } protected void addConfirmDeleteListener() { oObj.addConfirmDeleteListener(mxConfirmDeleteListener); tRes.tested("addConfirmDeleteListener()", true); } protected void removeConfirmDeleteListener() { oObj.removeConfirmDeleteListener(mxConfirmDeleteListener); tRes.tested("removeConfirmDeleteListener()", true); } }
qadevOOo/tests/java/ifc/form/_XConfirmDeleteBroadcaster.java
INTEGRATION: CWS qadev13 (1.1.2); FILE ADDED 2003/11/12 17:48:47 sg 1.1.2.1: #113689#NEW: initial version
qadevOOo/tests/java/ifc/form/_XConfirmDeleteBroadcaster.java
INTEGRATION: CWS qadev13 (1.1.2); FILE ADDED 2003/11/12 17:48:47 sg 1.1.2.1: #113689#NEW: initial version
Java
mpl-2.0
error: pathspec 'xmerge/source/writer2latex/source/writer2latex/office/ListStyle.java' did not match any file(s) known to git
420db4d1faef8d329eb10a3e5e0a6d2ca5b41230
1
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
/************************************************************************ * * ListStyle.java * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * Copyright: 2002 by Henrik Just * * All Rights Reserved. * * Version 0.3.3 (2004-02-16) * */ package writer2latex.office; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import writer2latex.util.Misc; /** <p> Class representing a list style (including outline numbering) in OOo Writer </p> */ public class ListStyle extends OfficeStyle { // the file format doesn't specify a maximum nesting level, but OOo // currently supports 10 private static final int MAX_LEVEL = 10; private PropertySet[] level; private PropertySet[] levelStyle; public ListStyle() { level = new PropertySet[MAX_LEVEL+1]; levelStyle = new PropertySet[MAX_LEVEL+1]; for (int i=1; i<=MAX_LEVEL; i++) { level[i] = new PropertySet(); levelStyle[i] = new PropertySet(); } } public String getLevelType(int i) { if (i>=1 && i<=MAX_LEVEL) { return level[i].getName(); } else { return null; } } public boolean isNumber(int i) { return XMLString.TEXT_LIST_LEVEL_STYLE_NUMBER.equals(level[i].getName()); } public boolean isBullet(int i) { return XMLString.TEXT_LIST_LEVEL_STYLE_BULLET.equals(level[i].getName()); } public boolean isImage(int i) { return XMLString.TEXT_LIST_LEVEL_STYLE_IMAGE.equals(level[i].getName()); } public String getLevelProperty(int i, String sName) { if (i>=1 && i<=MAX_LEVEL) { return level[i].getProperty(sName); } else { return null; } } public String getLevelStyleProperty(int i, String sName) { if (i>=1 && i<=MAX_LEVEL) { return levelStyle[i].getProperty(sName); } else { return null; } } public void loadStyleFromDOM(Node node) { super.loadStyleFromDOM(node); // Collect level information from child elements: if (node.hasChildNodes()){ NodeList nl = node.getChildNodes(); int nLen = nl.getLength(); for (int i = 0; i < nLen; i++ ) { Node child=nl.item(i); if (child.getNodeType()==Node.ELEMENT_NODE){ String sLevel = Misc.getAttribute(child,XMLString.TEXT_LEVEL); if (sLevel!=null) { int nLevel = Misc.getPosInteger(sLevel,1); if (nLevel>=1 && nLevel<=MAX_LEVEL) { level[nLevel].loadFromDOM(child); // Also include style:properties if (child.hasChildNodes()){ NodeList nl2 = child.getChildNodes(); int nLen2 = nl2.getLength(); for (int i2 = 0; i2 < nLen2; i2++ ) { Node child2=nl2.item(i2); if (child2.getNodeType()==Node.ELEMENT_NODE){ if (child2.getNodeName().equals(XMLString.STYLE_PROPERTIES)) { levelStyle[nLevel].loadFromDOM(child2); } } } } } } } } } } }
xmerge/source/writer2latex/source/writer2latex/office/ListStyle.java
INTEGRATION: CWS latex (1.1.2); FILE ADDED 2006/04/06 14:11:52 sus 1.1.2.1: #i24813# Adding LaTeX and BibTeX filter
xmerge/source/writer2latex/source/writer2latex/office/ListStyle.java
INTEGRATION: CWS latex (1.1.2); FILE ADDED 2006/04/06 14:11:52 sus 1.1.2.1: #i24813# Adding LaTeX and BibTeX filter
Java
agpl-3.0
97733848e7fc7d666d51f0efbc35be0d355021d5
0
MilosKozak/AndroidAPS,PoweRGbg/AndroidAPS,Heiner1/AndroidAPS,winni67/AndroidAPS,PoweRGbg/AndroidAPS,jotomo/AndroidAPS,MilosKozak/AndroidAPS,winni67/AndroidAPS,PoweRGbg/AndroidAPS,Heiner1/AndroidAPS,Heiner1/AndroidAPS,Heiner1/AndroidAPS,MilosKozak/AndroidAPS,jotomo/AndroidAPS,jotomo/AndroidAPS
package de.jotomo.ruffyscripter.commands; import android.os.SystemClock; import org.monkey.d.ruffy.ruffy.driver.display.MenuAttribute; import org.monkey.d.ruffy.ruffy.driver.display.MenuType; import org.monkey.d.ruffy.ruffy.driver.display.menu.MenuTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Locale; import de.jotomo.ruffyscripter.PumpState; import de.jotomo.ruffyscripter.RuffyScripter; public class SetTbrCommand implements Command { private static final Logger log = LoggerFactory.getLogger(SetTbrCommand.class); private final long percentage; private final long duration; public SetTbrCommand(long percentage, long duration) { this.percentage = percentage; this.duration = duration; } @Override public List<String> validateArguments() { List<String> violations = new ArrayList<>(); if (percentage % 10 != 0) { violations.add("TBR percentage must be set in 10% steps"); } if (percentage < 0 || percentage > 500) { violations.add("TBR percentage must be within 0-500%"); } if (percentage != 100) { if (duration % 15 != 0) { violations.add("TBR duration can only be set in 15 minute steps"); } if (duration > 60 * 24) { violations.add("Maximum TBR duration is 24 hours"); } } if (percentage == 0 && duration > 120) { violations.add("Max allowed zero-temp duration is 2h"); } return violations; } @Override public CommandResult execute(RuffyScripter scripter, PumpState initialPumpState) { try { enterTbrMenu(scripter); boolean tbrPercentInputSuccess = false; int tbrPercentInputRetries = 2; while (!tbrPercentInputSuccess) { try { inputTbrPercentage(scripter); SystemClock.sleep(750); verifyDisplayedTbrPercentage(scripter); tbrPercentInputSuccess = true; } catch (CommandException e) { if (tbrPercentInputRetries >= 0) { log.warn("Setting TBR percentage failed, retrying", e); tbrPercentInputRetries--; } else { throw e; } } } if (percentage == 100) { cancelTbrAndConfirmCancellationWarning(scripter); } else { // switch to TBR_DURATION menu by pressing menu key scripter.verifyMenuIsDisplayed(MenuType.TBR_SET); scripter.pressMenuKey(); scripter.waitForMenuUpdate(); scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION); boolean tbrDurationSuccess = false; int tbrDurationRetries = 2; while (!tbrDurationSuccess) { try { inputTbrDuration(scripter); SystemClock.sleep(750); verifyDisplayedTbrDuration(scripter); tbrDurationSuccess = true; } catch (CommandException e) { if (tbrDurationRetries >= 0) { log.warn("Setting TBR duration failed, retrying", e); tbrDurationRetries--; } else { throw e; } } } // confirm TBR scripter.pressCheckKey(); scripter.waitForMenuToBeLeft(MenuType.TBR_DURATION); } scripter.verifyMenuIsDisplayed(MenuType.MAIN_MENU, "Pump did not return to MAIN_MEU after setting TBR. " + "Check pump manually, the TBR might not have been set/cancelled."); // check main menu shows the same values we just set if (percentage == 100) { verifyMainMenuShowsNoActiveTbr(scripter); return new CommandResult().success(true).enacted(true).message("TBR was cancelled"); } else { verifyMainMenuShowsExpectedTbrActive(scripter); return new CommandResult().success(true).enacted(true).message( String.format(Locale.US, "TBR set to %d%% for %d min", percentage, duration)); } } catch (CommandException e) { return e.toCommandResult(); } } private void enterTbrMenu(RuffyScripter scripter) { scripter.verifyMenuIsDisplayed(MenuType.MAIN_MENU); scripter.navigateToMenu(MenuType.TBR_MENU); scripter.verifyMenuIsDisplayed(MenuType.TBR_MENU); scripter.pressCheckKey(); scripter.waitForMenuUpdate(); scripter.verifyMenuIsDisplayed(MenuType.TBR_SET); } private void inputTbrPercentage(RuffyScripter scripter) { scripter.verifyMenuIsDisplayed(MenuType.TBR_SET); long currentPercent = readDisplayedTbrPercentage(scripter); log.debug("Current TBR %: " + currentPercent); long percentageChange = percentage - currentPercent; long percentageSteps = percentageChange / 10; boolean increasePercentage = true; if (percentageSteps < 0) { increasePercentage = false; percentageSteps = Math.abs(percentageSteps); } log.debug("Pressing " + (increasePercentage ? "up" : "down") + " " + percentageSteps + " times"); for (int i = 0; i < percentageSteps; i++) { scripter.verifyMenuIsDisplayed(MenuType.TBR_SET); if (increasePercentage) scripter.pressUpKey(); else scripter.pressDownKey(); SystemClock.sleep(100); log.debug("Push #" + (i + 1)); } } private void verifyDisplayedTbrPercentage(RuffyScripter scripter) { scripter.verifyMenuIsDisplayed(MenuType.TBR_SET); long displayedPercentage = readDisplayedTbrPercentage(scripter); if (displayedPercentage != this.percentage) { log.debug("Final displayed TBR percentage: " + displayedPercentage); throw new CommandException().message("Failed to set TBR percentage"); } } private long readDisplayedTbrPercentage(RuffyScripter scripter) { Object percentageObj = scripter.currentMenu.getAttribute(MenuAttribute.BASAL_RATE); // this as a bit hacky, the display value is blinking, so we might catch that, so // keep trying till we get the Double we want while (!(percentageObj instanceof Double)) { scripter.waitForMenuUpdate(); percentageObj = scripter.currentMenu.getAttribute(MenuAttribute.BASAL_RATE); } return ((Double) percentageObj).longValue(); } private void inputTbrDuration(RuffyScripter scripter) { scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION); long currentDuration = readDisplayedTbrDuration(scripter); if (currentDuration % 15 != 0) { // The duration displayed is how long an active TBR will still run, // which might be something like 0:13, hence not in 15 minute steps. // Pressing up will go to the next higher 15 minute step. // Don't press down, from 0:13 it can't go down, so press up. // Pressing up from 23:59 works to go to 24:00. scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION); scripter.pressUpKey(); scripter.waitForMenuUpdate(); currentDuration = readDisplayedTbrDuration(scripter); } log.debug("Current TBR duration: " + currentDuration); long durationChange = duration - currentDuration; long durationSteps = durationChange / 15; boolean increaseDuration = true; if (durationSteps < 0) { increaseDuration = false; durationSteps = Math.abs(durationSteps); } log.debug("Pressing " + (increaseDuration ? "up" : "down") + " " + durationSteps + " times"); for (int i = 0; i < durationSteps; i++) { scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION); if (increaseDuration) scripter.pressUpKey(); else scripter.pressDownKey(); SystemClock.sleep(100); log.debug("Push #" + (i + 1)); } } private void verifyDisplayedTbrDuration(RuffyScripter scripter) { scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION); long displayedDuration = readDisplayedTbrDuration(scripter); if (displayedDuration != duration) { log.debug("Final displayed TBR duration: " + displayedDuration); throw new CommandException().message("Failed to set TBR duration"); } } private long readDisplayedTbrDuration(RuffyScripter scripter) { scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION); Object durationObj = scripter.currentMenu.getAttribute(MenuAttribute.RUNTIME); // this as a bit hacky, the display value is blinking, so we might catch that, so // keep trying till we get the Double we want while (!(durationObj instanceof MenuTime)) { scripter.waitForMenuUpdate(); durationObj = scripter.currentMenu.getAttribute(MenuAttribute.RUNTIME); } MenuTime duration = (MenuTime) durationObj; return duration.getHour() * 60 + duration.getMinute(); } private void cancelTbrAndConfirmCancellationWarning(RuffyScripter scripter) { // confirm entered TBR scripter.verifyMenuIsDisplayed(MenuType.TBR_SET); scripter.pressCheckKey(); // we could read remaining duration from MAIN_MENU, but but the time we're here, // we could have moved from 0:02 to 0:01, so instead, check if a "TBR CANCELLED alert" // is raised and if so dismiss it long inTwoSeconds = System.currentTimeMillis() + 5 * 1000; boolean alertProcessed = false; while (System.currentTimeMillis() < inTwoSeconds && !alertProcessed) { if (scripter.currentMenu.getType() == MenuType.WARNING_OR_ERROR) { // check the raised alarm is TBR CANCELLED. // note that the message is permanently displayed, while the error code is blinking. // wait till the error code can be read results in the code hanging, despite // menu updates coming in, so just check the message String errorMsg = (String) scripter.currentMenu.getAttribute(MenuAttribute.MESSAGE); if (!errorMsg.equals("TBR CANCELLED")) { throw new CommandException().success(false).enacted(false) .message("An alert other than the expected TBR CANCELLED was raised by the pump: " + errorMsg + ". Please check the pump."); } // confirm "TBR CANCELLED alert" scripter.verifyMenuIsDisplayed(MenuType.WARNING_OR_ERROR); scripter.pressCheckKey(); // dismiss "TBR CANCELLED alert" scripter.verifyMenuIsDisplayed(MenuType.WARNING_OR_ERROR); scripter.pressCheckKey(); scripter.waitForMenuToBeLeft(MenuType.WARNING_OR_ERROR); alertProcessed = true; } SystemClock.sleep(10); } } private void verifyMainMenuShowsNoActiveTbr(RuffyScripter scripter) { scripter.verifyMenuIsDisplayed(MenuType.MAIN_MENU); Double tbrPercentage = (Double) scripter.currentMenu.getAttribute(MenuAttribute.TBR); boolean runtimeDisplayed = scripter.currentMenu.attributes().contains(MenuAttribute.RUNTIME); if (tbrPercentage != 100 || runtimeDisplayed) { throw new CommandException().message("Cancelling TBR failed, TBR is still set according to MAIN_MENU"); } } private void verifyMainMenuShowsExpectedTbrActive(RuffyScripter scripter) { scripter.verifyMenuIsDisplayed(MenuType.MAIN_MENU); // new TBR set; percentage and duration must be displayed ... if (!scripter.currentMenu.attributes().contains(MenuAttribute.TBR) || !scripter.currentMenu.attributes().contains(MenuAttribute.TBR)) { throw new CommandException().message("Setting TBR failed, according to MAIN_MENU no TBR is active"); } Double mmTbrPercentage = (Double) scripter.currentMenu.getAttribute(MenuAttribute.TBR); MenuTime mmTbrDuration = (MenuTime) scripter.currentMenu.getAttribute(MenuAttribute.RUNTIME); // ... and be the same as what we set // note that displayed duration might have already counted down, e.g. from 30 minutes to // 29 minutes and 59 seconds, so that 29 minutes are displayed int mmTbrDurationInMinutes = mmTbrDuration.getHour() * 60 + mmTbrDuration.getMinute(); if (mmTbrPercentage != percentage || (mmTbrDurationInMinutes != duration && mmTbrDurationInMinutes + 1 != duration)) { throw new CommandException().message("Setting TBR failed, TBR in MAIN_MENU differs from expected"); } } @Override public String toString() { return "SetTbrCommand{" + "percentage=" + percentage + ", duration=" + duration + '}'; } }
app/src/main/java/de/jotomo/ruffyscripter/commands/SetTbrCommand.java
package de.jotomo.ruffyscripter.commands; import android.os.SystemClock; import org.monkey.d.ruffy.ruffy.driver.display.MenuAttribute; import org.monkey.d.ruffy.ruffy.driver.display.MenuType; import org.monkey.d.ruffy.ruffy.driver.display.menu.MenuTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Locale; import de.jotomo.ruffyscripter.PumpState; import de.jotomo.ruffyscripter.RuffyScripter; public class SetTbrCommand implements Command { private static final Logger log = LoggerFactory.getLogger(SetTbrCommand.class); private final long percentage; private final long duration; public SetTbrCommand(long percentage, long duration) { this.percentage = percentage; this.duration = duration; } @Override public List<String> validateArguments() { List<String> violations = new ArrayList<>(); if (percentage % 10 != 0) { violations.add("TBR percentage must be set in 10% steps"); } if (percentage < 0 || percentage > 500) { violations.add("TBR percentage must be within 0-500%"); } if (percentage != 100) { if (duration % 15 != 0) { violations.add("TBR duration can only be set in 15 minute steps"); } if (duration > 60 * 24) { violations.add("Maximum TBR duration is 24 hours"); } } if (percentage == 0 && duration > 120) { violations.add("Max allowed zero-temp duration is 2h"); } return violations; } @Override public CommandResult execute(RuffyScripter scripter, PumpState initialPumpState) { try { enterTbrMenu(scripter); boolean tbrPercentInputSuccess = false; int tbrPercentInputRetries = 2; while (!tbrPercentInputSuccess) { try { inputTbrPercentage(scripter); SystemClock.sleep(750); verifyDisplayedTbrPercentage(scripter); tbrPercentInputSuccess = true; } catch (CommandException e) { if (tbrPercentInputRetries >= 0) { log.warn("Setting TBR percentage failed, retrying", e); tbrPercentInputRetries--; } else { throw e; } } } if (percentage == 100) { cancelTbrAndConfirmCancellationWarning(scripter); } else { // switch to TBR_DURATION menu by pressing menu key scripter.verifyMenuIsDisplayed(MenuType.TBR_SET); scripter.pressMenuKey(); scripter.waitForMenuUpdate(); scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION); boolean tbrDurationSuccess = false; int tbrDurationRetries = 2; while (!tbrDurationSuccess) { try { inputTbrDuration(scripter); SystemClock.sleep(750); verifyDisplayedTbrDuration(scripter); tbrDurationSuccess = true; } catch (CommandException e) { if (tbrDurationRetries >= 0) { log.warn("Setting TBR duration failed, retrying", e); tbrDurationRetries--; } else { throw e; } } } // confirm TBR scripter.pressCheckKey(); SystemClock.sleep(500); } scripter.verifyMenuIsDisplayed(MenuType.MAIN_MENU, "Pump did not return to MAIN_MEU after setting TBR. " + "Check pump manually, the TBR might not have been set/cancelled."); // check main menu shows the same values we just set if (percentage == 100) { verifyMainMenuShowsNoActiveTbr(scripter); return new CommandResult().success(true).enacted(true).message("TBR was cancelled"); } else { verifyMainMenuShowsExpectedTbrActive(scripter); return new CommandResult().success(true).enacted(true).message( String.format(Locale.US, "TBR set to %d%% for %d min", percentage, duration)); } } catch (CommandException e) { return e.toCommandResult(); } } private void enterTbrMenu(RuffyScripter scripter) { scripter.verifyMenuIsDisplayed(MenuType.MAIN_MENU); scripter.navigateToMenu(MenuType.TBR_MENU); scripter.verifyMenuIsDisplayed(MenuType.TBR_MENU); scripter.pressCheckKey(); scripter.waitForMenuUpdate(); scripter.verifyMenuIsDisplayed(MenuType.TBR_SET); } private void inputTbrPercentage(RuffyScripter scripter) { scripter.verifyMenuIsDisplayed(MenuType.TBR_SET); long currentPercent = readDisplayedTbrPercentage(scripter); log.debug("Current TBR %: " + currentPercent); long percentageChange = percentage - currentPercent; long percentageSteps = percentageChange / 10; boolean increasePercentage = true; if (percentageSteps < 0) { increasePercentage = false; percentageSteps = Math.abs(percentageSteps); } log.debug("Pressing " + (increasePercentage ? "up" : "down") + " " + percentageSteps + " times"); for (int i = 0; i < percentageSteps; i++) { scripter.verifyMenuIsDisplayed(MenuType.TBR_SET); if (increasePercentage) scripter.pressUpKey(); else scripter.pressDownKey(); SystemClock.sleep(100); log.debug("Push #" + (i + 1)); } } private void verifyDisplayedTbrPercentage(RuffyScripter scripter) { scripter.verifyMenuIsDisplayed(MenuType.TBR_SET); long displayedPercentage = readDisplayedTbrPercentage(scripter); if (displayedPercentage != this.percentage) { log.debug("Final displayed TBR percentage: " + displayedPercentage); throw new CommandException().message("Failed to set TBR percentage"); } } private long readDisplayedTbrPercentage(RuffyScripter scripter) { Object percentageObj = scripter.currentMenu.getAttribute(MenuAttribute.BASAL_RATE); // this as a bit hacky, the display value is blinking, so we might catch that, so // keep trying till we get the Double we want while (!(percentageObj instanceof Double)) { scripter.waitForMenuUpdate(); percentageObj = scripter.currentMenu.getAttribute(MenuAttribute.BASAL_RATE); } return ((Double) percentageObj).longValue(); } private void inputTbrDuration(RuffyScripter scripter) { scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION); long currentDuration = readDisplayedTbrDuration(scripter); if (currentDuration % 15 != 0) { // The duration displayed is how long an active TBR will still run, // which might be something like 0:13, hence not in 15 minute steps. // Pressing up will go to the next higher 15 minute step. // Don't press down, from 0:13 it can't go down, so press up. // Pressing up from 23:59 works to go to 24:00. scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION); scripter.pressUpKey(); scripter.waitForMenuUpdate(); currentDuration = readDisplayedTbrDuration(scripter); } log.debug("Current TBR duration: " + currentDuration); long durationChange = duration - currentDuration; long durationSteps = durationChange / 15; boolean increaseDuration = true; if (durationSteps < 0) { increaseDuration = false; durationSteps = Math.abs(durationSteps); } log.debug("Pressing " + (increaseDuration ? "up" : "down") + " " + durationSteps + " times"); for (int i = 0; i < durationSteps; i++) { scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION); if (increaseDuration) scripter.pressUpKey(); else scripter.pressDownKey(); SystemClock.sleep(100); log.debug("Push #" + (i + 1)); } } private void verifyDisplayedTbrDuration(RuffyScripter scripter) { scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION); long displayedDuration = readDisplayedTbrDuration(scripter); if (displayedDuration != duration) { log.debug("Final displayed TBR duration: " + displayedDuration); throw new CommandException().message("Failed to set TBR duration"); } } private long readDisplayedTbrDuration(RuffyScripter scripter) { scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION); Object durationObj = scripter.currentMenu.getAttribute(MenuAttribute.RUNTIME); // this as a bit hacky, the display value is blinking, so we might catch that, so // keep trying till we get the Double we want while (!(durationObj instanceof MenuTime)) { scripter.waitForMenuUpdate(); durationObj = scripter.currentMenu.getAttribute(MenuAttribute.RUNTIME); } MenuTime duration = (MenuTime) durationObj; return duration.getHour() * 60 + duration.getMinute(); } private void cancelTbrAndConfirmCancellationWarning(RuffyScripter scripter) { // confirm entered TBR scripter.verifyMenuIsDisplayed(MenuType.TBR_SET); scripter.pressCheckKey(); // we could read remaining duration from MAIN_MENU, but but the time we're here, // we could have moved from 0:02 to 0:01, so instead, check if a "TBR CANCELLED alert" // is raised and if so dismiss it long inTwoSeconds = System.currentTimeMillis() + 5 * 1000; boolean alertProcessed = false; while (System.currentTimeMillis() < inTwoSeconds && !alertProcessed) { if (scripter.currentMenu.getType() == MenuType.WARNING_OR_ERROR) { // check the raised alarm is TBR CANCELLED. // note that the message is permanently displayed, while the error code is blinking. // wait till the error code can be read results in the code hanging, despite // menu updates coming in, so just check the message String errorMsg = (String) scripter.currentMenu.getAttribute(MenuAttribute.MESSAGE); if (!errorMsg.equals("TBR CANCELLED")) { throw new CommandException().success(false).enacted(false) .message("An alert other than the expected TBR CANCELLED was raised by the pump: " + errorMsg + ". Please check the pump."); } // confirm "TBR CANCELLED alert" scripter.verifyMenuIsDisplayed(MenuType.WARNING_OR_ERROR); scripter.pressCheckKey(); // dismiss "TBR CANCELLED alert" scripter.verifyMenuIsDisplayed(MenuType.WARNING_OR_ERROR); scripter.pressCheckKey(); scripter.waitForMenuToBeLeft(MenuType.WARNING_OR_ERROR); alertProcessed = true; } SystemClock.sleep(10); } } private void verifyMainMenuShowsNoActiveTbr(RuffyScripter scripter) { scripter.verifyMenuIsDisplayed(MenuType.MAIN_MENU); Double tbrPercentage = (Double) scripter.currentMenu.getAttribute(MenuAttribute.TBR); boolean runtimeDisplayed = scripter.currentMenu.attributes().contains(MenuAttribute.RUNTIME); if (tbrPercentage != 100 || runtimeDisplayed) { throw new CommandException().message("Cancelling TBR failed, TBR is still set according to MAIN_MENU"); } } private void verifyMainMenuShowsExpectedTbrActive(RuffyScripter scripter) { scripter.verifyMenuIsDisplayed(MenuType.MAIN_MENU); // new TBR set; percentage and duration must be displayed ... if (!scripter.currentMenu.attributes().contains(MenuAttribute.TBR) || !scripter.currentMenu.attributes().contains(MenuAttribute.TBR)) { throw new CommandException().message("Setting TBR failed, according to MAIN_MENU no TBR is active"); } Double mmTbrPercentage = (Double) scripter.currentMenu.getAttribute(MenuAttribute.TBR); MenuTime mmTbrDuration = (MenuTime) scripter.currentMenu.getAttribute(MenuAttribute.RUNTIME); // ... and be the same as what we set // note that displayed duration might have already counted down, e.g. from 30 minutes to // 29 minutes and 59 seconds, so that 29 minutes are displayed int mmTbrDurationInMinutes = mmTbrDuration.getHour() * 60 + mmTbrDuration.getMinute(); if (mmTbrPercentage != percentage || (mmTbrDurationInMinutes != duration && mmTbrDurationInMinutes + 1 != duration)) { throw new CommandException().message("Setting TBR failed, TBR in MAIN_MENU differs from expected"); } } @Override public String toString() { return "SetTbrCommand{" + "percentage=" + percentage + ", duration=" + duration + '}'; } }
SetTbrCommand: replace static wait with dynamic wait to have completionDate more accurate.
app/src/main/java/de/jotomo/ruffyscripter/commands/SetTbrCommand.java
SetTbrCommand: replace static wait with dynamic wait to have completionDate more accurate.
Java
agpl-3.0
error: pathspec 'src/de/bitdroid/flooding/ods/cep/CepManager.java' did not match any file(s) known to git
62ea5cc14d707e162c1312deb716c2ce582627a6
1
jvalue/hochwasser-app,jvalue/hochwasser-app,Haroenv/hochwasser-app,Haroenv/hochwasser-app
package de.bitdroid.flooding.ods.cep; import java.net.URL; import android.content.Context; import android.content.SharedPreferences; import de.bitdroid.flooding.utils.Assert; public final class CepManager { private static final String PREFS_NAME = CepManager.class.getName(); private static final String KEY_SERVER_NAME = "serverName"; private static CepManager instance; public static CepManager getInstance(Context context) { Assert.assertNotNull(context); synchronized(CepManager.class) { if (instance == null) instance = new CepManager(context); return instance; } } private final Context context; private CepManager(Context context) { this.context = context; } /** * Set the name for the CEP server. */ public void setCepServerName(String cepServerName) { Assert.assertNotNull(cepServerName); try { URL checkUrl = new URL(cepServerName); checkUrl.toURI(); } catch (Exception e) { throw new IllegalArgumentException(e); } SharedPreferences.Editor editor = getSharedPreferences().edit(); editor.putString(KEY_SERVER_NAME, cepServerName); editor.commit(); } /** * Returns the CEP server name currently being used for all interaction with * the CEP server. */ public String getCepServerName() { return getSharedPreferences().getString(KEY_SERVER_NAME, null); } private SharedPreferences getSharedPreferences() { return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); } }
src/de/bitdroid/flooding/ods/cep/CepManager.java
ods: added basic CepManager
src/de/bitdroid/flooding/ods/cep/CepManager.java
ods: added basic CepManager
Java
agpl-3.0
error: pathspec 'GAE/src/test/java/org/akvo/flow/util/FlowJsonObjectWriterTests.java' did not match any file(s) known to git
a776b5600ca8623811bb219948d94cee59252214
1
akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow
/* * Copyright (C) 2019 Stichting Akvo (Akvo Foundation) * * This file is part of Akvo FLOW. * * Akvo FLOW is free software: you can redistribute it and modify it under the terms of * the GNU Affero General Public License (AGPL) as published by the Free Software Foundation, * either version 3 of the License or any later version. * * Akvo FLOW is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License included below for more details. * * The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>. */ package test.java.org.akvo.flow.util; import com.gallatinsystems.survey.domain.Question; import org.akvo.flow.util.FlowJsonObjectWriter; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.*; import static org.junit.jupiter.api.Assertions.assertEquals; class FlowJsonObjectWriterTests { @Test void testComplexJsonObject() { Map<String, Object> complexJsonObject = new LinkedHashMap<>(); complexJsonObject.put("nullList", null); complexJsonObject.put("emptyList", new ArrayList<>()); List<Integer> listOfNumbers = new ArrayList<>(); listOfNumbers.add(1); listOfNumbers.add(2); listOfNumbers.add(3); complexJsonObject.put("listOfNumbers",listOfNumbers); List<Object> firstList = new ArrayList<>(); firstList.add(5345); firstList.add(6587); firstList.add(9987); List<Object> secondList = new ArrayList<>(); secondList.add("tea"); secondList.add("coffee"); Map<String, List<Object>> mapOfLists = new LinkedHashMap<>(); mapOfLists.put("firstList", firstList); mapOfLists.put("secondList", secondList); complexJsonObject.put("mapOfLists", mapOfLists); FlowJsonObjectWriter writer = new FlowJsonObjectWriter(); String jsonString = null; try { jsonString = writer.writeAsString(complexJsonObject); } catch (IOException e) { // } String jsonStringExpected = "{\"nullList\":null,\"emptyList\":[],\"listOfNumbers\":[1,2,3],\"mapOfLists\":{\"firstList\":[5345,6587,9987],\"secondList\":[\"tea\",\"coffee\"]}}"; assertEquals(jsonStringExpected, jsonString); } @Test void testWriteSimpleJsonObjectWithExcludeNonNull() { Question question = new Question(); question.setText("First Question"); question.setOrder(0); question.setType(Question.Type.FREE_TEXT); question.setAllowOtherFlag(true); FlowJsonObjectWriter writer = new FlowJsonObjectWriter().withExcludeNullValues(); String jsonString = null; try { jsonString = writer.writeAsString(question); } catch (IOException e) { // } String jsonStringExpected = "{\"type\":\"FREE_TEXT\",\"text\":\"First Question\",\"allowOtherFlag\":true,\"collapseable\":false,\"immutable\":false,\"order\":0}"; assertEquals(jsonStringExpected, jsonString); } }
GAE/src/test/java/org/akvo/flow/util/FlowJsonObjectWriterTests.java
[#2896] Add tests for the FlowJsonObjectWriter
GAE/src/test/java/org/akvo/flow/util/FlowJsonObjectWriterTests.java
[#2896] Add tests for the FlowJsonObjectWriter
Java
agpl-3.0
error: pathspec 'viewer-config-persistence/src/main/java/nl/b3p/viewer/config/services/SolrConfiguration.java' did not match any file(s) known to git
ad5dd115a53ad660b3f58b0b4fadc848bf79d68e
1
mvdstruijk/flamingo,flamingo-geocms/flamingo,flamingo-geocms/flamingo,mvdstruijk/flamingo,B3Partners/flamingo,mvdstruijk/flamingo,B3Partners/flamingo,B3Partners/flamingo,mvdstruijk/flamingo,flamingo-geocms/flamingo,flamingo-geocms/flamingo,B3Partners/flamingo
/* * Copyright (C) 2013 B3Partners B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nl.b3p.viewer.config.services; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.ManyToOne; /** * * @author Meine Toonen */ @Entity public class SolrConfiguration { @Id private Long id; @ManyToOne(fetch = FetchType.LAZY) private FeatureSource featureSource; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public FeatureSource getFeatureSource() { return featureSource; } public void setFeatureSource(FeatureSource featureSource) { this.featureSource = featureSource; } }
viewer-config-persistence/src/main/java/nl/b3p/viewer/config/services/SolrConfiguration.java
Entity for searchconfiguration created.
viewer-config-persistence/src/main/java/nl/b3p/viewer/config/services/SolrConfiguration.java
Entity for searchconfiguration created.
Java
lgpl-2.1
892aae16e9f3b282eea5488b19b942eca8eafedf
0
svartika/ccnx,svartika/ccnx,cawka/ndnx,cawka/ndnx,svartika/ccnx,svartika/ccnx,svartika/ccnx,cawka/ndnx,cawka/ndnx,svartika/ccnx,svartika/ccnx,cawka/ndnx
javasrc/src/org/ccnx/ccn/test/repo/Misc.java
/* * A CCNx library test. * * Copyright (C) 2008, 2009 Palo Alto Research Center, Inc. * * This work is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as published by the * Free Software Foundation. * This work is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ package org.ccnx.ccn.test.repo; import java.util.Comparator; import java.util.TreeSet; import org.junit.BeforeClass; import org.junit.Test; /** * Utility for repository tests. * */ public class Misc { public static class CompareTester implements Comparable<CompareTester> { String _name; String _label; int _age; public CompareTester(String name, String label, int age) { _age = age; _name = name; _label = label; } @Override public String toString() { return "Name: " + _name + " Label: " + _label + " Age: " + _age; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + _age; result = prime * result + ((_label == null) ? 0 : _label.hashCode()); result = prime * result + ((_name == null) ? 0 : _name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CompareTester other = (CompareTester) obj; if (_age != other._age) return false; if (_label == null) { if (other._label != null) return false; } else if (!_label.equals(other._label)) return false; if (_name == null) { if (other._name != null) return false; } else if (!_name.equals(other._name)) return false; return true; } /* @Override public int compareTo(Object obj) { if (this == obj) return 0; if (obj == null) return -1; if (getClass() != obj.getClass()) return 1; CompareTester other = (CompareTester) obj; return (compareTo(other)); } */ public int compareTo(CompareTester other) { int compared = _name.compareTo(other._name); if (0 != compared) return compared; compared = _label.compareTo(other._label); if (0 != compared) return compared; if (_age > other._age) return 1; else if (_age < other._age) return -1; return 0; } public int compareToNameOnly(Object obj) { if (this == obj) return 0; if (obj == null) return -1; if (getClass() != obj.getClass()) return 1; CompareTester other = (CompareTester) obj; int compared = _name.compareTo(other._name); if (0 != compared) return compared; return 0; } public int compareToIgnoreAge(Object obj) { if (this == obj) return 0; if (obj == null) return -1; if (getClass() != obj.getClass()) return 1; CompareTester other = (CompareTester) obj; int compared = _name.compareTo(other._name); if (0 != compared) return compared; compared = _label.compareTo(other._label); if (0 != compared) return compared; return 0; } } public static class IgnoreAgeComparator implements Comparator<CompareTester> { public int compare(CompareTester o1, CompareTester o2) { if (o1 != null) { return o1.compareToIgnoreAge(o2); } if (o2 != null) { return o2.compareToIgnoreAge(o1); } return 0; // both null } } public static class NameOnlyComparator implements Comparator<CompareTester> { public int compare(CompareTester o1, CompareTester o2) { if (o1 != null) { return o1.compareToNameOnly(o2); } if (o2 != null) { return o2.compareToNameOnly(o1); } return 0; // both null } } @BeforeClass public static void setUpBeforeClass() throws Exception { } @Test public void miscTest() { TreeSet<CompareTester> standardCompare = new TreeSet<CompareTester>(); TreeSet<CompareTester> ignoreAge = new TreeSet<CompareTester>(new IgnoreAgeComparator()); TreeSet<CompareTester> nameOnly = new TreeSet<CompareTester>(new NameOnlyComparator()); CompareTester [] theData = new CompareTester[]{ new CompareTester("Name", "Label", 21), new CompareTester("Name", "Label", 21), new CompareTester("AnotherName", "ADifferentLabel", 23), new CompareTester("Name", "ADifferentLabel", 23), new CompareTester("Name", "YetADifferentLabel", 25), new CompareTester("Name", "ADifferentLabel", 47), new CompareTester("Alex", "ADifferentLabel", 47), new CompareTester("ProbeName", "ProbeLabel", 40)}; for (CompareTester tester : theData) { standardCompare.add(tester); ignoreAge.add(tester); nameOnly.add(tester); } System.out.println("Added " + theData.length + " elements to sets with different comparators."); System.out.println("Standard comparator kept: " + standardCompare.size()); System.out.println("Ignore age comparator kept: " + ignoreAge.size()); System.out.println("Name only comparator kept: " + nameOnly.size()); CompareTester [] probes = new CompareTester[]{ new CompareTester("AnotherName", "Foodle", 106), new CompareTester("Alex", "ADifferentLabel", 47), new CompareTester("ProbeName", "ProbeLabel", 42)}; for (CompareTester probe : probes) { System.out.println("Probe: " + probe); System.out.println("Standard comparator contains: " + standardCompare.contains(probe)); System.out.println("Ignore age comparator contains: " + ignoreAge.contains(probe)); System.out.println("Name-only comparator contains: " + nameOnly.contains(probe)); } } }
refs #100374 Misc.java is unused and hasn't been for a long time - removing it
javasrc/src/org/ccnx/ccn/test/repo/Misc.java
refs #100374 Misc.java is unused and hasn't been for a long time - removing it
Java
unlicense
error: pathspec 'fr.mvanbesien.projecteuler/src/fr/mvanbesien/projecteuler/from041to060/Problem052.java' did not match any file(s) known to git
fe2955cf8ef1a303e6e9a062d80f25c2b8e10d64
1
mvanbesien/projecteuler
package fr.mvanbesien.projecteuler.from041to060; import java.util.Arrays; import java.util.concurrent.Callable; public class Problem052 implements Callable<Long> { public static void main(String[] args) throws Exception { long nanotime = System.nanoTime(); System.out.println("Answer is " + new Problem052().call()); System.out.println(String.format("Executed in %d �s", (System.nanoTime() - nanotime) / 1000)); } @Override public Long call() throws Exception { for (int i = 125874; true; i = next(i)) { if (haveSameDigits(i, 2 * i, 3 * i, 4 * i, 5 * i, 6 * i)) { return (long) i; } } } private boolean haveSameDigits(int... values) { if (values.length == 0) return true; String[] s = new String[values.length]; int length = String.valueOf(values[0]).length(); for (int i = 0; i < values.length; i++) { String valueOf = String.valueOf(values[i]); if (valueOf.length() != length) return false; s[i] = new String(newSortedCharArray(valueOf)); } for (int i = 1;i<length;i++) { for (int j = 1;j<s.length;j++) { if (s[j].charAt(i) != s[0].charAt(i)) return false; } } return true; } private int next(int number) { int temp = number + 1; while (!hasUniqueDigits(temp)) { temp++; } return temp; } private boolean hasUniqueDigits(int number) { char[] values = String.valueOf(number).toCharArray(); Arrays.sort(values); for (int i = 0; i < values.length - 1; i++) { if (values[i] == values[i + 1]) return false; } return true; } private char[] newSortedCharArray(String s) { char[] charArray = s.toCharArray(); Arrays.sort(charArray); return charArray; } }
fr.mvanbesien.projecteuler/src/fr/mvanbesien/projecteuler/from041to060/Problem052.java
Added problem 52
fr.mvanbesien.projecteuler/src/fr/mvanbesien/projecteuler/from041to060/Problem052.java
Added problem 52
Java
apache-2.0
375b94d8e039beb83aa552cdfc0c82eb3a6b1fd1
0
allotria/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,xfournet/intellij-community,da1z/intellij-community,da1z/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,da1z/intellij-community,xfournet/intellij-community,da1z/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,da1z/intellij-community,xfournet/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,allotria/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,allotria/intellij-community,da1z/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,allotria/intellij-community
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.siyeh.ig; import com.intellij.codeHighlighting.HighlightDisplayLevel; import com.intellij.codeInsight.daemon.HighlightDisplayKey; import com.intellij.codeInspection.InspectionProfileEntry; import com.intellij.codeInspection.ex.InspectionProfileImpl; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.util.text.StringUtil; import com.intellij.profile.codeInspection.ProjectInspectionProfileManager; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiClass; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase; import com.intellij.util.ArrayUtil; import org.intellij.lang.annotations.Language; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * @author Bas Leijdekkers */ public abstract class LightInspectionTestCase extends LightCodeInsightFixtureTestCase { @Override protected void setUp() throws Exception { super.setUp(); for (String environmentClass : getEnvironmentClasses()) { myFixture.addClass(environmentClass); } final InspectionProfileEntry inspection = getInspection(); if (inspection != null) { myFixture.enableInspections(inspection); final Project project = myFixture.getProject(); final HighlightDisplayKey displayKey = HighlightDisplayKey.find(inspection.getShortName()); final InspectionProfileImpl currentProfile = ProjectInspectionProfileManager.getInstance(project).getCurrentProfile(); final HighlightDisplayLevel errorLevel = currentProfile.getErrorLevel(displayKey, null); if (errorLevel == HighlightDisplayLevel.DO_NOT_SHOW) { currentProfile.setErrorLevel(displayKey, HighlightDisplayLevel.WARNING, project); } } Sdk sdk = ModuleRootManager.getInstance(ModuleManager.getInstance(getProject()).getModules()[0]).getSdk(); if (JAVA_1_7.getSdk().getName().equals(sdk == null ? null : sdk.getName())) { PsiClass object = JavaPsiFacade.getInstance(getProject()).findClass("java.lang.Object", GlobalSearchScope.allScope(getProject())); assertNotNull(object); PsiClass component = JavaPsiFacade.getInstance(getProject()).findClass("java.awt.Component", GlobalSearchScope.allScope(getProject())); assertNotNull(component); } } @Nullable protected abstract InspectionProfileEntry getInspection(); @Language("JAVA") @SuppressWarnings("LanguageMismatch") protected String[] getEnvironmentClasses() { return ArrayUtil.EMPTY_STRING_ARRAY; } protected void addEnvironmentClass(@Language("JAVA") @NotNull String classText) { myFixture.addClass(classText); } protected final void doStatementTest(@Language(value="JAVA", prefix="@SuppressWarnings(\"all\") class X { void m() {", suffix="}}") @NotNull String statementText) { doTest("class X { void m() {" + statementText + "}}"); } protected final void doMemberTest(@Language(value="JAVA", prefix="@SuppressWarnings(\"all\") class X {", suffix="}") @NotNull String memberText) { doTest("class X {" + memberText + "}"); } protected final void doTest(@Language("JAVA") @NotNull String classText) { doTest(classText, "X.java"); } protected final void doTest(@Language("JAVA") @NotNull String classText, String fileName) { final StringBuilder newText = new StringBuilder(); int start = 0; int end = classText.indexOf("/*"); while (end >= 0) { newText.append(classText, start, end); start = end + 2; end = classText.indexOf("*/", end); if (end < 0) { throw new IllegalArgumentException("invalid class text"); } final String text = classText.substring(start, end); if (text.isEmpty()) { newText.append("</warning>"); } else if ("!".equals(text)) { newText.append("</error>"); } else if ("_".equals(text)) { newText.append("<caret>"); } else if (text.startsWith("!")) { newText.append("<error descr=\"").append(text.substring(1)).append("\">"); } else { newText.append("<warning descr=\"").append(text).append("\">"); } start = end + 2; end = classText.indexOf("/*", end + 1); } newText.append(classText, start, classText.length()); myFixture.configureByText(fileName, newText.toString()); myFixture.testHighlighting(true, false, false); } @Override protected String getBasePath() { final InspectionProfileEntry inspection = getInspection(); assertNotNull("File-based tests should either return an inspection or override this method", inspection); final String className = inspection.getClass().getName(); final String[] words = className.split("\\."); final StringBuilder basePath = new StringBuilder("/plugins/InspectionGadgets/test/"); final int lastWordIndex = words.length - 1; for (int i = 0; i < lastWordIndex; i++) { String word = words[i]; if (word.equals("ig")) { //noinspection SpellCheckingInspection word = "igtest"; } basePath.append(word).append('/'); } String lastWord = words[lastWordIndex]; lastWord = StringUtil.trimEnd(lastWord, "Inspection"); final int length = lastWord.length(); boolean upperCase = false; for (int i = 0; i < length; i++) { final char ch = lastWord.charAt(i); if (Character.isUpperCase(ch)) { if (!upperCase) { upperCase = true; if (i != 0) { basePath.append('_'); } } basePath.append(Character.toLowerCase(ch)); } else { upperCase = false; basePath.append(ch); } } return basePath.toString(); } protected final void doTest() { doNamedTest(getTestName(false)); } protected final void doNamedTest(String name) { myFixture.configureByFile(name + ".java"); myFixture.testHighlighting(true, false, false); } }
java/testFramework/src/com/siyeh/ig/LightInspectionTestCase.java
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.siyeh.ig; import com.intellij.codeHighlighting.HighlightDisplayLevel; import com.intellij.codeInsight.daemon.HighlightDisplayKey; import com.intellij.codeInspection.InspectionProfileEntry; import com.intellij.codeInspection.ex.InspectionProfileImpl; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.util.text.StringUtil; import com.intellij.profile.codeInspection.ProjectInspectionProfileManager; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiClass; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase; import com.intellij.util.ArrayUtil; import org.intellij.lang.annotations.Language; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * @author Bas Leijdekkers */ public abstract class LightInspectionTestCase extends LightCodeInsightFixtureTestCase { @Override protected void setUp() throws Exception { super.setUp(); for (String environmentClass : getEnvironmentClasses()) { myFixture.addClass(environmentClass); } final InspectionProfileEntry inspection = getInspection(); if (inspection != null) { myFixture.enableInspections(inspection); final Project project = myFixture.getProject(); final HighlightDisplayKey displayKey = HighlightDisplayKey.find(inspection.getShortName()); final InspectionProfileImpl currentProfile = ProjectInspectionProfileManager.getInstance(project).getCurrentProfile(); final HighlightDisplayLevel errorLevel = currentProfile.getErrorLevel(displayKey, null); if (errorLevel == HighlightDisplayLevel.DO_NOT_SHOW) { currentProfile.setErrorLevel(displayKey, HighlightDisplayLevel.WARNING, project); } } Sdk sdk = ModuleRootManager.getInstance(ModuleManager.getInstance(getProject()).getModules()[0]).getSdk(); if (JAVA_1_7.getSdk().getName().equals(sdk == null ? null : sdk.getName())) { PsiClass object = JavaPsiFacade.getInstance(getProject()).findClass("java.lang.Object", GlobalSearchScope.allScope(getProject())); assertNotNull(object); PsiClass component = JavaPsiFacade.getInstance(getProject()).findClass("java.awt.Component", GlobalSearchScope.allScope(getProject())); assertNotNull(component); } } @Nullable protected abstract InspectionProfileEntry getInspection(); @Language("JAVA") @SuppressWarnings("LanguageMismatch") protected String[] getEnvironmentClasses() { return ArrayUtil.EMPTY_STRING_ARRAY; } protected void addEnvironmentClass(@Language("JAVA") @NotNull String classText) { myFixture.addClass(classText); } protected final void doStatementTest(@Language(value="JAVA", prefix="class X { void m() {", suffix="}}") @NotNull String statementText) { doTest("class X { void m() {" + statementText + "}}"); } protected final void doMemberTest(@Language(value="JAVA", prefix="class X {", suffix="}") @NotNull String memberText) { doTest("class X {" + memberText + "}"); } protected final void doTest(@Language("JAVA") @NotNull String classText) { doTest(classText, "X.java"); } protected final void doTest(@Language("JAVA") @NotNull String classText, String fileName) { final StringBuilder newText = new StringBuilder(); int start = 0; int end = classText.indexOf("/*"); while (end >= 0) { newText.append(classText, start, end); start = end + 2; end = classText.indexOf("*/", end); if (end < 0) { throw new IllegalArgumentException("invalid class text"); } final String text = classText.substring(start, end); if (text.isEmpty()) { newText.append("</warning>"); } else if ("!".equals(text)) { newText.append("</error>"); } else if ("_".equals(text)) { newText.append("<caret>"); } else if (text.startsWith("!")) { newText.append("<error descr=\"").append(text.substring(1)).append("\">"); } else { newText.append("<warning descr=\"").append(text).append("\">"); } start = end + 2; end = classText.indexOf("/*", end + 1); } newText.append(classText, start, classText.length()); myFixture.configureByText(fileName, newText.toString()); myFixture.testHighlighting(true, false, false); } @Override protected String getBasePath() { final InspectionProfileEntry inspection = getInspection(); assertNotNull("File-based tests should either return an inspection or override this method", inspection); final String className = inspection.getClass().getName(); final String[] words = className.split("\\."); final StringBuilder basePath = new StringBuilder("/plugins/InspectionGadgets/test/"); final int lastWordIndex = words.length - 1; for (int i = 0; i < lastWordIndex; i++) { String word = words[i]; if (word.equals("ig")) { //noinspection SpellCheckingInspection word = "igtest"; } basePath.append(word).append('/'); } String lastWord = words[lastWordIndex]; lastWord = StringUtil.trimEnd(lastWord, "Inspection"); final int length = lastWord.length(); boolean upperCase = false; for (int i = 0; i < length; i++) { final char ch = lastWord.charAt(i); if (Character.isUpperCase(ch)) { if (!upperCase) { upperCase = true; if (i != 0) { basePath.append('_'); } } basePath.append(Character.toLowerCase(ch)); } else { upperCase = false; basePath.append(ch); } } return basePath.toString(); } protected final void doTest() { doNamedTest(getTestName(false)); } protected final void doNamedTest(String name) { myFixture.configureByFile(name + ".java"); myFixture.testHighlighting(true, false, false); } }
LightInspectionTestCase: suppress all warnings in injected code by default for member test and statement test
java/testFramework/src/com/siyeh/ig/LightInspectionTestCase.java
LightInspectionTestCase: suppress all warnings in injected code by default for member test and statement test
Java
apache-2.0
b0d30ff57492be668e50929403679c46009e8c90
0
signed/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,caot/intellij-community,apixandru/intellij-community,kdwink/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,adedayo/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,da1z/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,slisson/intellij-community,fnouama/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,robovm/robovm-studio,jagguli/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,vvv1559/intellij-community,signed/intellij-community,fnouama/intellij-community,dslomov/intellij-community,adedayo/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,signed/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,holmes/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,petteyg/intellij-community,samthor/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,caot/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,vladmm/intellij-community,samthor/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,slisson/intellij-community,asedunov/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,kool79/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,semonte/intellij-community,robovm/robovm-studio,amith01994/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,amith01994/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,jagguli/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,samthor/intellij-community,petteyg/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,supersven/intellij-community,supersven/intellij-community,kool79/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,apixandru/intellij-community,adedayo/intellij-community,adedayo/intellij-community,xfournet/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,blademainer/intellij-community,diorcety/intellij-community,dslomov/intellij-community,apixandru/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,semonte/intellij-community,ahb0327/intellij-community,slisson/intellij-community,slisson/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,signed/intellij-community,blademainer/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,jagguli/intellij-community,samthor/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,suncycheng/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,semonte/intellij-community,fitermay/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,xfournet/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,holmes/intellij-community,amith01994/intellij-community,semonte/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,kdwink/intellij-community,apixandru/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,robovm/robovm-studio,retomerz/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,diorcety/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,fnouama/intellij-community,holmes/intellij-community,supersven/intellij-community,Distrotech/intellij-community,caot/intellij-community,youdonghai/intellij-community,caot/intellij-community,signed/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,semonte/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,ryano144/intellij-community,fitermay/intellij-community,ibinti/intellij-community,petteyg/intellij-community,supersven/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,ryano144/intellij-community,apixandru/intellij-community,samthor/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,blademainer/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,caot/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,izonder/intellij-community,apixandru/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,dslomov/intellij-community,adedayo/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,semonte/intellij-community,izonder/intellij-community,vladmm/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,slisson/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,signed/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,signed/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,da1z/intellij-community,izonder/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,da1z/intellij-community,asedunov/intellij-community,fnouama/intellij-community,FHannes/intellij-community,allotria/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,FHannes/intellij-community,caot/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,da1z/intellij-community,petteyg/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,kdwink/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,holmes/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,ibinti/intellij-community,adedayo/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,caot/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,diorcety/intellij-community,da1z/intellij-community,semonte/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,fnouama/intellij-community,allotria/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,diorcety/intellij-community,asedunov/intellij-community,slisson/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,signed/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,asedunov/intellij-community,xfournet/intellij-community,ryano144/intellij-community,clumsy/intellij-community,clumsy/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,samthor/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,FHannes/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,samthor/intellij-community,samthor/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,allotria/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,izonder/intellij-community,kdwink/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,samthor/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,petteyg/intellij-community,fitermay/intellij-community,caot/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,da1z/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,caot/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,clumsy/intellij-community,ibinti/intellij-community,retomerz/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,supersven/intellij-community,signed/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,supersven/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,semonte/intellij-community,asedunov/intellij-community,slisson/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,signed/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,kool79/intellij-community,kool79/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,allotria/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,izonder/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,petteyg/intellij-community,blademainer/intellij-community,fitermay/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,signed/intellij-community,supersven/intellij-community,Distrotech/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,kool79/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,supersven/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,jagguli/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,diorcety/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,signed/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,youdonghai/intellij-community,apixandru/intellij-community
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.github.api; import com.google.gson.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.ThrowableConvertor; import com.intellij.util.net.HttpConfigurable; import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.*; import org.apache.commons.httpclient.params.HttpConnectionManagerParams; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.github.*; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URLEncoder; import java.util.*; /** * @author Kirill Likhodedov */ public class GithubApiUtil { public static final String DEFAULT_GITHUB_HOST = "github.com"; private static final int CONNECTION_TIMEOUT = 5000; private static final Logger LOG = GithubUtil.LOG; @NotNull private static final Gson gson = initGson(); private static Gson initGson() { GsonBuilder builder = new GsonBuilder(); builder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); return builder.create(); } private enum HttpVerb { GET, POST, DELETE, HEAD } @Nullable private static JsonElement postRequest(@NotNull GithubAuthData auth, @NotNull String path, @Nullable String requestBody) throws IOException { return request(auth, path, requestBody, HttpVerb.POST).getJsonElement(); } @Nullable private static JsonElement deleteRequest(@NotNull GithubAuthData auth, @NotNull String path) throws IOException { return request(auth, path, null, HttpVerb.DELETE).getJsonElement(); } @Nullable private static JsonElement getRequest(@NotNull GithubAuthData auth, @NotNull String path) throws IOException { return request(auth, path, null, HttpVerb.GET).getJsonElement(); } @NotNull private static ResponsePage request(@NotNull GithubAuthData auth, @NotNull String path, @Nullable String requestBody, @NotNull HttpVerb verb) throws IOException { HttpMethod method = null; try { method = doREST(auth, path, requestBody, verb); checkStatusCode(method); InputStream resp = method.getResponseBodyAsStream(); if (resp == null) { return new ResponsePage(); } JsonElement ret = parseResponse(resp); if (ret.isJsonNull()) { return new ResponsePage(); } Header header = method.getResponseHeader("Link"); if (header != null) { String value = header.getValue(); int end = value.indexOf(">; rel=\"next\""); int begin = value.lastIndexOf('<', end); if (begin >= 0 && end >= 0) { String newPath = GithubUrlUtil.removeProtocolPrefix(value.substring(begin + 1, end)); int index = newPath.indexOf('/'); return new ResponsePage(ret, newPath.substring(index)); } } return new ResponsePage(ret); } finally { if (method != null) { method.releaseConnection(); } } } @NotNull private static HttpMethod doREST(@NotNull final GithubAuthData auth, @NotNull String path, @Nullable final String requestBody, @NotNull final HttpVerb verb) throws IOException { HttpClient client = getHttpClient(auth.getBasicAuth()); String uri = GithubUrlUtil.getApiUrl(auth.getHost()) + path; return GithubSslSupport.getInstance() .executeSelfSignedCertificateAwareRequest(client, uri, new ThrowableConvertor<String, HttpMethod, IOException>() { @Override public HttpMethod convert(String uri) throws IOException { HttpMethod method; switch (verb) { case POST: method = new PostMethod(uri); if (requestBody != null) { ((PostMethod)method).setRequestEntity(new StringRequestEntity(requestBody, "application/json", "UTF-8")); } break; case GET: method = new GetMethod(uri); break; case DELETE: method = new DeleteMethod(uri); break; case HEAD: method = new HeadMethod(uri); break; default: throw new IllegalStateException("Wrong HttpVerb: unknown method: " + verb.toString()); } GithubAuthData.TokenAuth tokenAuth = auth.getTokenAuth(); if (tokenAuth != null) { method.addRequestHeader("Authorization", "token " + tokenAuth.getToken()); } method.addRequestHeader("Accept", "application/vnd.github.preview"); //TODO: remove after end of preview period. ~ october 2013 return method; } }); } @NotNull private static HttpClient getHttpClient(@Nullable GithubAuthData.BasicAuth basicAuth) { final HttpClient client = new HttpClient(); HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams(); params.setConnectionTimeout(CONNECTION_TIMEOUT); //set connection timeout (how long it takes to connect to remote host) params.setSoTimeout(CONNECTION_TIMEOUT); //set socket timeout (how long it takes to retrieve data from remote host) client.getParams().setContentCharset("UTF-8"); // Configure proxySettings if it is required final HttpConfigurable proxySettings = HttpConfigurable.getInstance(); if (proxySettings.USE_HTTP_PROXY && !StringUtil.isEmptyOrSpaces(proxySettings.PROXY_HOST)) { client.getHostConfiguration().setProxy(proxySettings.PROXY_HOST, proxySettings.PROXY_PORT); if (proxySettings.PROXY_AUTHENTICATION) { client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxySettings.PROXY_LOGIN, proxySettings.getPlainProxyPassword())); } } if (basicAuth != null) { client.getParams().setCredentialCharset("UTF-8"); client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(basicAuth.getLogin(), basicAuth.getPassword())); } return client; } private static void checkStatusCode(@NotNull HttpMethod method) throws IOException { int code = method.getStatusCode(); switch (code) { case HttpStatus.SC_OK: case HttpStatus.SC_CREATED: case HttpStatus.SC_ACCEPTED: case HttpStatus.SC_NO_CONTENT: return; case HttpStatus.SC_BAD_REQUEST: case HttpStatus.SC_UNAUTHORIZED: case HttpStatus.SC_PAYMENT_REQUIRED: case HttpStatus.SC_FORBIDDEN: case HttpStatus.SC_NOT_FOUND: throw new GithubAuthenticationException("Request response: " + getErrorMessage(method)); default: throw new HttpException(code + ": " + getErrorMessage(method)); } } @NotNull private static String getErrorMessage(@NotNull HttpMethod method) { try { InputStream resp = method.getResponseBodyAsStream(); if (resp != null) { GithubErrorMessageRaw error = fromJson(parseResponse(resp), GithubErrorMessageRaw.class); return method.getStatusText() + " - " + error.getMessage(); } } catch (IOException ignore) { } return method.getStatusText(); } @NotNull private static JsonElement parseResponse(@NotNull InputStream githubResponse) throws IOException { Reader reader = new InputStreamReader(githubResponse); try { return new JsonParser().parse(reader); } catch (JsonSyntaxException jse) { throw new JsonException(String.format("Couldn't parse GitHub response:%n%s", githubResponse), jse); } finally { reader.close(); } } private static class ResponsePage { @Nullable private final JsonElement response; @Nullable private final String nextPage; public ResponsePage() { this(null, null); } public ResponsePage(@Nullable JsonElement response) { this(response, null); } public ResponsePage(@Nullable JsonElement response, @Nullable String next) { this.response = response; this.nextPage = next; } @Nullable public JsonElement getJsonElement() { return response; } @Nullable public String getNextPage() { return nextPage; } } /* * Json API */ static <Raw extends DataConstructor, Result> Result createDataFromRaw(@NotNull Raw rawObject, @NotNull Class<Result> resultClass) throws JsonException { try { return rawObject.create(resultClass); } catch (Exception e) { throw new JsonException("Json parse error", e); } } public static class PagedRequest<T> { @Nullable private String myNextPage; @NotNull private final Class<T> myResult; @NotNull private final Class<? extends DataConstructor[]> myRawArray; @SuppressWarnings("NullableProblems") public PagedRequest(@NotNull String path, @NotNull Class<T> result, @NotNull Class<? extends DataConstructor[]> rawArray) { myNextPage = path; myResult = result; myRawArray = rawArray; } @NotNull public List<T> next(@NotNull GithubAuthData auth) throws IOException { if (myNextPage == null) { throw new NoSuchElementException(); } String page = myNextPage; myNextPage = null; ResponsePage response = request(auth, page, null, HttpVerb.GET); if (response.getJsonElement() == null) { throw new HttpException("Empty response"); } if (!response.getJsonElement().isJsonArray()) { throw new JsonException("Wrong json type: expected JsonArray"); } myNextPage = response.getNextPage(); List<T> result = new ArrayList<T>(); for (DataConstructor raw : fromJson(response.getJsonElement().getAsJsonArray(), myRawArray)) { result.add(createDataFromRaw(raw, myResult)); } return result; } public boolean hasNext() { return myNextPage != null; } @NotNull public List<T> getAll(@NotNull GithubAuthData auth) throws IOException { List<T> result = new ArrayList<T>(); while (hasNext()) { result.addAll(next(auth)); } return result; } } @NotNull private static <T> T fromJson(@Nullable JsonElement json, @NotNull Class<T> classT) throws IOException { if (json == null) { throw new JsonException("Unexpected empty response"); } T res; try { //cast as workaround for early java 1.6 bug //noinspection RedundantCast res = (T)gson.fromJson(json, classT); } catch (ClassCastException e) { throw new JsonException("Parse exception while converting JSON to object " + classT.toString(), e); } catch (JsonParseException e) { throw new JsonException("Parse exception while converting JSON to object " + classT.toString(), e); } if (res == null) { throw new JsonException("Empty Json response"); } return res; } /* * Github API */ @NotNull public static Collection<String> getTokenScopes(@NotNull GithubAuthData auth) throws IOException { HttpMethod method = null; try { method = doREST(auth, "", null, HttpVerb.HEAD); checkStatusCode(method); Header header = method.getResponseHeader("X-OAuth-Scopes"); if (header == null) { throw new HttpException("No scopes header"); } Collection<String> scopes = new ArrayList<String>(); for (HeaderElement elem : header.getElements()) { scopes.add(elem.getName()); } return scopes; } finally { if (method != null) { method.releaseConnection(); } } } @NotNull public static String getScopedToken(@NotNull GithubAuthData auth, @NotNull Collection<String> scopes, @Nullable String note) throws IOException { String path = "/authorizations"; GithubAuthorizationRequest request = new GithubAuthorizationRequest(new ArrayList<String>(scopes), note, null); GithubAuthorization response = createDataFromRaw(fromJson(postRequest(auth, path, gson.toJson(request)), GithubAuthorizationRaw.class), GithubAuthorization.class); return response.getToken(); } @NotNull public static GithubUser getCurrentUser(@NotNull GithubAuthData auth) throws IOException { JsonElement result = getRequest(auth, "/user"); return createDataFromRaw(fromJson(result, GithubUserRaw.class), GithubUser.class); } @NotNull public static GithubUserDetailed getCurrentUserDetailed(@NotNull GithubAuthData auth) throws IOException { JsonElement result = getRequest(auth, "/user"); return createDataFromRaw(fromJson(result, GithubUserRaw.class), GithubUserDetailed.class); } @NotNull public static List<GithubRepo> getAvailableRepos(@NotNull GithubAuthData auth) throws IOException { return doGetAvailableRepos(auth, null); } @NotNull public static List<GithubRepo> getAvailableRepos(@NotNull GithubAuthData auth, @NotNull String user) throws IOException { return doGetAvailableRepos(auth, user); } @NotNull private static List<GithubRepo> doGetAvailableRepos(@NotNull GithubAuthData auth, @Nullable String user) throws IOException { String path = user == null ? "/user/repos" : "/users/" + user + "/repos?per_page=100"; PagedRequest<GithubRepo> request = new PagedRequest<GithubRepo>(path, GithubRepo.class, GithubRepoRaw[].class); return request.getAll(auth); } @NotNull public static GithubRepoDetailed getDetailedRepoInfo(@NotNull GithubAuthData auth, @NotNull String owner, @NotNull String name) throws IOException { final String request = "/repos/" + owner + "/" + name; JsonElement jsonObject = getRequest(auth, request); return createDataFromRaw(fromJson(jsonObject, GithubRepoRaw.class), GithubRepoDetailed.class); } public static void deleteGithubRepository(@NotNull GithubAuthData auth, @NotNull String username, @NotNull String repo) throws IOException { String path = "/repos/" + username + "/" + repo; deleteRequest(auth, path); } public static void deleteGist(@NotNull GithubAuthData auth, @NotNull String id) throws IOException { String path = "/gists/" + id; deleteRequest(auth, path); } @NotNull public static GithubGist getGist(@NotNull GithubAuthData auth, @NotNull String id) throws IOException { String path = "/gists/" + id; JsonElement result = getRequest(auth, path); return createDataFromRaw(fromJson(result, GithubGistRaw.class), GithubGist.class); } @NotNull public static GithubGist createGist(@NotNull GithubAuthData auth, @NotNull List<GithubGist.FileContent> contents, @NotNull String description, boolean isPrivate) throws IOException { String request = gson.toJson(new GithubGistRequest(contents, description, !isPrivate)); return createDataFromRaw(fromJson(postRequest(auth, "/gists", request), GithubGistRaw.class), GithubGist.class); } @NotNull public static GithubPullRequest createPullRequest(@NotNull GithubAuthData auth, @NotNull String user, @NotNull String repo, @NotNull String title, @NotNull String description, @NotNull String from, @NotNull String onto) throws IOException { String request = gson.toJson(new GithubPullRequestRequest(title, description, from, onto)); return createDataFromRaw(fromJson(postRequest(auth, "/repos/" + user + "/" + repo + "/pulls", request), GithubPullRequestRaw.class), GithubPullRequest.class); } @NotNull public static GithubRepo createRepo(@NotNull GithubAuthData auth, @NotNull String name, @NotNull String description, boolean isPublic) throws IOException { String path = "/user/repos"; GithubRepoRequest request = new GithubRepoRequest(name, description, isPublic); return createDataFromRaw(fromJson(postRequest(auth, path, gson.toJson(request)), GithubRepoRaw.class), GithubRepo.class); } @NotNull public static List<GithubIssue> getIssuesAssigned(@NotNull GithubAuthData auth, @NotNull String user, @NotNull String repo, @Nullable String assigned) throws IOException { String path; if (StringUtil.isEmptyOrSpaces(assigned)) { path = "/repos/" + user + "/" + repo + "/issues?per_page=100"; } else { path = "/repos/" + user + "/" + repo + "/issues?assignee=" + assigned + "&per_page=100"; } PagedRequest<GithubIssue> request = new PagedRequest<GithubIssue>(path, GithubIssue.class, GithubIssueRaw[].class); return request.getAll(auth); } @NotNull public static List<GithubIssue> getIssuesQueried(@NotNull GithubAuthData auth, @NotNull String user, @NotNull String repo, @Nullable String query) throws IOException { query = URLEncoder.encode("@" + user + "/" + repo + " " + query, "UTF-8"); String path = "/search/issues?q=" + query; JsonElement result = getRequest(auth, path); return createDataFromRaw(fromJson(result, GithubIssuesSearchResultRaw.class), GithubIssuesSearchResult.class).getIssues(); } @NotNull public static GithubIssue getIssue(@NotNull GithubAuthData auth, @NotNull String user, @NotNull String repo, @NotNull String id) throws IOException { String path = "/repos/" + user + "/" + repo + "/issues/" + id; JsonElement result = getRequest(auth, path); return createDataFromRaw(fromJson(result, GithubIssueRaw.class), GithubIssue.class); } @NotNull public static List<GithubIssueComment> getIssueComments(@NotNull GithubAuthData auth, @NotNull String user, @NotNull String repo, long id) throws IOException { String path = "/repos/" + user + "/" + repo + "/issues/" + id + "/comments?per_page=100"; PagedRequest<GithubIssueComment> request = new PagedRequest<GithubIssueComment>(path, GithubIssueComment.class, GithubIssueCommentRaw[].class); return request.getAll(auth); } @NotNull public static GithubCommitDetailed getCommit(@NotNull GithubAuthData auth, @NotNull String user, @NotNull String repo, @NotNull String sha) throws IOException { String path = "/repos/" + user + "/" + repo + "/commits/" + sha; JsonElement result = getRequest(auth, path); return createDataFromRaw(fromJson(result, GithubCommitRaw.class), GithubCommitDetailed.class); } @NotNull public static GithubPullRequest getPullRequest(@NotNull GithubAuthData auth, @NotNull String user, @NotNull String repo, int id) throws IOException { String path = "/repos/" + user + "/" + repo + "/pulls/" + id; return createDataFromRaw(fromJson(getRequest(auth, path), GithubPullRequestRaw.class), GithubPullRequest.class); } @NotNull public static List<GithubPullRequest> getPullRequests(@NotNull GithubAuthData auth, @NotNull String user, @NotNull String repo) throws IOException { String path = "/repos/" + user + "/" + repo + "/pulls?per_page=100"; PagedRequest<GithubPullRequest> request = new PagedRequest<GithubPullRequest>(path, GithubPullRequest.class, GithubPullRequestRaw[].class); return request.getAll(auth); } @NotNull public static PagedRequest<GithubPullRequest> getPullRequests(@NotNull String user, @NotNull String repo) { String path = "/repos/" + user + "/" + repo + "/pulls?per_page=100"; return new PagedRequest<GithubPullRequest>(path, GithubPullRequest.class, GithubPullRequestRaw[].class); } @NotNull public static List<GithubCommit> getPullRequestCommits(@NotNull GithubAuthData auth, @NotNull String user, @NotNull String repo, long id) throws IOException { String path = "/repos/" + user + "/" + repo + "/pulls/" + id + "/commits?per_page=100"; PagedRequest<GithubCommit> request = new PagedRequest<GithubCommit>(path, GithubCommit.class, GithubCommitRaw[].class); return request.getAll(auth); } @NotNull public static List<GithubFile> getPullRequestFiles(@NotNull GithubAuthData auth, @NotNull String user, @NotNull String repo, long id) throws IOException { String path = "/repos/" + user + "/" + repo + "/pulls/" + id + "/files?per_page=100"; PagedRequest<GithubFile> request = new PagedRequest<GithubFile>(path, GithubFile.class, GithubFileRaw[].class); return request.getAll(auth); } @NotNull public static List<GithubBranch> getRepoBranches(@NotNull GithubAuthData auth, @NotNull String user, @NotNull String repo) throws IOException { String path = "/repos/" + user + "/" + repo + "/branches?per_page=100"; PagedRequest<GithubBranch> request = new PagedRequest<GithubBranch>(path, GithubBranch.class, GithubBranchRaw[].class); return request.getAll(auth); } @Nullable public static GithubRepo findForkByUser(@NotNull GithubAuthData auth, @NotNull String user, @NotNull String repo, @NotNull String forkUser) throws IOException { String path = "/repos/" + user + "/" + repo + "/forks?per_page=100"; PagedRequest<GithubRepo> request = new PagedRequest<GithubRepo>(path, GithubRepo.class, GithubRepoRaw[].class); while (request.hasNext()) { for (GithubRepo fork : request.next(auth)) { if (StringUtil.equalsIgnoreCase(fork.getUserName(), forkUser)) { return fork; } } } return null; } }
plugins/github/src/org/jetbrains/plugins/github/api/GithubApiUtil.java
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.github.api; import com.google.gson.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.ThrowableConvertor; import com.intellij.util.net.HttpConfigurable; import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.*; import org.apache.commons.httpclient.params.HttpConnectionManagerParams; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.github.*; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URLEncoder; import java.util.*; /** * @author Kirill Likhodedov */ public class GithubApiUtil { public static final String DEFAULT_GITHUB_HOST = "github.com"; private static final int CONNECTION_TIMEOUT = 5000; private static final Logger LOG = GithubUtil.LOG; @NotNull private static final Gson gson = initGson(); private static Gson initGson() { GsonBuilder builder = new GsonBuilder(); builder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); return builder.create(); } private enum HttpVerb { GET, POST, DELETE, HEAD } @Nullable private static JsonElement postRequest(@NotNull GithubAuthData auth, @NotNull String path, @Nullable String requestBody) throws IOException { return request(auth, path, requestBody, HttpVerb.POST).getJsonElement(); } @Nullable private static JsonElement deleteRequest(@NotNull GithubAuthData auth, @NotNull String path) throws IOException { return request(auth, path, null, HttpVerb.DELETE).getJsonElement(); } @Nullable private static JsonElement getRequest(@NotNull GithubAuthData auth, @NotNull String path) throws IOException { return request(auth, path, null, HttpVerb.GET).getJsonElement(); } @NotNull private static ResponsePage request(@NotNull GithubAuthData auth, @NotNull String path, @Nullable String requestBody, @NotNull HttpVerb verb) throws IOException { HttpMethod method = null; try { method = doREST(auth, path, requestBody, verb); checkStatusCode(method); InputStream resp = method.getResponseBodyAsStream(); if (resp == null) { return new ResponsePage(); } JsonElement ret = parseResponse(resp); if (ret.isJsonNull()) { return new ResponsePage(); } Header header = method.getResponseHeader("Link"); if (header != null) { String value = header.getValue(); int end = value.indexOf(">; rel=\"next\""); int begin = value.lastIndexOf('<', end); if (begin >= 0 && end >= 0) { String newPath = GithubUrlUtil.removeProtocolPrefix(value.substring(begin + 1, end)); int index = newPath.indexOf('/'); return new ResponsePage(ret, newPath.substring(index)); } } return new ResponsePage(ret); } finally { if (method != null) { method.releaseConnection(); } } } @NotNull private static HttpMethod doREST(@NotNull final GithubAuthData auth, @NotNull String path, @Nullable final String requestBody, @NotNull final HttpVerb verb) throws IOException { HttpClient client = getHttpClient(auth.getBasicAuth()); String uri = GithubUrlUtil.getApiUrl(auth.getHost()) + path; return GithubSslSupport.getInstance() .executeSelfSignedCertificateAwareRequest(client, uri, new ThrowableConvertor<String, HttpMethod, IOException>() { @Override public HttpMethod convert(String uri) throws IOException { HttpMethod method; switch (verb) { case POST: method = new PostMethod(uri); if (requestBody != null) { ((PostMethod)method).setRequestEntity(new StringRequestEntity(requestBody, "application/json", "UTF-8")); } break; case GET: method = new GetMethod(uri); break; case DELETE: method = new DeleteMethod(uri); break; case HEAD: method = new HeadMethod(uri); break; default: throw new IllegalStateException("Wrong HttpVerb: unknown method: " + verb.toString()); } GithubAuthData.TokenAuth tokenAuth = auth.getTokenAuth(); if (tokenAuth != null) { method.addRequestHeader("Authorization", "token " + tokenAuth.getToken()); } method.addRequestHeader("Accept", "application/vnd.github.preview"); //TODO: remove after end of preview period. ~ october 2013 return method; } }); } @NotNull private static HttpClient getHttpClient(@Nullable GithubAuthData.BasicAuth basicAuth) { final HttpClient client = new HttpClient(); HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams(); params.setConnectionTimeout(CONNECTION_TIMEOUT); //set connection timeout (how long it takes to connect to remote host) params.setSoTimeout(CONNECTION_TIMEOUT); //set socket timeout (how long it takes to retrieve data from remote host) client.getParams().setContentCharset("UTF-8"); // Configure proxySettings if it is required final HttpConfigurable proxySettings = HttpConfigurable.getInstance(); if (proxySettings.USE_HTTP_PROXY && !StringUtil.isEmptyOrSpaces(proxySettings.PROXY_HOST)) { client.getHostConfiguration().setProxy(proxySettings.PROXY_HOST, proxySettings.PROXY_PORT); if (proxySettings.PROXY_AUTHENTICATION) { client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxySettings.PROXY_LOGIN, proxySettings.getPlainProxyPassword())); } } if (basicAuth != null) { client.getParams().setCredentialCharset("UTF-8"); client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(basicAuth.getLogin(), basicAuth.getPassword())); } return client; } private static void checkStatusCode(@NotNull HttpMethod method) throws IOException { int code = method.getStatusCode(); switch (code) { case HttpStatus.SC_OK: case HttpStatus.SC_CREATED: case HttpStatus.SC_ACCEPTED: case HttpStatus.SC_NO_CONTENT: return; case HttpStatus.SC_BAD_REQUEST: case HttpStatus.SC_UNAUTHORIZED: case HttpStatus.SC_PAYMENT_REQUIRED: case HttpStatus.SC_FORBIDDEN: case HttpStatus.SC_NOT_FOUND: throw new GithubAuthenticationException("Request response: " + getErrorMessage(method)); default: throw new HttpException(code + ": " + getErrorMessage(method)); } } @NotNull private static String getErrorMessage(@NotNull HttpMethod method) { try { InputStream resp = method.getResponseBodyAsStream(); if (resp != null) { GithubErrorMessageRaw error = fromJson(parseResponse(resp), GithubErrorMessageRaw.class); return method.getStatusText() + " - " + error.getMessage(); } } catch (IOException ignore) { } return method.getStatusText(); } @NotNull private static JsonElement parseResponse(@NotNull InputStream githubResponse) throws IOException { Reader reader = new InputStreamReader(githubResponse); try { return new JsonParser().parse(reader); } catch (JsonSyntaxException jse) { throw new JsonException(String.format("Couldn't parse GitHub response:%n%s", githubResponse), jse); } finally { reader.close(); } } private static class ResponsePage { @Nullable private JsonElement response; @Nullable private String nextPage; public ResponsePage() { this(null, null); } public ResponsePage(@Nullable JsonElement response) { this(response, null); } public ResponsePage(@Nullable JsonElement response, @Nullable String next) { this.response = response; this.nextPage = next; } @Nullable public JsonElement getJsonElement() { return response; } @Nullable public String getNextPage() { return nextPage; } } /* * Json API */ static <Raw extends DataConstructor, Result> Result createDataFromRaw(@NotNull Raw rawObject, @NotNull Class<Result> resultClass) throws JsonException { try { return rawObject.create(resultClass); } catch (Exception e) { throw new JsonException("Json parse error", e); } } static class PagedRequest<T, R extends DataConstructor> { @NotNull private GithubAuthData myAuth; @Nullable private String myNextPage; @NotNull private Class<T> myResult; @NotNull private Class<R[]> myRawArray; public PagedRequest(@NotNull GithubAuthData auth, @NotNull String path, @NotNull Class<T> result, @NotNull Class<R[]> rawArray) { myAuth = auth; myNextPage = path; myResult = result; myRawArray = rawArray; } @NotNull public List<T> next() throws IOException { if (myNextPage == null) { throw new NoSuchElementException(); } String page = myNextPage; myNextPage = null; ResponsePage response = request(myAuth, page, null, HttpVerb.GET); if (response.getJsonElement() == null) { throw new HttpException("Empty response"); } if (!response.getJsonElement().isJsonArray()) { throw new JsonException("Wrong json type: expected JsonArray"); } myNextPage = response.getNextPage(); List<T> result = new ArrayList<T>(); for (R raw : fromJson(response.getJsonElement().getAsJsonArray(), myRawArray)) { result.add(createDataFromRaw(raw, myResult)); } return result; } public boolean hasNext() { return myNextPage != null; } @NotNull public List<T> getAll() throws IOException { List<T> result = new ArrayList<T>(); while (hasNext()) { result.addAll(next()); } return result; } } @NotNull private static <T> T fromJson(@Nullable JsonElement json, @NotNull Class<T> classT) throws IOException { if (json == null) { throw new JsonException("Unexpected empty response"); } T res; try { //cast as workaround for early java 1.6 bug //noinspection RedundantCast res = (T)gson.fromJson(json, classT); } catch (ClassCastException e) { throw new JsonException("Parse exception while converting JSON to object " + classT.toString(), e); } catch (JsonParseException e) { throw new JsonException("Parse exception while converting JSON to object " + classT.toString(), e); } if (res == null) { throw new JsonException("Empty Json response"); } return res; } /* * Github API */ @NotNull public static Collection<String> getTokenScopes(@NotNull GithubAuthData auth) throws IOException { HttpMethod method = null; try { method = doREST(auth, "", null, HttpVerb.HEAD); checkStatusCode(method); Header header = method.getResponseHeader("X-OAuth-Scopes"); if (header == null) { throw new HttpException("No scopes header"); } Collection<String> scopes = new ArrayList<String>(); for (HeaderElement elem : header.getElements()) { scopes.add(elem.getName()); } return scopes; } finally { if (method != null) { method.releaseConnection(); } } } @NotNull public static String getScopedToken(@NotNull GithubAuthData auth, @NotNull Collection<String> scopes, @Nullable String note) throws IOException { String path = "/authorizations"; GithubAuthorizationRequest request = new GithubAuthorizationRequest(new ArrayList<String>(scopes), note, null); GithubAuthorization response = createDataFromRaw(fromJson(postRequest(auth, path, gson.toJson(request)), GithubAuthorizationRaw.class), GithubAuthorization.class); return response.getToken(); } @NotNull public static GithubUser getCurrentUser(@NotNull GithubAuthData auth) throws IOException { JsonElement result = getRequest(auth, "/user"); return createDataFromRaw(fromJson(result, GithubUserRaw.class), GithubUser.class); } @NotNull public static GithubUserDetailed getCurrentUserDetailed(@NotNull GithubAuthData auth) throws IOException { JsonElement result = getRequest(auth, "/user"); return createDataFromRaw(fromJson(result, GithubUserRaw.class), GithubUserDetailed.class); } @NotNull public static List<GithubRepo> getAvailableRepos(@NotNull GithubAuthData auth) throws IOException { return doGetAvailableRepos(auth, null); } @NotNull public static List<GithubRepo> getAvailableRepos(@NotNull GithubAuthData auth, @NotNull String user) throws IOException { return doGetAvailableRepos(auth, user); } @NotNull private static List<GithubRepo> doGetAvailableRepos(@NotNull GithubAuthData auth, @Nullable String user) throws IOException { String path = user == null ? "/user/repos" : "/users/" + user + "/repos?per_page=100"; PagedRequest<GithubRepo, GithubRepoRaw> request = new PagedRequest<GithubRepo, GithubRepoRaw>(auth, path, GithubRepo.class, GithubRepoRaw[].class); return request.getAll(); } @NotNull public static GithubRepoDetailed getDetailedRepoInfo(@NotNull GithubAuthData auth, @NotNull String owner, @NotNull String name) throws IOException { final String request = "/repos/" + owner + "/" + name; JsonElement jsonObject = getRequest(auth, request); return createDataFromRaw(fromJson(jsonObject, GithubRepoRaw.class), GithubRepoDetailed.class); } public static void deleteGithubRepository(@NotNull GithubAuthData auth, @NotNull String username, @NotNull String repo) throws IOException { String path = "/repos/" + username + "/" + repo; deleteRequest(auth, path); } public static void deleteGist(@NotNull GithubAuthData auth, @NotNull String id) throws IOException { String path = "/gists/" + id; deleteRequest(auth, path); } @NotNull public static GithubGist getGist(@NotNull GithubAuthData auth, @NotNull String id) throws IOException { String path = "/gists/" + id; JsonElement result = getRequest(auth, path); return createDataFromRaw(fromJson(result, GithubGistRaw.class), GithubGist.class); } @NotNull public static GithubGist createGist(@NotNull GithubAuthData auth, @NotNull List<GithubGist.FileContent> contents, @NotNull String description, boolean isPrivate) throws IOException { String request = gson.toJson(new GithubGistRequest(contents, description, !isPrivate)); return createDataFromRaw(fromJson(postRequest(auth, "/gists", request), GithubGistRaw.class), GithubGist.class); } @NotNull public static GithubPullRequest createPullRequest(@NotNull GithubAuthData auth, @NotNull String user, @NotNull String repo, @NotNull String title, @NotNull String description, @NotNull String from, @NotNull String onto) throws IOException { String request = gson.toJson(new GithubPullRequestRequest(title, description, from, onto)); return createDataFromRaw(fromJson(postRequest(auth, "/repos/" + user + "/" + repo + "/pulls", request), GithubPullRequestRaw.class), GithubPullRequest.class); } @NotNull public static GithubRepo createRepo(@NotNull GithubAuthData auth, @NotNull String name, @NotNull String description, boolean isPublic) throws IOException { String path = "/user/repos"; GithubRepoRequest request = new GithubRepoRequest(name, description, isPublic); return createDataFromRaw(fromJson(postRequest(auth, path, gson.toJson(request)), GithubRepoRaw.class), GithubRepo.class); } @NotNull public static List<GithubIssue> getIssuesAssigned(@NotNull GithubAuthData auth, @NotNull String user, @NotNull String repo, @Nullable String assigned) throws IOException { String path; if (StringUtil.isEmptyOrSpaces(assigned)) { path = "/repos/" + user + "/" + repo + "/issues?per_page=100"; } else { path = "/repos/" + user + "/" + repo + "/issues?assignee=" + assigned + "&per_page=100"; } PagedRequest<GithubIssue, GithubIssueRaw> request = new PagedRequest<GithubIssue, GithubIssueRaw>(auth, path, GithubIssue.class, GithubIssueRaw[].class); return request.getAll(); } @NotNull public static List<GithubIssue> getIssuesQueried(@NotNull GithubAuthData auth, @NotNull String user, @NotNull String repo, @Nullable String query) throws IOException { query = URLEncoder.encode("@" + user + "/" + repo + " " + query, "UTF-8"); String path = "/search/issues?q=" + query; JsonElement result = getRequest(auth, path); return createDataFromRaw(fromJson(result, GithubIssuesSearchResultRaw.class), GithubIssuesSearchResult.class).getIssues(); } @NotNull public static GithubIssue getIssue(@NotNull GithubAuthData auth, @NotNull String user, @NotNull String repo, @NotNull String id) throws IOException { String path = "/repos/" + user + "/" + repo + "/issues/" + id; JsonElement result = getRequest(auth, path); return createDataFromRaw(fromJson(result, GithubIssueRaw.class), GithubIssue.class); } @NotNull public static List<GithubIssueComment> getIssueComments(@NotNull GithubAuthData auth, @NotNull String user, @NotNull String repo, long id) throws IOException { String path = "/repos/" + user + "/" + repo + "/issues/" + id + "/comments?per_page=100"; PagedRequest<GithubIssueComment, GithubIssueCommentRaw> request = new PagedRequest<GithubIssueComment, GithubIssueCommentRaw>(auth, path, GithubIssueComment.class, GithubIssueCommentRaw[].class); return request.getAll(); } @NotNull public static GithubCommitDetailed getCommit(@NotNull GithubAuthData auth, @NotNull String user, @NotNull String repo, @NotNull String sha) throws IOException { String path = "/repos/" + user + "/" + repo + "/commits/" + sha; JsonElement result = getRequest(auth, path); return createDataFromRaw(fromJson(result, GithubCommitRaw.class), GithubCommitDetailed.class); } @NotNull public static GithubPullRequest getPullRequest(@NotNull GithubAuthData auth, @NotNull String user, @NotNull String repo, int id) throws IOException { String path = "/repos/" + user + "/" + repo + "/pulls/" + id; return createDataFromRaw(fromJson(getRequest(auth, path), GithubPullRequestRaw.class), GithubPullRequest.class); } @NotNull public static List<GithubPullRequest> getPullRequests(@NotNull GithubAuthData auth, @NotNull String user, @NotNull String repo) throws IOException { String path = "/repos/" + user + "/" + repo + "/pulls?per_page=100"; PagedRequest<GithubPullRequest, GithubPullRequestRaw> request = new PagedRequest<GithubPullRequest, GithubPullRequestRaw>(auth, path, GithubPullRequest.class, GithubPullRequestRaw[].class); return request.getAll(); } @NotNull public static List<GithubCommit> getPullRequestCommits(@NotNull GithubAuthData auth, @NotNull String user, @NotNull String repo, long id) throws IOException { String path = "/repos/" + user + "/" + repo + "/pulls/" + id + "/commits?per_page=100"; PagedRequest<GithubCommit, GithubCommitRaw> request = new PagedRequest<GithubCommit, GithubCommitRaw>(auth, path, GithubCommit.class, GithubCommitRaw[].class); return request.getAll(); } @NotNull public static List<GithubFile> getPullRequestFiles(@NotNull GithubAuthData auth, @NotNull String user, @NotNull String repo, long id) throws IOException { String path = "/repos/" + user + "/" + repo + "/pulls/" + id + "/files?per_page=100"; PagedRequest<GithubFile, GithubFileRaw> request = new PagedRequest<GithubFile, GithubFileRaw>(auth, path, GithubFile.class, GithubFileRaw[].class); return request.getAll(); } @NotNull public static List<GithubBranch> getRepoBranches(@NotNull GithubAuthData auth, @NotNull String user, @NotNull String repo) throws IOException { String path = "/repos/" + user + "/" + repo + "/branches?per_page=100"; PagedRequest<GithubBranch, GithubBranchRaw> request = new PagedRequest<GithubBranch, GithubBranchRaw>(auth, path, GithubBranch.class, GithubBranchRaw[].class); return request.getAll(); } @Nullable public static GithubRepo findForkByUser(@NotNull GithubAuthData auth, @NotNull String user, @NotNull String repo, @NotNull String forkUser) throws IOException { String path = "/repos/" + user + "/" + repo + "/forks?per_page=100"; PagedRequest<GithubRepo, GithubRepoRaw> request = new PagedRequest<GithubRepo, GithubRepoRaw>(auth, path, GithubRepo.class, GithubRepoRaw[].class); while (request.hasNext()) { for (GithubRepo fork : request.next()) { if (StringUtil.equalsIgnoreCase(fork.getUserName(), forkUser)) { return fork; } } } return null; } }
Github: make pagination public - for delayed page requests
plugins/github/src/org/jetbrains/plugins/github/api/GithubApiUtil.java
Github: make pagination public - for delayed page requests
Java
apache-2.0
8110e0b5f0d2b1a9e468489ba52e57431b753fff
0
nicolargo/intellij-community,clumsy/intellij-community,allotria/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,petteyg/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,holmes/intellij-community,akosyakov/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,caot/intellij-community,hurricup/intellij-community,fnouama/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,slisson/intellij-community,fnouama/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,petteyg/intellij-community,supersven/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,da1z/intellij-community,slisson/intellij-community,petteyg/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,izonder/intellij-community,da1z/intellij-community,adedayo/intellij-community,retomerz/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,slisson/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,samthor/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,ryano144/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,robovm/robovm-studio,holmes/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,caot/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,signed/intellij-community,petteyg/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,holmes/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,slisson/intellij-community,adedayo/intellij-community,ryano144/intellij-community,allotria/intellij-community,caot/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,da1z/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,izonder/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,FHannes/intellij-community,amith01994/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,diorcety/intellij-community,ibinti/intellij-community,vladmm/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,da1z/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,izonder/intellij-community,jagguli/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,caot/intellij-community,FHannes/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,kool79/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,hurricup/intellij-community,hurricup/intellij-community,semonte/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,caot/intellij-community,allotria/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,kdwink/intellij-community,adedayo/intellij-community,samthor/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,caot/intellij-community,vladmm/intellij-community,amith01994/intellij-community,semonte/intellij-community,xfournet/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,allotria/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,hurricup/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,supersven/intellij-community,blademainer/intellij-community,semonte/intellij-community,adedayo/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,signed/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,signed/intellij-community,petteyg/intellij-community,slisson/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,izonder/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,kool79/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,samthor/intellij-community,samthor/intellij-community,slisson/intellij-community,amith01994/intellij-community,caot/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,semonte/intellij-community,ahb0327/intellij-community,caot/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,signed/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,clumsy/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,slisson/intellij-community,ibinti/intellij-community,slisson/intellij-community,kdwink/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,kool79/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,supersven/intellij-community,signed/intellij-community,ahb0327/intellij-community,holmes/intellij-community,Lekanich/intellij-community,supersven/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,vladmm/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,signed/intellij-community,clumsy/intellij-community,signed/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,vladmm/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,fitermay/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,Lekanich/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,vladmm/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,fnouama/intellij-community,apixandru/intellij-community,ibinti/intellij-community,FHannes/intellij-community,clumsy/intellij-community,samthor/intellij-community,FHannes/intellij-community,FHannes/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,apixandru/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,supersven/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,semonte/intellij-community,izonder/intellij-community,diorcety/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,kdwink/intellij-community,dslomov/intellij-community,izonder/intellij-community,semonte/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,holmes/intellij-community,xfournet/intellij-community,caot/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,signed/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,izonder/intellij-community,allotria/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,kool79/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,allotria/intellij-community,kool79/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,signed/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,FHannes/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,supersven/intellij-community,robovm/robovm-studio,signed/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,supersven/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,semonte/intellij-community,da1z/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,Lekanich/intellij-community,supersven/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,kool79/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,fnouama/intellij-community,ibinti/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,allotria/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.util.indexing; import com.intellij.AppTopics; import com.intellij.history.LocalHistory; import com.intellij.ide.util.DelegatingProgressIndicator; import com.intellij.lang.ASTNode; import com.intellij.notification.NotificationDisplayType; import com.intellij.notification.NotificationGroup; import com.intellij.notification.NotificationType; import com.intellij.openapi.application.ApplicationAdapter; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.impl.EditorHighlighterCache; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.FileDocumentManagerAdapter; import com.intellij.openapi.fileTypes.*; import com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator; import com.intellij.openapi.project.*; import com.intellij.openapi.roots.*; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.impl.BulkVirtualFileListenerAdapter; import com.intellij.openapi.vfs.newvfs.BulkFileListener; import com.intellij.openapi.vfs.newvfs.ManagingFS; import com.intellij.openapi.vfs.newvfs.NewVirtualFile; import com.intellij.openapi.vfs.newvfs.events.VFileEvent; import com.intellij.openapi.vfs.newvfs.impl.VirtualFileSystemEntry; import com.intellij.openapi.vfs.newvfs.persistent.FlushingDaemon; import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS; import com.intellij.psi.*; import com.intellij.psi.impl.PsiDocumentTransactionListener; import com.intellij.psi.impl.PsiManagerImpl; import com.intellij.psi.impl.PsiTreeChangeEventImpl; import com.intellij.psi.impl.PsiTreeChangePreprocessor; import com.intellij.psi.impl.cache.impl.id.IdIndex; import com.intellij.psi.impl.cache.impl.id.PlatformIdTableBuilding; import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.psi.search.EverythingGlobalScope; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.stubs.SerializationManagerEx; import com.intellij.util.*; import com.intellij.util.concurrency.Semaphore; import com.intellij.util.containers.ConcurrentHashSet; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.io.*; import com.intellij.util.io.DataOutputStream; import com.intellij.util.io.storage.HeavyProcessLatch; import com.intellij.util.messages.MessageBus; import com.intellij.util.messages.MessageBusConnection; import gnu.trove.*; import jsr166e.extra.SequenceLock; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.*; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Lock; /** * @author Eugene Zhuravlev * @since Dec 20, 2007 */ public class FileBasedIndexImpl extends FileBasedIndex { private static final Logger LOG = Logger.getInstance("#com.intellij.util.indexing.FileBasedIndexImpl"); @NonNls private static final String CORRUPTION_MARKER_NAME = "corruption.marker"; private final Map<ID<?, ?>, Pair<UpdatableIndex<?, ?, FileContent>, InputFilter>> myIndices = new THashMap<ID<?, ?>, Pair<UpdatableIndex<?, ?, FileContent>, InputFilter>>(); private final List<ID<?, ?>> myIndicesWithoutFileTypeInfo = new ArrayList<ID<?, ?>>(); private final Map<FileType, List<ID<?, ?>>> myFileType2IndicesWithFileTypeInfoMap = new THashMap<FileType, List<ID<?, ?>>>(); private final List<ID<?, ?>> myIndicesForDirectories = new SmartList<ID<?, ?>>(); private final Map<ID<?, ?>, Semaphore> myUnsavedDataIndexingSemaphores = new THashMap<ID<?, ?>, Semaphore>(); private final TObjectIntHashMap<ID<?, ?>> myIndexIdToVersionMap = new TObjectIntHashMap<ID<?, ?>>(); private final Set<ID<?, ?>> myNotRequiringContentIndices = new THashSet<ID<?, ?>>(); private final Set<ID<?, ?>> myRequiringContentIndices = new THashSet<ID<?, ?>>(); private final Set<ID<?, ?>> myPsiDependentIndices = new THashSet<ID<?, ?>>(); private final Set<FileType> myNoLimitCheckTypes = new THashSet<FileType>(); private final PerIndexDocumentVersionMap myLastIndexedDocStamps = new PerIndexDocumentVersionMap(); @NotNull private final ChangedFilesCollector myChangedFilesCollector; private final List<IndexableFileSet> myIndexableSets = ContainerUtil.createLockFreeCopyOnWriteList(); private final Map<IndexableFileSet, Project> myIndexableSetToProjectMap = new THashMap<IndexableFileSet, Project>(); private static final int OK = 1; private static final int REQUIRES_REBUILD = 2; private static final int REBUILD_IN_PROGRESS = 3; private static final Map<ID<?, ?>, AtomicInteger> ourRebuildStatus = new THashMap<ID<?, ?>, AtomicInteger>(); private final MessageBusConnection myConnection; private final FileDocumentManager myFileDocumentManager; private final FileTypeManagerImpl myFileTypeManager; private final SerializationManagerEx mySerializationManagerEx; private final ConcurrentHashSet<ID<?, ?>> myUpToDateIndicesForUnsavedOrTransactedDocuments = new ConcurrentHashSet<ID<?, ?>>(); private volatile SmartFMap<Document, PsiFile> myTransactionMap = SmartFMap.emptyMap(); @Nullable private final String myConfigPath; @Nullable private final String myLogPath; private final boolean myIsUnitTestMode; @Nullable private ScheduledFuture<?> myFlushingFuture; private volatile int myLocalModCount; private volatile int myFilesModCount; private final AtomicInteger myUpdatingFiles = new AtomicInteger(); private final ConcurrentHashSet<Project> myProjectsBeingUpdated = new ConcurrentHashSet<Project>(); @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"}) private volatile boolean myInitialized; // need this variable for memory barrier public FileBasedIndexImpl(@SuppressWarnings("UnusedParameters") VirtualFileManager vfManager, FileDocumentManager fdm, FileTypeManagerImpl fileTypeManager, @NotNull MessageBus bus, SerializationManagerEx sm) { myFileDocumentManager = fdm; myFileTypeManager = fileTypeManager; mySerializationManagerEx = sm; myIsUnitTestMode = ApplicationManager.getApplication().isUnitTestMode(); myConfigPath = calcConfigPath(PathManager.getConfigPath()); myLogPath = calcConfigPath(PathManager.getLogPath()); final MessageBusConnection connection = bus.connect(); connection.subscribe(PsiDocumentTransactionListener.TOPIC, new PsiDocumentTransactionListener() { @Override public void transactionStarted(@NotNull final Document doc, @NotNull final PsiFile file) { myTransactionMap = myTransactionMap.plus(doc, file); myUpToDateIndicesForUnsavedOrTransactedDocuments.clear(); } @Override public void transactionCompleted(@NotNull final Document doc, @NotNull final PsiFile file) { myTransactionMap = myTransactionMap.minus(doc); } }); connection.subscribe(FileTypeManager.TOPIC, new FileTypeListener() { @Nullable private Map<FileType, Set<String>> myTypeToExtensionMap; @Override public void beforeFileTypesChanged(@NotNull final FileTypeEvent event) { cleanupProcessedFlag(); myTypeToExtensionMap = new THashMap<FileType, Set<String>>(); for (FileType type : myFileTypeManager.getRegisteredFileTypes()) { myTypeToExtensionMap.put(type, getExtensions(type)); } } @Override public void fileTypesChanged(@NotNull final FileTypeEvent event) { final Map<FileType, Set<String>> oldExtensions = myTypeToExtensionMap; myTypeToExtensionMap = null; if (oldExtensions != null) { final Map<FileType, Set<String>> newExtensions = new THashMap<FileType, Set<String>>(); for (FileType type : myFileTypeManager.getRegisteredFileTypes()) { newExtensions.put(type, getExtensions(type)); } // we are interested only in extension changes or removals. // addition of an extension is handled separately by RootsChanged event if (!newExtensions.keySet().containsAll(oldExtensions.keySet())) { rebuildAllIndices(); return; } for (Map.Entry<FileType, Set<String>> entry : oldExtensions.entrySet()) { FileType fileType = entry.getKey(); Set<String> strings = entry.getValue(); if (!newExtensions.get(fileType).containsAll(strings)) { rebuildAllIndices(); return; } } } } @NotNull private Set<String> getExtensions(@NotNull FileType type) { final Set<String> set = new THashSet<String>(); for (FileNameMatcher matcher : myFileTypeManager.getAssociations(type)) { set.add(matcher.getPresentableString()); } return set; } private void rebuildAllIndices() { IndexingStamp.flushCaches(); for (ID<?, ?> indexId : myIndices.keySet()) { try { clearIndex(indexId); } catch (StorageException e) { LOG.info(e); } } scheduleIndexRebuild(); } }); connection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, new FileDocumentManagerAdapter() { @Override public void fileContentReloaded(@NotNull VirtualFile file, @NotNull Document document) { cleanupMemoryStorage(); } @Override public void unsavedDocumentsDropped() { cleanupMemoryStorage(); } }); ApplicationManager.getApplication().addApplicationListener(new ApplicationAdapter() { @Override public void writeActionStarted(Object action) { myUpToDateIndicesForUnsavedOrTransactedDocuments.clear(); } }); myChangedFilesCollector = new ChangedFilesCollector(); myConnection = connection; } public static boolean isProjectOrWorkspaceFile(@NotNull VirtualFile file, @Nullable FileType fileType) { if (fileType instanceof InternalFileType) return true; VirtualFile parent = file.isDirectory() ? file: file.getParent(); while(parent instanceof VirtualFileSystemEntry) { if (((VirtualFileSystemEntry)parent).compareNameTo(ProjectCoreUtil.DIRECTORY_BASED_PROJECT_DIR, !SystemInfoRt.isFileSystemCaseSensitive) == 0) return true; parent = parent.getParent(); } return false; } @Override public void requestReindex(@NotNull final VirtualFile file) { myChangedFilesCollector.invalidateIndices(file, true); } private void initExtensions() { try { final FileBasedIndexExtension[] extensions = Extensions.getExtensions(FileBasedIndexExtension.EXTENSION_POINT_NAME); for (FileBasedIndexExtension<?, ?> extension : extensions) { ourRebuildStatus.put(extension.getName(), new AtomicInteger(OK)); } final File corruptionMarker = new File(PathManager.getIndexRoot(), CORRUPTION_MARKER_NAME); final boolean currentVersionCorrupted = corruptionMarker.exists(); boolean versionChanged = false; for (FileBasedIndexExtension<?, ?> extension : extensions) { versionChanged |= registerIndexer(extension, currentVersionCorrupted); } for(List<ID<?, ?>> value: myFileType2IndicesWithFileTypeInfoMap.values()) { value.addAll(myIndicesWithoutFileTypeInfo); } FileUtil.delete(corruptionMarker); String rebuildNotification = null; if (currentVersionCorrupted) { rebuildNotification = "Index files on disk are corrupted. Indices will be rebuilt."; } else if (versionChanged) { rebuildNotification = "Index file format has changed for some indices. These indices will be rebuilt."; } if (rebuildNotification != null && !ApplicationManager.getApplication().isHeadlessEnvironment() && Registry.is("ide.showIndexRebuildMessage")) { new NotificationGroup("Indexing", NotificationDisplayType.BALLOON, false) .createNotification("Index Rebuild", rebuildNotification, NotificationType.INFORMATION, null).notify(null); } dropUnregisteredIndices(); // check if rebuild was requested for any index during registration for (ID<?, ?> indexId : myIndices.keySet()) { if (ourRebuildStatus.get(indexId).compareAndSet(REQUIRES_REBUILD, OK)) { try { clearIndex(indexId); } catch (StorageException e) { requestRebuild(indexId); LOG.error(e); } } } myConnection.subscribe(VirtualFileManager.VFS_CHANGES, myChangedFilesCollector); registerIndexableSet(new AdditionalIndexableFileSet(), null); } catch (IOException e) { throw new RuntimeException(e); } finally { ShutDownTracker.getInstance().registerShutdownTask(new Runnable() { @Override public void run() { performShutdown(); } }); saveRegisteredIndices(myIndices.keySet()); myFlushingFuture = FlushingDaemon.everyFiveSeconds(new Runnable() { private int lastModCount = 0; @Override public void run() { if (lastModCount == myLocalModCount) { flushAllIndices(lastModCount); } lastModCount = myLocalModCount; } }); myInitialized = true; // this will ensure that all changes to component's state will be visible to other threads } } @Override public void initComponent() { initExtensions(); } @Nullable private static String calcConfigPath(@NotNull String path) { try { final String _path = FileUtil.toSystemIndependentName(new File(path).getCanonicalPath()); return _path.endsWith("/") ? _path : _path + "/"; } catch (IOException e) { LOG.info(e); return null; } } /** * @return true if registered index requires full rebuild for some reason, e.g. is just created or corrupted */ private <K, V> boolean registerIndexer(@NotNull final FileBasedIndexExtension<K, V> extension, final boolean isCurrentVersionCorrupted) throws IOException { final ID<K, V> name = extension.getName(); final int version = extension.getVersion(); final File versionFile = IndexInfrastructure.getVersionFile(name); final boolean versionFileExisted = versionFile.exists(); boolean versionChanged = false; if (isCurrentVersionCorrupted || IndexingStamp.versionDiffers(versionFile, version)) { if (!isCurrentVersionCorrupted && versionFileExisted) { versionChanged = true; LOG.info("Version has changed for index " + name + ". The index will be rebuilt."); } if (extension.hasSnapshotMapping() && (isCurrentVersionCorrupted || versionChanged)) { safeDelete(IndexInfrastructure.getPersistentIndexRootDir(name)); } safeDelete(IndexInfrastructure.getIndexRootDir(name)); IndexingStamp.rewriteVersion(versionFile, version); } initIndexStorage(extension, version, versionFile); return versionChanged; } private <K, V> void initIndexStorage(@NotNull FileBasedIndexExtension<K, V> extension, int version, @NotNull File versionFile) throws IOException { MapIndexStorage<K, V> storage = null; final ID<K, V> name = extension.getName(); boolean contentHashesEnumeratorOk = false; for (int attempt = 0; attempt < 2; attempt++) { try { if (extension.hasSnapshotMapping()) { ContentHashesSupport.initContentHashesEnumerator(); contentHashesEnumeratorOk = true; } storage = new MapIndexStorage<K, V>( IndexInfrastructure.getStorageFile(name), extension.getKeyDescriptor(), extension.getValueExternalizer(), extension.getCacheSize(), extension.isKeyHighlySelective(), extension.traceKeyHashToVirtualFileMapping() ); final MemoryIndexStorage<K, V> memStorage = new MemoryIndexStorage<K, V>(storage); final UpdatableIndex<K, V, FileContent> index = createIndex(name, extension, memStorage); final InputFilter inputFilter = extension.getInputFilter(); myIndices.put(name, new Pair<UpdatableIndex<?, ?, FileContent>, InputFilter>(index, new IndexableFilesFilter(inputFilter))); if (inputFilter instanceof FileTypeSpecificInputFilter) { ((FileTypeSpecificInputFilter)inputFilter).registerFileTypesUsedForIndexing(new Consumer<FileType>() { final Set<FileType> addedTypes = new THashSet<FileType>(); @Override public void consume(FileType type) { if (type == null || !addedTypes.add(type)) { return; } List<ID<?, ?>> ids = myFileType2IndicesWithFileTypeInfoMap.get(type); if (ids == null) myFileType2IndicesWithFileTypeInfoMap.put(type, ids = new ArrayList<ID<?, ?>>(5)); ids.add(name); } }); } else { myIndicesWithoutFileTypeInfo.add(name); } myUnsavedDataIndexingSemaphores.put(name, new Semaphore()); myIndexIdToVersionMap.put(name, version); if (!extension.dependsOnFileContent()) { if (extension.indexDirectories()) myIndicesForDirectories.add(name); myNotRequiringContentIndices.add(name); } else { myRequiringContentIndices.add(name); } if (extension instanceof PsiDependentIndex) myPsiDependentIndices.add(name); myNoLimitCheckTypes.addAll(extension.getFileTypesWithSizeLimitNotApplicable()); break; } catch (Exception e) { LOG.info(e); boolean instantiatedStorage = storage != null; try { if (storage != null) storage.close(); storage = null; } catch (Exception ignored) { } safeDelete(IndexInfrastructure.getIndexRootDir(name)); if (extension.hasSnapshotMapping() && (!contentHashesEnumeratorOk || instantiatedStorage)) { safeDelete(IndexInfrastructure.getPersistentIndexRootDir(name)); // todo there is possibility of corruption of storage and content hashes } IndexingStamp.rewriteVersion(versionFile, version); } } } private static boolean safeDelete(File dir) { File directory = FileUtil.findSequentNonexistentFile(dir.getParentFile(), dir.getName(), ""); boolean success = dir.renameTo(directory); return FileUtil.delete(success ? directory:dir); } private static void saveRegisteredIndices(@NotNull Collection<ID<?, ?>> ids) { final File file = getRegisteredIndicesFile(); try { FileUtil.createIfDoesntExist(file); final DataOutputStream os = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); try { os.writeInt(ids.size()); for (ID<?, ?> id : ids) { IOUtil.writeString(id.toString(), os); } } finally { os.close(); } } catch (IOException ignored) { } } @NotNull private static Set<String> readRegisteredIndexNames() { final Set<String> result = new THashSet<String>(); try { final DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(getRegisteredIndicesFile()))); try { final int size = in.readInt(); for (int idx = 0; idx < size; idx++) { result.add(IOUtil.readString(in)); } } finally { in.close(); } } catch (IOException ignored) { } return result; } @NotNull private static File getRegisteredIndicesFile() { return new File(PathManager.getIndexRoot(), "registered"); } @NotNull private <K, V> UpdatableIndex<K, V, FileContent> createIndex(@NotNull final ID<K, V> indexId, @NotNull final FileBasedIndexExtension<K, V> extension, @NotNull final MemoryIndexStorage<K, V> storage) throws StorageException, IOException { final MapReduceIndex<K, V, FileContent> index; if (extension instanceof CustomImplementationFileBasedIndexExtension) { final UpdatableIndex<K, V, FileContent> custom = ((CustomImplementationFileBasedIndexExtension<K, V, FileContent>)extension).createIndexImplementation(indexId, this, storage); if (!(custom instanceof MapReduceIndex)) { return custom; } index = (MapReduceIndex<K, V, FileContent>)custom; } else { DataExternalizer<Collection<K>> externalizer = extension.hasSnapshotMapping() && IdIndex.ourSnapshotMappingsEnabled ? createInputsIndexExternalizer(extension, indexId, extension.getKeyDescriptor()) : null; index = new MapReduceIndex<K, V, FileContent>(indexId, extension.getIndexer(), storage, externalizer, extension.getValueExternalizer()); } index.setInputIdToDataKeysIndex(new Factory<PersistentHashMap<Integer, Collection<K>>>() { @Override public PersistentHashMap<Integer, Collection<K>> create() { try { return createIdToDataKeysIndex(extension, storage); } catch (IOException e) { throw new RuntimeException(e); } } }); return index; } @NotNull public static <K> PersistentHashMap<Integer, Collection<K>> createIdToDataKeysIndex(@NotNull FileBasedIndexExtension <K, ?> extension, @NotNull MemoryIndexStorage<K, ?> storage) throws IOException { ID<K, ?> indexId = extension.getName(); KeyDescriptor<K> keyDescriptor = extension.getKeyDescriptor(); final File indexStorageFile = IndexInfrastructure.getInputIndexStorageFile(indexId); final AtomicBoolean isBufferingMode = new AtomicBoolean(); final TIntObjectHashMap<Collection<K>> tempMap = new TIntObjectHashMap<Collection<K>>(); // Important! Update IdToDataKeysIndex depending on the sate of "buffering" flag from the MemoryStorage. // If buffering is on, all changes should be done in memory (similar to the way it is done in memory storage). // Otherwise data in IdToDataKeysIndex will not be in sync with the 'main' data in the index on disk and index updates will be based on the // wrong sets of keys for the given file. This will lead to unpredictable results in main index because it will not be // cleared properly before updating (removed data will still be present on disk). See IDEA-52223 for illustration of possible effects. final PersistentHashMap<Integer, Collection<K>> map = new PersistentHashMap<Integer, Collection<K>>( indexStorageFile, EnumeratorIntegerDescriptor.INSTANCE, createInputsIndexExternalizer(extension, indexId, keyDescriptor) ) { @Override protected Collection<K> doGet(Integer integer) throws IOException { if (isBufferingMode.get()) { final Collection<K> collection = tempMap.get(integer); if (collection != null) { return collection; } } return super.doGet(integer); } @Override protected void doPut(Integer integer, @Nullable Collection<K> ks) throws IOException { if (isBufferingMode.get()) { tempMap.put(integer, ks == null ? Collections.<K>emptySet() : ks); } else { super.doPut(integer, ks); } } @Override protected void doRemove(Integer integer) throws IOException { if (isBufferingMode.get()) { tempMap.put(integer, Collections.<K>emptySet()); } else { super.doRemove(integer); } } }; storage.addBufferingStateListener(new MemoryIndexStorage.BufferingStateListener() { @Override public void bufferingStateChanged(boolean newState) { synchronized (map) { isBufferingMode.set(newState); } } @Override public void memoryStorageCleared() { synchronized (map) { tempMap.clear(); } } }); return map; } private static <K> DataExternalizer<Collection<K>> createInputsIndexExternalizer(FileBasedIndexExtension<K, ?> extension, ID<K, ?> indexId, KeyDescriptor<K> keyDescriptor) { DataExternalizer<Collection<K>> externalizer; if (extension instanceof CustomInputsIndexFileBasedIndexExtension) { externalizer = ((CustomInputsIndexFileBasedIndexExtension<K>)extension).createExternalizer(); } else { externalizer = new InputIndexDataExternalizer<K>(keyDescriptor, indexId); } return externalizer; } @Override public void disposeComponent() { performShutdown(); } private final AtomicBoolean myShutdownPerformed = new AtomicBoolean(false); private void performShutdown() { if (!myShutdownPerformed.compareAndSet(false, true)) { return; // already shut down } try { if (myFlushingFuture != null) { myFlushingFuture.cancel(false); myFlushingFuture = null; } //myFileDocumentManager.saveAllDocuments(); // rev=Eugene Juravlev } finally { LOG.info("START INDEX SHUTDOWN"); try { myChangedFilesCollector.ensureAllInvalidateTasksCompleted(); IndexingStamp.flushCaches(); for (ID<?, ?> indexId : myIndices.keySet()) { final UpdatableIndex<?, ?, FileContent> index = getIndex(indexId); assert index != null; checkRebuild(indexId, true); // if the index was scheduled for rebuild, only clean it index.dispose(); } myConnection.disconnect(); } catch (Throwable e) { LOG.error("Problems during index shutdown", e); } LOG.info("END INDEX SHUTDOWN"); } } private void flushAllIndices(final long modCount) { if (HeavyProcessLatch.INSTANCE.isRunning()) { return; } IndexingStamp.flushCaches(); for (ID<?, ?> indexId : new ArrayList<ID<?, ?>>(myIndices.keySet())) { if (HeavyProcessLatch.INSTANCE.isRunning() || modCount != myLocalModCount) { return; // do not interfere with 'main' jobs } try { final UpdatableIndex<?, ?, FileContent> index = getIndex(indexId); if (index != null) { index.flush(); } } catch (StorageException e) { LOG.info(e); requestRebuild(indexId); } } if (!HeavyProcessLatch.INSTANCE.isRunning() && modCount == myLocalModCount) { // do not interfere with 'main' jobs mySerializationManagerEx.flushNameStorage(); } } @Override @NotNull public <K> Collection<K> getAllKeys(@NotNull final ID<K, ?> indexId, @NotNull Project project) { Set<K> allKeys = new THashSet<K>(); processAllKeys(indexId, new CommonProcessors.CollectProcessor<K>(allKeys), project); return allKeys; } @Override public <K> boolean processAllKeys(@NotNull final ID<K, ?> indexId, @NotNull Processor<K> processor, @Nullable Project project) { return processAllKeys(indexId, processor, project == null ? new EverythingGlobalScope() : GlobalSearchScope.allScope(project), null); } @Override public <K> boolean processAllKeys(@NotNull ID<K, ?> indexId, @NotNull Processor<K> processor, @NotNull GlobalSearchScope scope, @Nullable IdFilter idFilter) { try { final UpdatableIndex<K, ?, FileContent> index = getIndex(indexId); if (index == null) { return true; } ensureUpToDate(indexId, scope.getProject(), scope); return index.processAllKeys(processor, scope, idFilter); } catch (StorageException e) { scheduleRebuild(indexId, e); } catch (RuntimeException e) { final Throwable cause = e.getCause(); if (cause instanceof StorageException || cause instanceof IOException) { scheduleRebuild(indexId, cause); } else { throw e; } } return false; } private static final ThreadLocal<Integer> myUpToDateCheckState = new ThreadLocal<Integer>(); public static void disableUpToDateCheckForCurrentThread() { final Integer currentValue = myUpToDateCheckState.get(); myUpToDateCheckState.set(currentValue == null ? 1 : currentValue.intValue() + 1); } public static void enableUpToDateCheckForCurrentThread() { final Integer currentValue = myUpToDateCheckState.get(); if (currentValue != null) { final int newValue = currentValue.intValue() - 1; if (newValue != 0) { myUpToDateCheckState.set(newValue); } else { myUpToDateCheckState.remove(); } } } private static boolean isUpToDateCheckEnabled() { final Integer value = myUpToDateCheckState.get(); return value == null || value.intValue() == 0; } private final ThreadLocal<Boolean> myReentrancyGuard = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return Boolean.FALSE; } }; /** * DO NOT CALL DIRECTLY IN CLIENT CODE * The method is internal to indexing engine end is called internally. The method is public due to implementation details */ @Override public <K> void ensureUpToDate(@NotNull final ID<K, ?> indexId, @Nullable Project project, @Nullable GlobalSearchScope filter) { ensureUpToDate(indexId, project, filter, null); } protected <K> void ensureUpToDate(@NotNull final ID<K, ?> indexId, @Nullable Project project, @Nullable GlobalSearchScope filter, @Nullable VirtualFile restrictedFile) { ProgressManager.checkCanceled(); myContentlessIndicesUpdateQueue.ensureUpToDate(); // some content full indices depends on contentless ones if (!needsFileContentLoading(indexId)) { return; //indexed eagerly in foreground while building unindexed file list } if (filter == GlobalSearchScope.EMPTY_SCOPE) { return; } if (isDumb(project)) { handleDumbMode(project); } if (myReentrancyGuard.get().booleanValue()) { //assert false : "ensureUpToDate() is not reentrant!"; return; } myReentrancyGuard.set(Boolean.TRUE); try { myChangedFilesCollector.ensureAllInvalidateTasksCompleted(); if (isUpToDateCheckEnabled()) { try { checkRebuild(indexId, false); myChangedFilesCollector.forceUpdate(project, filter, restrictedFile); indexUnsavedDocuments(indexId, project, filter, restrictedFile); } catch (StorageException e) { scheduleRebuild(indexId, e); } catch (RuntimeException e) { final Throwable cause = e.getCause(); if (cause instanceof StorageException || cause instanceof IOException) { scheduleRebuild(indexId, e); } else { throw e; } } } } finally { myReentrancyGuard.set(Boolean.FALSE); } } private static void handleDumbMode(@Nullable Project project) { ProgressManager.checkCanceled(); // DumbModeAction.CANCEL if (project != null) { final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); if (progressIndicator instanceof BackgroundableProcessIndicator) { final BackgroundableProcessIndicator indicator = (BackgroundableProcessIndicator)progressIndicator; if (indicator.getDumbModeAction() == DumbModeAction.WAIT) { assert !ApplicationManager.getApplication().isDispatchThread(); DumbService.getInstance(project).waitForSmartMode(); return; } } } throw new IndexNotReadyException(); } private static boolean isDumb(@Nullable Project project) { if (project != null) { return DumbServiceImpl.getInstance(project).isDumb(); } for (Project proj : ProjectManager.getInstance().getOpenProjects()) { if (DumbServiceImpl.getInstance(proj).isDumb()) { return true; } } return false; } @Override @NotNull public <K, V> List<V> getValues(@NotNull final ID<K, V> indexId, @NotNull K dataKey, @NotNull final GlobalSearchScope filter) { final List<V> values = new SmartList<V>(); processValuesImpl(indexId, dataKey, true, null, new ValueProcessor<V>() { @Override public boolean process(final VirtualFile file, final V value) { values.add(value); return true; } }, filter, null); return values; } @Override @NotNull public <K, V> Collection<VirtualFile> getContainingFiles(@NotNull final ID<K, V> indexId, @NotNull K dataKey, @NotNull final GlobalSearchScope filter) { final Set<VirtualFile> files = new THashSet<VirtualFile>(); processValuesImpl(indexId, dataKey, false, null, new ValueProcessor<V>() { @Override public boolean process(final VirtualFile file, final V value) { files.add(file); return true; } }, filter, null); return files; } @Override public <K, V> boolean processValues(@NotNull final ID<K, V> indexId, @NotNull final K dataKey, @Nullable final VirtualFile inFile, @NotNull ValueProcessor<V> processor, @NotNull final GlobalSearchScope filter) { return processValues(indexId, dataKey, inFile, processor, filter, null); } @Override public <K, V> boolean processValues(@NotNull ID<K, V> indexId, @NotNull K dataKey, @Nullable VirtualFile inFile, @NotNull ValueProcessor<V> processor, @NotNull GlobalSearchScope filter, @Nullable IdFilter idFilter) { return processValuesImpl(indexId, dataKey, false, inFile, processor, filter, idFilter); } @Nullable private <K, V, R> R processExceptions(@NotNull final ID<K, V> indexId, @Nullable final VirtualFile restrictToFile, @NotNull final GlobalSearchScope filter, @NotNull ThrowableConvertor<UpdatableIndex<K, V, FileContent>, R, StorageException> computable) { try { final UpdatableIndex<K, V, FileContent> index = getIndex(indexId); if (index == null) { return null; } final Project project = filter.getProject(); //assert project != null : "GlobalSearchScope#getProject() should be not-null for all index queries"; ensureUpToDate(indexId, project, filter, restrictToFile); try { index.getReadLock().lock(); return computable.convert(index); } finally { index.getReadLock().unlock(); } } catch (StorageException e) { scheduleRebuild(indexId, e); } catch (RuntimeException e) { final Throwable cause = getCauseToRebuildIndex(e); if (cause != null) { scheduleRebuild(indexId, cause); } else { throw e; } } catch(AssertionError ae) { scheduleRebuild(indexId, ae); } return null; } private <K, V> boolean processValuesImpl(@NotNull final ID<K, V> indexId, @NotNull final K dataKey, final boolean ensureValueProcessedOnce, @Nullable final VirtualFile restrictToFile, @NotNull final ValueProcessor<V> processor, @NotNull final GlobalSearchScope scope, @Nullable final IdFilter idFilter) { ThrowableConvertor<UpdatableIndex<K, V, FileContent>, Boolean, StorageException> keyProcessor = new ThrowableConvertor<UpdatableIndex<K, V, FileContent>, Boolean, StorageException>() { @Override public Boolean convert(@NotNull UpdatableIndex<K, V, FileContent> index) throws StorageException { final ValueContainer<V> container = index.getData(dataKey); boolean shouldContinue = true; if (restrictToFile != null) { if (restrictToFile instanceof VirtualFileWithId) { final int restrictedFileId = getFileId(restrictToFile); for (final Iterator<V> valueIt = container.getValueIterator(); valueIt.hasNext(); ) { final V value = valueIt.next(); if (container.isAssociated(value, restrictedFileId)) { shouldContinue = processor.process(restrictToFile, value); if (!shouldContinue) { break; } } } } } else { final PersistentFS fs = (PersistentFS)ManagingFS.getInstance(); final IdFilter filter = idFilter != null ? idFilter : projectIndexableFiles(scope.getProject()); VALUES_LOOP: for (final Iterator<V> valueIt = container.getValueIterator(); valueIt.hasNext(); ) { final V value = valueIt.next(); for (final ValueContainer.IntIterator inputIdsIterator = container.getInputIdsIterator(value); inputIdsIterator.hasNext(); ) { final int id = inputIdsIterator.next(); if (filter != null && !filter.containsFileId(id)) continue; VirtualFile file = IndexInfrastructure.findFileByIdIfCached(fs, id); if (file != null && scope.accept(file)) { shouldContinue = processor.process(file, value); if (!shouldContinue) { break VALUES_LOOP; } if (ensureValueProcessedOnce) { break; // continue with the next value } } } } } return shouldContinue; } }; final Boolean result = processExceptions(indexId, restrictToFile, scope, keyProcessor); return result == null || result.booleanValue(); } @Override public <K, V> boolean processFilesContainingAllKeys(@NotNull final ID<K, V> indexId, @NotNull final Collection<K> dataKeys, @NotNull final GlobalSearchScope filter, @Nullable Condition<V> valueChecker, @NotNull final Processor<VirtualFile> processor) { ProjectIndexableFilesFilter filesSet = projectIndexableFiles(filter.getProject()); final TIntHashSet set = collectFileIdsContainingAllKeys(indexId, dataKeys, filter, valueChecker, filesSet); return set != null && processVirtualFiles(set, filter, processor); } private static final Key<SoftReference<ProjectIndexableFilesFilter>> ourProjectFilesSetKey = Key.create("projectFiles"); public void filesUpdateEnumerationFinished() { myContentlessIndicesUpdateQueue.ensureUpToDate(); myContentlessIndicesUpdateQueue.signalUpdateEnd(); } public static final class ProjectIndexableFilesFilter extends IdFilter { private static final int SHIFT = 6; private static final int MASK = (1 << SHIFT) - 1; private final long[] myBitMask; private final int myModificationCount; private final int myMinId; private final int myMaxId; private ProjectIndexableFilesFilter(@NotNull TIntArrayList set, int modificationCount) { myModificationCount = modificationCount; final int[] minMax = new int[2]; if (!set.isEmpty()) { minMax[0] = minMax[1] = set.get(0); } set.forEach(new TIntProcedure() { @Override public boolean execute(int value) { if (value < 0) value = -value; minMax[0] = Math.min(minMax[0], value); minMax[1] = Math.max(minMax[1], value); return true; } }); myMaxId = minMax[1]; myMinId = minMax[0]; myBitMask = new long[((myMaxId - myMinId) >> SHIFT) + 1]; set.forEach(new TIntProcedure() { @Override public boolean execute(int value) { if (value < 0) value = -value; value -= myMinId; myBitMask[value >> SHIFT] |= (1L << (value & MASK)); return true; } }); } @Override public boolean containsFileId(int id) { if (id < myMinId) return false; if (id > myMaxId) return false; id -= myMinId; return (myBitMask[id >> SHIFT] & (1L << (id & MASK))) != 0; } } void filesUpdateStarted(Project project) { myContentlessIndicesUpdateQueue.signalUpdateStart(); myContentlessIndicesUpdateQueue.ensureUpToDate(); myProjectsBeingUpdated.add(project); } void filesUpdateFinished(@NotNull Project project) { myProjectsBeingUpdated.remove(project); ++myFilesModCount; } private final Lock myCalcIndexableFilesLock = new SequenceLock(); @Nullable public ProjectIndexableFilesFilter projectIndexableFiles(@Nullable Project project) { if (project == null || myUpdatingFiles.get() > 0) return null; if (myProjectsBeingUpdated.contains(project)) return null; SoftReference<ProjectIndexableFilesFilter> reference = project.getUserData(ourProjectFilesSetKey); ProjectIndexableFilesFilter data = com.intellij.reference.SoftReference.dereference(reference); if (data != null && data.myModificationCount == myFilesModCount) return data; if (myCalcIndexableFilesLock.tryLock()) { // make best effort for calculating filter try { reference = project.getUserData(ourProjectFilesSetKey); data = com.intellij.reference.SoftReference.dereference(reference); if (data != null && data.myModificationCount == myFilesModCount) { return data; } long start = System.currentTimeMillis(); final TIntArrayList filesSet = new TIntArrayList(); iterateIndexableFiles(new ContentIterator() { @Override public boolean processFile(@NotNull VirtualFile fileOrDir) { filesSet.add(((VirtualFileWithId)fileOrDir).getId()); return true; } }, project, SilentProgressIndicator.create()); ProjectIndexableFilesFilter filter = new ProjectIndexableFilesFilter(filesSet, myFilesModCount); project.putUserData(ourProjectFilesSetKey, new SoftReference<ProjectIndexableFilesFilter>(filter)); long finish = System.currentTimeMillis(); LOG.debug(filesSet.size() + " files iterated in " + (finish - start) + " ms"); return filter; } finally { myCalcIndexableFilesLock.unlock(); } } return null; // ok, no filtering } @Nullable private <K, V> TIntHashSet collectFileIdsContainingAllKeys(@NotNull final ID<K, V> indexId, @NotNull final Collection<K> dataKeys, @NotNull final GlobalSearchScope filter, @Nullable final Condition<V> valueChecker, @Nullable final ProjectIndexableFilesFilter projectFilesFilter) { final ThrowableConvertor<UpdatableIndex<K, V, FileContent>, TIntHashSet, StorageException> convertor = new ThrowableConvertor<UpdatableIndex<K, V, FileContent>, TIntHashSet, StorageException>() { @Nullable @Override public TIntHashSet convert(@NotNull UpdatableIndex<K, V, FileContent> index) throws StorageException { TIntHashSet mainIntersection = null; for (K dataKey : dataKeys) { ProgressManager.checkCanceled(); final TIntHashSet copy = new TIntHashSet(); final ValueContainer<V> container = index.getData(dataKey); for (final Iterator<V> valueIt = container.getValueIterator(); valueIt.hasNext(); ) { final V value = valueIt.next(); if (valueChecker != null && !valueChecker.value(value)) { continue; } ValueContainer.IntIterator iterator = container.getInputIdsIterator(value); if (mainIntersection == null || iterator.size() < mainIntersection.size()) { while (iterator.hasNext()) { final int id = iterator.next(); if (mainIntersection == null && (projectFilesFilter == null || projectFilesFilter.containsFileId(id)) || mainIntersection != null && mainIntersection.contains(id) ) { copy.add(id); } } } else { mainIntersection.forEach(new TIntProcedure() { final ValueContainer.IntPredicate predicate = container.getValueAssociationPredicate(value); @Override public boolean execute(int id) { if (predicate.contains(id)) copy.add(id); return true; } }); } } mainIntersection = copy; if (mainIntersection.isEmpty()) { return new TIntHashSet(); } } return mainIntersection; } }; return processExceptions(indexId, null, filter, convertor); } private static boolean processVirtualFiles(@NotNull TIntHashSet ids, @NotNull final GlobalSearchScope filter, @NotNull final Processor<VirtualFile> processor) { final PersistentFS fs = (PersistentFS)ManagingFS.getInstance(); return ids.forEach(new TIntProcedure() { @Override public boolean execute(int id) { ProgressManager.checkCanceled(); VirtualFile file = IndexInfrastructure.findFileByIdIfCached(fs, id); if (file != null && filter.accept(file)) { return processor.process(file); } return true; } }); } @Nullable public static Throwable getCauseToRebuildIndex(@NotNull RuntimeException e) { Throwable cause = e.getCause(); if (cause instanceof StorageException || cause instanceof IOException || cause instanceof IllegalArgumentException) return cause; return null; } @Override public <K, V> boolean getFilesWithKey(@NotNull final ID<K, V> indexId, @NotNull final Set<K> dataKeys, @NotNull Processor<VirtualFile> processor, @NotNull GlobalSearchScope filter) { return processFilesContainingAllKeys(indexId, dataKeys, filter, null, processor); } @Override public <K> void scheduleRebuild(@NotNull final ID<K, ?> indexId, @NotNull final Throwable e) { requestRebuild(indexId, new Throwable(e)); try { checkRebuild(indexId, false); } catch (ProcessCanceledException ignored) { } } private void checkRebuild(@NotNull final ID<?, ?> indexId, final boolean cleanupOnly) { final AtomicInteger status = ourRebuildStatus.get(indexId); if (status.get() == OK) { return; } if (status.compareAndSet(REQUIRES_REBUILD, REBUILD_IN_PROGRESS)) { cleanupProcessedFlag(); advanceIndexVersion(indexId); final Runnable rebuildRunnable = new Runnable() { @Override public void run() { try { doClearIndex(indexId); if (!cleanupOnly) { scheduleIndexRebuild(); } } catch (StorageException e) { requestRebuild(indexId); LOG.info(e); } finally { status.compareAndSet(REBUILD_IN_PROGRESS, OK); } } }; if (cleanupOnly || myIsUnitTestMode) { rebuildRunnable.run(); } else { //noinspection SSBasedInspection ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { new Task.Modal(null, "Updating index", false) { @Override public void run(@NotNull final ProgressIndicator indicator) { indicator.setIndeterminate(true); rebuildRunnable.run(); } }.queue(); } }, ModalityState.NON_MODAL); } } if (status.get() == REBUILD_IN_PROGRESS) { throw new ProcessCanceledException(); } } private static void scheduleIndexRebuild() { for (Project project : ProjectManager.getInstance().getOpenProjects()) { DumbService.getInstance(project).queueTask(new UnindexedFilesUpdater(project, false)); } } private void clearIndex(@NotNull final ID<?, ?> indexId) throws StorageException { advanceIndexVersion(indexId); doClearIndex(indexId); } private void doClearIndex(ID<?, ?> indexId) throws StorageException { final UpdatableIndex<?, ?, FileContent> index = getIndex(indexId); assert index != null : "Index with key " + indexId + " not found or not registered properly"; index.clear(); } private void advanceIndexVersion(ID<?, ?> indexId) { try { IndexingStamp.rewriteVersion(IndexInfrastructure.getVersionFile(indexId), myIndexIdToVersionMap.get(indexId)); } catch (IOException e) { LOG.error(e); } } @NotNull private Set<Document> getUnsavedDocuments() { Document[] documents = myFileDocumentManager.getUnsavedDocuments(); if (documents.length == 0) return Collections.emptySet(); if (documents.length == 1) return Collections.singleton(documents[0]); return new THashSet<Document>(Arrays.asList(documents)); } @NotNull private Set<Document> getTransactedDocuments() { return myTransactionMap.keySet(); } private void indexUnsavedDocuments(@NotNull ID<?, ?> indexId, @Nullable Project project, GlobalSearchScope filter, VirtualFile restrictedFile) throws StorageException { if (myUpToDateIndicesForUnsavedOrTransactedDocuments.contains(indexId)) { return; // no need to index unsaved docs } Set<Document> documents = getUnsavedDocuments(); boolean psiBasedIndex = myPsiDependentIndices.contains(indexId); if(psiBasedIndex) { documents.addAll(getTransactedDocuments()); } if (!documents.isEmpty()) { // now index unsaved data final StorageGuard.StorageModeExitHandler guard = setDataBufferingEnabled(true); try { final Semaphore semaphore = myUnsavedDataIndexingSemaphores.get(indexId); assert semaphore != null : "Semaphore for unsaved data indexing was not initialized for index " + indexId; semaphore.down(); boolean allDocsProcessed = true; try { for (Document document : documents) { if (psiBasedIndex && project != null && PsiDocumentManager.getInstance(project).isUncommited(document)) { continue; } allDocsProcessed &= indexUnsavedDocument(document, indexId, project, filter, restrictedFile); ProgressManager.checkCanceled(); } } finally { semaphore.up(); while (!semaphore.waitFor(500)) { // may need to wait until another thread is done with indexing ProgressManager.checkCanceled(); if (Thread.holdsLock(PsiLock.LOCK)) { break; // hack. Most probably that other indexing threads is waiting for PsiLock, which we're are holding. } } if (allDocsProcessed && !hasActiveTransactions()) { ProgressManager.checkCanceled(); // assume all tasks were finished or cancelled in the same time // safe to set the flag here, because it will be cleared under the WriteAction myUpToDateIndicesForUnsavedOrTransactedDocuments.add(indexId); } } } finally { guard.leave(); } } } private boolean hasActiveTransactions() { return !myTransactionMap.isEmpty(); } private interface DocumentContent { CharSequence getText(); long getModificationStamp(); } private static class AuthenticContent implements DocumentContent { private final Document myDocument; private AuthenticContent(final Document document) { myDocument = document; } @Override public CharSequence getText() { return myDocument.getImmutableCharSequence(); } @Override public long getModificationStamp() { return myDocument.getModificationStamp(); } } private static class PsiContent implements DocumentContent { private final Document myDocument; private final PsiFile myFile; private PsiContent(final Document document, final PsiFile file) { myDocument = document; myFile = file; } @Override public CharSequence getText() { if (myFile.getViewProvider().getModificationStamp() != myDocument.getModificationStamp()) { final ASTNode node = myFile.getNode(); assert node != null; return node.getChars(); } return myDocument.getImmutableCharSequence(); } @Override public long getModificationStamp() { return myFile.getViewProvider().getModificationStamp(); } } private static final Key<WeakReference<FileContentImpl>> ourFileContentKey = Key.create("unsaved.document.index.content"); // returns false if doc was not indexed because the file does not fit in scope private boolean indexUnsavedDocument(@NotNull final Document document, @NotNull final ID<?, ?> requestedIndexId, final Project project, @Nullable GlobalSearchScope filter, @Nullable VirtualFile restrictedFile) { final VirtualFile vFile = myFileDocumentManager.getFile(document); if (!(vFile instanceof VirtualFileWithId) || !vFile.isValid()) { return true; } if (restrictedFile != null) { if (!Comparing.equal(vFile, restrictedFile)) { return false; } } else if (filter != null && !filter.accept(vFile)) { return false; } final PsiFile dominantContentFile = findDominantPsiForDocument(document, project); final DocumentContent content; if (dominantContentFile != null && dominantContentFile.getViewProvider().getModificationStamp() != document.getModificationStamp()) { content = new PsiContent(document, dominantContentFile); } else { content = new AuthenticContent(document); } final long currentDocStamp = content.getModificationStamp(); final long previousDocStamp = myLastIndexedDocStamps.getAndSet(document, requestedIndexId, currentDocStamp); if (currentDocStamp != previousDocStamp) { final CharSequence contentText = content.getText(); FileTypeManagerImpl.cacheFileType(vFile, vFile.getFileType()); try { if (!isTooLarge(vFile, contentText.length()) && getAffectedIndexCandidates(vFile).contains(requestedIndexId) && getInputFilter(requestedIndexId).acceptInput(vFile)) { // Reasonably attempt to use same file content when calculating indices as we can evaluate them several at once and store in file content WeakReference<FileContentImpl> previousContentRef = document.getUserData(ourFileContentKey); FileContentImpl previousContent = com.intellij.reference.SoftReference.dereference(previousContentRef); final FileContentImpl newFc; if (previousContent != null && previousContent.getStamp() == currentDocStamp) { newFc = previousContent; } else { newFc = new FileContentImpl(vFile, contentText, vFile.getCharset(), currentDocStamp); document.putUserData(ourFileContentKey, new WeakReference<FileContentImpl>(newFc)); } initFileContent(newFc, project, dominantContentFile); if (content instanceof AuthenticContent) { newFc.putUserData(PlatformIdTableBuilding.EDITOR_HIGHLIGHTER, EditorHighlighterCache.getEditorHighlighterForCachesBuilding(document)); } final int inputId = Math.abs(getFileId(vFile)); try { getIndex(requestedIndexId).update(inputId, newFc).compute(); } catch (ProcessCanceledException pce) { myLastIndexedDocStamps.getAndSet(document, requestedIndexId, previousDocStamp); throw pce; } finally { cleanFileContent(newFc, dominantContentFile); } } } finally { FileTypeManagerImpl.cacheFileType(vFile, null); } } return true; } private final TaskQueue myContentlessIndicesUpdateQueue = new TaskQueue(10000); @Nullable private PsiFile findDominantPsiForDocument(@NotNull Document document, @Nullable Project project) { PsiFile psiFile = myTransactionMap.get(document); if (psiFile != null) return psiFile; return project == null ? null : findLatestKnownPsiForUncomittedDocument(document, project); } private final StorageGuard myStorageLock = new StorageGuard(); private volatile boolean myPreviousDataBufferingState; private final Object myBufferingStateUpdateLock = new Object(); @NotNull private StorageGuard.StorageModeExitHandler setDataBufferingEnabled(final boolean enabled) { StorageGuard.StorageModeExitHandler storageModeExitHandler = myStorageLock.enter(enabled); if (myPreviousDataBufferingState != enabled) { synchronized (myBufferingStateUpdateLock) { if (myPreviousDataBufferingState != enabled) { for (ID<?, ?> indexId : myIndices.keySet()) { final MapReduceIndex index = (MapReduceIndex)getIndex(indexId); assert index != null; ((MemoryIndexStorage)index.getStorage()).setBufferingEnabled(enabled); } myPreviousDataBufferingState = enabled; } } } return storageModeExitHandler; } private void cleanupMemoryStorage() { myLastIndexedDocStamps.clear(); for (ID<?, ?> indexId : myIndices.keySet()) { final MapReduceIndex index = (MapReduceIndex)getIndex(indexId); assert index != null; final MemoryIndexStorage memStorage = (MemoryIndexStorage)index.getStorage(); index.getWriteLock().lock(); try { memStorage.clearMemoryMap(); } finally { index.getWriteLock().unlock(); } memStorage.fireMemoryStorageCleared(); } } private void dropUnregisteredIndices() { final Set<String> indicesToDrop = readRegisteredIndexNames(); for (ID<?, ?> key : myIndices.keySet()) { indicesToDrop.remove(key.toString()); } for (String s : indicesToDrop) { safeDelete(IndexInfrastructure.getIndexRootDir(ID.create(s))); } } @Override public void requestRebuild(ID<?, ?> indexId, Throwable throwable) { cleanupProcessedFlag(); boolean requiresRebuildWasSet = ourRebuildStatus.get(indexId).compareAndSet(OK, REQUIRES_REBUILD); if (requiresRebuildWasSet) LOG.info("Rebuild requested for index " + indexId, throwable); } private <K, V> UpdatableIndex<K, V, FileContent> getIndex(ID<K, V> indexId) { final Pair<UpdatableIndex<?, ?, FileContent>, InputFilter> pair = myIndices.get(indexId); assert pair != null : "Index data is absent for index " + indexId; //noinspection unchecked return (UpdatableIndex<K, V, FileContent>)pair.getFirst(); } private InputFilter getInputFilter(@NotNull ID<?, ?> indexId) { final Pair<UpdatableIndex<?, ?, FileContent>, InputFilter> pair = myIndices.get(indexId); assert pair != null : "Index data is absent for index " + indexId; return pair.getSecond(); } public int getNumberOfPendingInvalidations() { return myChangedFilesCollector.getNumberOfPendingInvalidations(); } public int getChangedFileCount() { return myChangedFilesCollector.getAllFilesToUpdate().size(); } @NotNull public Collection<VirtualFile> getFilesToUpdate(final Project project) { return ContainerUtil.findAll(myChangedFilesCollector.getAllFilesToUpdate(), new Condition<VirtualFile>() { @Override public boolean value(VirtualFile virtualFile) { for (IndexableFileSet set : myIndexableSets) { final Project proj = myIndexableSetToProjectMap.get(set); if (proj != null && !proj.equals(project)) { continue; // skip this set as associated with a different project } if (set.isInSet(virtualFile)) { return true; } } return false; } }); } public boolean isFileUpToDate(VirtualFile file) { return !myChangedFilesCollector.myFilesToUpdate.contains(file); } void processRefreshedFile(@NotNull Project project, @NotNull final com.intellij.ide.caches.FileContent fileContent) { myChangedFilesCollector.ensureAllInvalidateTasksCompleted(); myChangedFilesCollector.processFileImpl(project, fileContent); // ProcessCanceledException will cause re-adding the file to processing list } public void indexFileContent(@Nullable Project project, @NotNull com.intellij.ide.caches.FileContent content) { VirtualFile file = content.getVirtualFile(); // if file was scheduled for update due to vfs events then it is present in myFilesToUpdate // in this case we consider that current indexing (out of roots backed CacheUpdater) will cover its content // todo this assumption isn't correct for vfs events happened between content loading and indexing itself // proper fix will when events handling will be out of direct execution by EDT myChangedFilesCollector.myFilesToUpdate.remove(file); doIndexFileContent(project, content); } private void doIndexFileContent(@Nullable Project project, @NotNull com.intellij.ide.caches.FileContent content) { myChangedFilesCollector.ensureAllInvalidateTasksCompleted(); final VirtualFile file = content.getVirtualFile(); FileType fileType = file.getFileType(); FileTypeManagerImpl.cacheFileType(file, fileType); try { PsiFile psiFile = null; FileContentImpl fc = null; final List<ID<?, ?>> affectedIndexCandidates = getAffectedIndexCandidates(file); //noinspection ForLoopReplaceableByForEach for (int i = 0, size = affectedIndexCandidates.size(); i < size; ++i) { final ID<?, ?> indexId = affectedIndexCandidates.get(i); if (shouldIndexFile(file, indexId)) { if (fc == null) { byte[] currentBytes; byte[] hash; try { currentBytes = content.getBytes(); hash = fileType.isBinary() || !IdIndex.ourSnapshotMappingsEnabled ? null:ContentHashesSupport.calcContentHashWithFileType(currentBytes, fileType); } catch (IOException e) { currentBytes = ArrayUtil.EMPTY_BYTE_ARRAY; hash = null; } fc = new FileContentImpl(file, currentBytes, hash); if (project == null) { project = ProjectUtil.guessProjectForFile(file); } psiFile = content.getUserData(IndexingDataKeys.PSI_FILE); initFileContent(fc, project, psiFile); } try { ProgressManager.checkCanceled(); updateSingleIndex(indexId, file, fc); } catch (ProcessCanceledException e) { cleanFileContent(fc, psiFile); myChangedFilesCollector.scheduleForUpdate(file); throw e; } catch (StorageException e) { requestRebuild(indexId); LOG.info(e); } } } if (psiFile != null) { psiFile.putUserData(PsiFileImpl.BUILDING_STUB, null); } } finally { FileTypeManagerImpl.cacheFileType(file, null); } } public boolean isIndexingCandidate(@NotNull VirtualFile file, @NotNull ID<?, ?> indexId) { return !isTooLarge(file) && getAffectedIndexCandidates(file).contains(indexId); } @NotNull private List<ID<?, ?>> getAffectedIndexCandidates(@NotNull VirtualFile file) { if (file.isDirectory()) { return isProjectOrWorkspaceFile(file, null) ? Collections.<ID<?,?>>emptyList() : myIndicesForDirectories; } FileType fileType = file.getFileType(); if(isProjectOrWorkspaceFile(file, fileType)) return Collections.emptyList(); List<ID<?, ?>> ids = myFileType2IndicesWithFileTypeInfoMap.get(fileType); if (ids == null) ids = myIndicesWithoutFileTypeInfo; return ids; } private static void cleanFileContent(@NotNull FileContentImpl fc, PsiFile psiFile) { if (psiFile != null) psiFile.putUserData(PsiFileImpl.BUILDING_STUB, false); fc.putUserData(IndexingDataKeys.PSI_FILE, null); } private static void initFileContent(@NotNull FileContentImpl fc, Project project, PsiFile psiFile) { if (psiFile != null) { psiFile.putUserData(PsiFileImpl.BUILDING_STUB, true); fc.putUserData(IndexingDataKeys.PSI_FILE, psiFile); } fc.putUserData(IndexingDataKeys.PROJECT, project); } private void updateSingleIndex(@NotNull ID<?, ?> indexId, @NotNull final VirtualFile file, @Nullable FileContent currentFC) throws StorageException { if (ourRebuildStatus.get(indexId).get() == REQUIRES_REBUILD) { return; // the index is scheduled for rebuild, no need to update } myLocalModCount++; final int inputId = Math.abs(getFileId(file)); final UpdatableIndex<?, ?, FileContent> index = getIndex(indexId); assert index != null; if (currentFC != null && currentFC.getUserData(ourPhysicalContentKey) == null) { currentFC.putUserData(ourPhysicalContentKey, Boolean.TRUE); } // important: no hard referencing currentFC to avoid OOME, the methods introduced for this purpose! final Computable<Boolean> update = index.update(inputId, currentFC); scheduleUpdate(indexId, createUpdateComputableWithBufferingDisabled(update), createIndexedStampUpdateRunnable(indexId, file, currentFC != null) ); } static final Key<Boolean> ourPhysicalContentKey = Key.create("physical.content.flag"); @NotNull private Runnable createIndexedStampUpdateRunnable(@NotNull final ID<?, ?> indexId, @NotNull final VirtualFile file, final boolean hasContent) { return new Runnable() { @Override public void run() { if (file.isValid()) { if (hasContent) { IndexingStamp.setFileIndexedStateCurrent(file, indexId); } else { IndexingStamp.setFileIndexedStateUnindexed(file, indexId); } if (myNotRequiringContentIndices.contains(indexId)) IndexingStamp.flushCache(file); } } }; } @NotNull private Computable<Boolean> createUpdateComputableWithBufferingDisabled(@NotNull final Computable<Boolean> update) { return new Computable<Boolean>() { @Override public Boolean compute() { Boolean result; final StorageGuard.StorageModeExitHandler lock = setDataBufferingEnabled(false); try { result = update.compute(); } finally { lock.leave(); } return result; } }; } private void scheduleUpdate(@NotNull ID<?, ?> indexId, @NotNull Computable<Boolean> update, @NotNull Runnable successRunnable) { if (myNotRequiringContentIndices.contains(indexId)) { myContentlessIndicesUpdateQueue.submit(update, successRunnable); } else { Boolean result = update.compute(); if (result == Boolean.TRUE) ApplicationManager.getApplication().runReadAction(successRunnable); } } private boolean needsFileContentLoading(@NotNull ID<?, ?> indexId) { return !myNotRequiringContentIndices.contains(indexId); } private abstract static class InvalidationTask implements Runnable { private final VirtualFile mySubj; protected InvalidationTask(@NotNull VirtualFile subj) { mySubj = subj; } @NotNull public VirtualFile getSubj() { return mySubj; } } private static class SilentProgressIndicator extends DelegatingProgressIndicator { // suppress verbose messages private SilentProgressIndicator(ProgressIndicator indicator) { super(indicator); } @Nullable private static SilentProgressIndicator create() { final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); return indicator != null ? new SilentProgressIndicator(indicator) : null; } @Override public void setText(String text) { } @Override public String getText() { return ""; } @Override public void setText2(String text) { } @Override public String getText2() { return ""; } } private final class ChangedFilesCollector extends VirtualFileAdapter implements BulkFileListener { private final Set<VirtualFile> myFilesToUpdate = new ConcurrentHashSet<VirtualFile>(); private final Queue<InvalidationTask> myFutureInvalidations = new ConcurrentLinkedQueue<InvalidationTask>(); private final ManagingFS myManagingFS = ManagingFS.getInstance(); @Override public void fileMoved(@NotNull VirtualFileMoveEvent event) { markDirty(event, false); } @Override public void fileCreated(@NotNull final VirtualFileEvent event) { markDirty(event, false); } @Override public void fileCopied(@NotNull final VirtualFileCopyEvent event) { markDirty(event, false); } @Override public void beforeFileDeletion(@NotNull final VirtualFileEvent event) { invalidateIndices(event.getFile(), false); } @Override public void beforeContentsChange(@NotNull final VirtualFileEvent event) { invalidateIndices(event.getFile(), true); } @Override public void contentsChanged(@NotNull final VirtualFileEvent event) { markDirty(event, true); } @Override public void beforePropertyChange(@NotNull final VirtualFilePropertyEvent event) { if (event.getPropertyName().equals(VirtualFile.PROP_NAME)) { // indexes may depend on file name final VirtualFile file = event.getFile(); // name change may lead to filetype change so the file might become not indexable // in general case have to 'unindex' the file and index it again if needed after the name has been changed invalidateIndices(file, false); } } @Override public void propertyChanged(@NotNull final VirtualFilePropertyEvent event) { if (event.getPropertyName().equals(VirtualFile.PROP_NAME)) { // indexes may depend on file name markDirty(event, false); } } private void markDirty(@NotNull final VirtualFileEvent event, final boolean contentChange) { final VirtualFile eventFile = event.getFile(); cleanProcessedFlag(eventFile); if (!contentChange) { myUpdatingFiles.incrementAndGet(); } iterateIndexableFiles(eventFile, new Processor<VirtualFile>() { @Override public boolean process(@NotNull final VirtualFile file) { // handle 'content-less' indices separately boolean fileIsDirectory = file.isDirectory(); if (!contentChange) { FileContent fileContent = null; for (ID<?, ?> indexId : fileIsDirectory ? myIndicesForDirectories : myNotRequiringContentIndices) { if (getInputFilter(indexId).acceptInput(file)) { try { if (fileContent == null) { fileContent = new FileContentImpl(file); } updateSingleIndex(indexId, file, fileContent); } catch (StorageException e) { LOG.info(e); requestRebuild(indexId); } } } } // For 'normal indices' schedule the file for update and reset stamps for all affected indices (there // can be client that used indices between before and after events, in such case indices are up to date due to force update // with old content) if (!fileIsDirectory && !isTooLarge(file)) { FileTypeManagerImpl.cacheFileType(file, file.getFileType()); try { final List<ID<?, ?>> candidates = getAffectedIndexCandidates(file); //noinspection ForLoopReplaceableByForEach boolean scheduleForUpdate = false; boolean resetStamp = false; //noinspection ForLoopReplaceableByForEach for (int i = 0, size = candidates.size(); i < size; ++i) { final ID<?, ?> indexId = candidates.get(i); if (needsFileContentLoading(indexId) && getInputFilter(indexId).acceptInput(file)) { if (IndexingStamp.isFileIndexedStateCurrent(file, indexId)) { IndexingStamp.setFileIndexedStateOutdated(file, indexId); resetStamp = true; } scheduleForUpdate = true; } } if (scheduleForUpdate) { if (resetStamp) IndexingStamp.flushCache(file); scheduleForUpdate(file); } } finally { FileTypeManagerImpl.cacheFileType(file, null); } } return true; } }); IndexingStamp.flushCaches(); if (!contentChange) { if (myUpdatingFiles.decrementAndGet() == 0) { ++myFilesModCount; } } } private void scheduleForUpdate(VirtualFile file) { myFilesToUpdate.add(file); } private void invalidateIndices(@NotNull final VirtualFile file, final boolean markForReindex) { VfsUtilCore.visitChildrenRecursively(file, new VirtualFileVisitor() { @Override public boolean visitFile(@NotNull VirtualFile file) { if (isUnderConfigOrSystem(file)) { return false; } if (file.isDirectory()) { invalidateIndicesForFile(file, markForReindex); if (!isMock(file) && !myManagingFS.wereChildrenAccessed(file)) { return false; } } else { invalidateIndicesForFile(file, markForReindex); } return true; } @Override public Iterable<VirtualFile> getChildrenIterable(@NotNull VirtualFile file) { return file instanceof NewVirtualFile ? ((NewVirtualFile)file).iterInDbChildren() : null; } }); } private void invalidateIndicesForFile(@NotNull final VirtualFile file, boolean markForReindex) { cleanProcessedFlag(file); IndexingStamp.flushCache(file); List<ID<?, ?>> nontrivialFileIndexedStates = IndexingStamp.getNontrivialFileIndexedStates(file); if (!markForReindex) { // markForReindex really means content changed for (ID<?, ?> indexId : nontrivialFileIndexedStates) { if (myNotRequiringContentIndices.contains(indexId)) { try { updateSingleIndex(indexId, file, null); } catch (StorageException e) { LOG.info(e); requestRebuild(indexId); } } } myFilesToUpdate.remove(file); // no need to update it anymore } Collection<ID<?, ?>> fileIndexedStatesToUpdate = ContainerUtil.intersection(nontrivialFileIndexedStates, myRequiringContentIndices); if (markForReindex) { // only mark the file as outdated, reindex will be done lazily if (!fileIndexedStatesToUpdate.isEmpty()) { final List<ID<?, ?>> finalNontrivialFileIndexedStates = nontrivialFileIndexedStates; ApplicationManager.getApplication().runReadAction(new Runnable() { @Override public void run() { //noinspection ForLoopReplaceableByForEach for (int i = 0, size = finalNontrivialFileIndexedStates.size(); i < size; ++i) { final ID<?, ?> indexId = finalNontrivialFileIndexedStates.get(i); if (needsFileContentLoading(indexId) && IndexingStamp.isFileIndexedStateCurrent(file, indexId)) { IndexingStamp.setFileIndexedStateOutdated(file, indexId); } } } }); // the file is for sure not a dir and it was previously indexed by at least one index if (!isTooLarge(file)) scheduleForUpdate(file); } } else if (!fileIndexedStatesToUpdate.isEmpty()) { // file was removed, its data should be (lazily) wiped for every index final Collection<ID<?, ?>> finalFileIndexedStatesToUpdate = fileIndexedStatesToUpdate; myFutureInvalidations.offer(new InvalidationTask(file) { @Override public void run() { removeFileDataFromIndices(finalFileIndexedStatesToUpdate, file); } }); } IndexingStamp.flushCache(file); } private void removeFileDataFromIndices(@NotNull Collection<ID<?, ?>> affectedIndices, @NotNull VirtualFile file) { Throwable unexpectedError = null; for (ID<?, ?> indexId : affectedIndices) { try { updateSingleIndex(indexId, file, null); } catch (StorageException e) { LOG.info(e); requestRebuild(indexId); } catch (ProcessCanceledException pce) { LOG.error(pce); } catch (Throwable e) { LOG.info(e); if (unexpectedError == null) { unexpectedError = e; } } } IndexingStamp.flushCache(file); if (unexpectedError != null) { LOG.error(unexpectedError); } } public int getNumberOfPendingInvalidations() { return myFutureInvalidations.size(); } public void ensureAllInvalidateTasksCompleted() { final int size = getNumberOfPendingInvalidations(); if (size == 0) { return; } // we must avoid PCE interruptions when removing data from indices ProgressManager.getInstance().executeNonCancelableSection( new Runnable() { @Override public void run() { final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); indicator.setText(""); int count = 0; while (true) { InvalidationTask task = myFutureInvalidations.poll(); if (task == null) { break; } indicator.setFraction((double)count++ / size); task.run(); } } } ); } private void iterateIndexableFiles(@NotNull final VirtualFile file, @NotNull final Processor<VirtualFile> processor) { if (file.isDirectory()) { final ContentIterator iterator = new ContentIterator() { @Override public boolean processFile(@NotNull final VirtualFile fileOrDir) { processor.process(fileOrDir); return true; } }; for (IndexableFileSet set : myIndexableSets) { if (set.isInSet(file)) { set.iterateIndexableFilesIn(file, iterator); } } } else { for (IndexableFileSet set : myIndexableSets) { if (set.isInSet(file)) { processor.process(file); break; } } } } public Collection<VirtualFile> getAllFilesToUpdate() { if (myFilesToUpdate.isEmpty()) { return Collections.emptyList(); } return new ArrayList<VirtualFile>(myFilesToUpdate); } private final AtomicReference<UpdateSemaphore> myUpdateSemaphoreRef = new AtomicReference<UpdateSemaphore>(null); @NotNull private UpdateSemaphore obtainForceUpdateSemaphore() { UpdateSemaphore newValue = null; while (true) { final UpdateSemaphore currentValue = myUpdateSemaphoreRef.get(); if (currentValue != null) { return currentValue; } if (newValue == null) { // lazy init newValue = new UpdateSemaphore(); } if (myUpdateSemaphoreRef.compareAndSet(null, newValue)) { return newValue; } } } private void releaseForceUpdateSemaphore(UpdateSemaphore semaphore) { myUpdateSemaphoreRef.compareAndSet(semaphore, null); } private void forceUpdate(@Nullable Project project, @Nullable GlobalSearchScope filter, @Nullable VirtualFile restrictedTo) { myChangedFilesCollector.ensureAllInvalidateTasksCompleted(); ProjectIndexableFilesFilter indexableFilesFilter = projectIndexableFiles(project); UpdateSemaphore updateSemaphore; do { updateSemaphore = obtainForceUpdateSemaphore(); try { for (VirtualFile file : getAllFilesToUpdate()) { if (indexableFilesFilter != null && file instanceof VirtualFileWithId && !indexableFilesFilter.containsFileId( ((VirtualFileWithId)file).getId())) { continue; } if (filter == null || filter.accept(file) || Comparing.equal(file, restrictedTo)) { try { updateSemaphore.down(); // process only files that can affect result processFileImpl(project, new com.intellij.ide.caches.FileContent(file)); } catch (ProcessCanceledException e) { updateSemaphore.reportUpdateCanceled(); throw e; } finally { updateSemaphore.up(); } } } // If several threads entered the method at the same time and there were files to update, // all the threads should leave the method synchronously after all the files scheduled for update are reindexed, // no matter which thread will do reindexing job. // Thus we ensure that all the threads that entered the method will get the most recent data while (!updateSemaphore.waitFor(500)) { // may need to wait until another thread is done with indexing if (Thread.holdsLock(PsiLock.LOCK)) { break; // hack. Most probably that other indexing threads is waiting for PsiLock, which we're are holding. } } } finally { releaseForceUpdateSemaphore(updateSemaphore); } // if some other thread was unable to complete indexing because of PCE, // we should try again and ensure the file is indexed before proceeding further } while (updateSemaphore.isUpdateCanceled()); } private void processFileImpl(Project project, @NotNull final com.intellij.ide.caches.FileContent fileContent) { final VirtualFile file = fileContent.getVirtualFile(); final boolean reallyRemoved = myFilesToUpdate.remove(file); if (reallyRemoved && file.isValid()) { try { if (isTooLarge(file)) { removeFileDataFromIndices(ContainerUtil.intersection(IndexingStamp.getNontrivialFileIndexedStates(file), myRequiringContentIndices), file); } else { doIndexFileContent(project, fileContent); } } finally { IndexingStamp.flushCache(file); } } } @Override public void before(@NotNull List<? extends VFileEvent> events) { myContentlessIndicesUpdateQueue.signalUpdateStart(); myContentlessIndicesUpdateQueue.ensureUpToDate(); for (VFileEvent event : events) { Object requestor = event.getRequestor(); if (requestor instanceof FileDocumentManager || requestor instanceof PsiManager || requestor == LocalHistory.VFS_EVENT_REQUESTOR) { cleanupMemoryStorage(); break; } } for (VFileEvent event : events) { BulkVirtualFileListenerAdapter.fireBefore(this, event); } } @Override public void after(@NotNull List<? extends VFileEvent> events) { myContentlessIndicesUpdateQueue.ensureUpToDate(); for (VFileEvent event : events) { BulkVirtualFileListenerAdapter.fireAfter(this, event); } myContentlessIndicesUpdateQueue.signalUpdateEnd(); } } private class UnindexedFilesFinder implements CollectingContentIterator { private final List<VirtualFile> myFiles = new ArrayList<VirtualFile>(); @Nullable private final ProgressIndicator myProgressIndicator; private UnindexedFilesFinder(@Nullable ProgressIndicator indicator) { myProgressIndicator = indicator; } @NotNull @Override public List<VirtualFile> getFiles() { return myFiles; } @Override public boolean processFile(@NotNull final VirtualFile file) { if (!file.isValid()) { return true; } if (file instanceof VirtualFileSystemEntry && ((VirtualFileSystemEntry)file).isFileIndexed()) { return true; } if (!(file instanceof VirtualFileWithId)) { return true; } try { FileType type = file.getFileType(); FileTypeManagerImpl.cacheFileType(file, type); boolean oldStuff = true; if (file.isDirectory() || !isTooLarge(file)) { final List<ID<?, ?>> affectedIndexCandidates = getAffectedIndexCandidates(file); //noinspection ForLoopReplaceableByForEach for (int i = 0, size = affectedIndexCandidates.size(); i < size; ++i) { final ID<?, ?> indexId = affectedIndexCandidates.get(i); try { if (needsFileContentLoading(indexId) && shouldIndexFile(file, indexId)) { myFiles.add(file); oldStuff = false; break; } } catch (RuntimeException e) { final Throwable cause = e.getCause(); if (cause instanceof IOException || cause instanceof StorageException) { LOG.info(e); requestRebuild(indexId); } else { throw e; } } } } FileContent fileContent = null; for (ID<?, ?> indexId : myNotRequiringContentIndices) { if (shouldIndexFile(file, indexId)) { oldStuff = false; try { if (fileContent == null) { fileContent = new FileContentImpl(file); } updateSingleIndex(indexId, file, fileContent); } catch (StorageException e) { LOG.info(e); requestRebuild(indexId); } } } IndexingStamp.flushCache(file); if (oldStuff && file instanceof VirtualFileSystemEntry) { ((VirtualFileSystemEntry)file).setFileIndexed(true); } } finally { FileTypeManagerImpl.cacheFileType(file, null); } if (myProgressIndicator != null && file.isDirectory()) { // once for dir is cheap enough myProgressIndicator.checkCanceled(); myProgressIndicator.setText("Scanning files to index"); } return true; } } private boolean shouldIndexFile(@NotNull VirtualFile file, @NotNull ID<?, ?> indexId) { return getInputFilter(indexId).acceptInput(file) && (isMock(file) || !isFileIndexed(file, indexId)); } private static boolean isFileIndexed(VirtualFile file, @NotNull ID<?, ?> indexId) { return IndexingStamp.isFileIndexedStateCurrent(file, indexId); } private boolean isUnderConfigOrSystem(@NotNull VirtualFile file) { final String filePath = file.getPath(); return myConfigPath != null && FileUtil.startsWith(filePath, myConfigPath) || myLogPath != null && FileUtil.startsWith(filePath, myLogPath); } private static boolean isMock(final VirtualFile file) { return !(file instanceof NewVirtualFile); } private boolean isTooLarge(@NotNull VirtualFile file) { if (SingleRootFileViewProvider.isTooLargeForIntelligence(file)) { return !myNoLimitCheckTypes.contains(file.getFileType()); } return false; } private boolean isTooLarge(@NotNull VirtualFile file, long contentSize) { if (SingleRootFileViewProvider.isTooLargeForIntelligence(file, contentSize)) { return !myNoLimitCheckTypes.contains(file.getFileType()); } return false; } @NotNull public CollectingContentIterator createContentIterator(@Nullable ProgressIndicator indicator) { return new UnindexedFilesFinder(indicator); } @Override public void registerIndexableSet(@NotNull IndexableFileSet set, @Nullable Project project) { myIndexableSets.add(set); myIndexableSetToProjectMap.put(set, project); if (project != null) { ((PsiManagerImpl)PsiManager.getInstance(project)).addTreeChangePreprocessor(new PsiTreeChangePreprocessor() { @Override public void treeChanged(@NotNull PsiTreeChangeEventImpl event) { if (event.isGenericChange() && event.getCode() == PsiTreeChangeEventImpl.PsiEventType.CHILDREN_CHANGED) { PsiFile file = event.getFile(); if (file != null) { VirtualFile virtualFile = file.getVirtualFile(); Document document = myFileDocumentManager.getDocument(virtualFile); if (document != null && myFileDocumentManager.isDocumentUnsaved(document)) { for(ID<?,?> psiBackedIndex:myPsiDependentIndices) { myUpToDateIndicesForUnsavedOrTransactedDocuments.remove(psiBackedIndex); } } else { // change in persistent file if (virtualFile instanceof VirtualFileWithId) { boolean wasIndexed = false; for (ID<?, ?> psiBackedIndex : myPsiDependentIndices) { if (isFileIndexed(virtualFile, psiBackedIndex)) { IndexingStamp.setFileIndexedStateOutdated(virtualFile, psiBackedIndex); wasIndexed = true; } } if (wasIndexed) { myChangedFilesCollector.scheduleForUpdate(virtualFile); IndexingStamp.flushCache(virtualFile); } } } } } } }); } } @Override public void removeIndexableSet(@NotNull IndexableFileSet set) { if (!myIndexableSetToProjectMap.containsKey(set)) return; myChangedFilesCollector.ensureAllInvalidateTasksCompleted(); IndexingStamp.flushCaches(); myIndexableSets.remove(set); myIndexableSetToProjectMap.remove(set); } @Override public VirtualFile findFileById(Project project, int id) { return IndexInfrastructure.findFileById((PersistentFS) ManagingFS.getInstance(), id); } @Nullable private static PsiFile findLatestKnownPsiForUncomittedDocument(@NotNull Document doc, @NotNull Project project) { return PsiDocumentManager.getInstance(project).getCachedPsiFile(doc); } private static class IndexableFilesFilter implements InputFilter { private final InputFilter myDelegate; private IndexableFilesFilter(InputFilter delegate) { myDelegate = delegate; } @Override public boolean acceptInput(@NotNull final VirtualFile file) { return file instanceof VirtualFileWithId && myDelegate.acceptInput(file); } } private static void cleanupProcessedFlag() { final VirtualFile[] roots = ManagingFS.getInstance().getRoots(); for (VirtualFile root : roots) { cleanProcessedFlag(root); } } private static void cleanProcessedFlag(@NotNull final VirtualFile file) { if (!(file instanceof VirtualFileSystemEntry)) return; final VirtualFileSystemEntry nvf = (VirtualFileSystemEntry)file; if (file.isDirectory()) { nvf.setFileIndexed(false); for (VirtualFile child : nvf.getCachedChildren()) { cleanProcessedFlag(child); } } else { nvf.setFileIndexed(false); } } @Override public void iterateIndexableFiles(@NotNull final ContentIterator processor, @NotNull Project project, ProgressIndicator indicator) { if (project.isDisposed()) { return; } final ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex(); // iterate project content projectFileIndex.iterateContent(processor); if (project.isDisposed()) { return; } Set<VirtualFile> visitedRoots = new THashSet<VirtualFile>(); for (IndexedRootsProvider provider : Extensions.getExtensions(IndexedRootsProvider.EP_NAME)) { //important not to depend on project here, to support per-project background reindex // each client gives a project to FileBasedIndex if (project.isDisposed()) { return; } for (VirtualFile root : IndexableSetContributor.getRootsToIndex(provider)) { if (visitedRoots.add(root)) { iterateRecursively(root, processor, indicator, visitedRoots); } } for (VirtualFile root : IndexableSetContributor.getProjectRootsToIndex(provider, project)) { if (visitedRoots.add(root)) { iterateRecursively(root, processor, indicator, visitedRoots); } } } if (project.isDisposed()) { return; } // iterate associated libraries for (Module module : ModuleManager.getInstance(project).getModules()) { if (module.isDisposed()) { return; } OrderEntry[] orderEntries = ModuleRootManager.getInstance(module).getOrderEntries(); for (OrderEntry orderEntry : orderEntries) { if (orderEntry instanceof LibraryOrSdkOrderEntry) { if (orderEntry.isValid()) { final LibraryOrSdkOrderEntry entry = (LibraryOrSdkOrderEntry)orderEntry; final VirtualFile[] libSources = entry.getRootFiles(OrderRootType.SOURCES); final VirtualFile[] libClasses = entry.getRootFiles(OrderRootType.CLASSES); for (VirtualFile[] roots : new VirtualFile[][]{libSources, libClasses}) { for (VirtualFile root : roots) { if (visitedRoots.add(root)) { iterateRecursively(root, processor, indicator, null); } } } } } } } } private static void iterateRecursively(@Nullable final VirtualFile root, @NotNull final ContentIterator processor, @Nullable final ProgressIndicator indicator, @Nullable final Set<VirtualFile> visitedRoots ) { if (root == null) { return; } VfsUtilCore.visitChildrenRecursively(root, new VirtualFileVisitor() { @Override public boolean visitFile(@NotNull VirtualFile file) { if (visitedRoots != null && root != file && file.isDirectory() && !visitedRoots.add(file)) { return false; // avoid visiting files more than once, e.g. additional indexed roots intersect sometimes } if (indicator != null) indicator.checkCanceled(); processor.processFile(file); return true; } }); } @SuppressWarnings({"WhileLoopSpinsOnField", "SynchronizeOnThis"}) private static class StorageGuard { private int myHolds = 0; private int myWaiters = 0; public interface StorageModeExitHandler { void leave(); } private final StorageModeExitHandler myTrueStorageModeExitHandler = new StorageModeExitHandler() { @Override public void leave() { StorageGuard.this.leave(true); } }; private final StorageModeExitHandler myFalseStorageModeExitHandler = new StorageModeExitHandler() { @Override public void leave() { StorageGuard.this.leave(false); } }; @NotNull private synchronized StorageModeExitHandler enter(boolean mode) { if (mode) { while (myHolds < 0) { doWait(); } myHolds++; return myTrueStorageModeExitHandler; } else { while (myHolds > 0) { doWait(); } myHolds--; return myFalseStorageModeExitHandler; } } private void doWait() { try { ++myWaiters; wait(); } catch (InterruptedException ignored) { } finally { --myWaiters; } } private synchronized void leave(boolean mode) { myHolds += mode ? -1 : 1; if (myHolds == 0 && myWaiters > 0) { notifyAll(); } } } }
platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.util.indexing; import com.intellij.AppTopics; import com.intellij.history.LocalHistory; import com.intellij.ide.util.DelegatingProgressIndicator; import com.intellij.lang.ASTNode; import com.intellij.notification.NotificationDisplayType; import com.intellij.notification.NotificationGroup; import com.intellij.notification.NotificationType; import com.intellij.openapi.application.ApplicationAdapter; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.impl.EditorHighlighterCache; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.FileDocumentManagerAdapter; import com.intellij.openapi.fileTypes.*; import com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator; import com.intellij.openapi.project.*; import com.intellij.openapi.roots.*; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.impl.BulkVirtualFileListenerAdapter; import com.intellij.openapi.vfs.newvfs.BulkFileListener; import com.intellij.openapi.vfs.newvfs.ManagingFS; import com.intellij.openapi.vfs.newvfs.NewVirtualFile; import com.intellij.openapi.vfs.newvfs.events.VFileEvent; import com.intellij.openapi.vfs.newvfs.impl.VirtualFileSystemEntry; import com.intellij.openapi.vfs.newvfs.persistent.FlushingDaemon; import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS; import com.intellij.psi.*; import com.intellij.psi.impl.PsiDocumentTransactionListener; import com.intellij.psi.impl.PsiManagerImpl; import com.intellij.psi.impl.PsiTreeChangeEventImpl; import com.intellij.psi.impl.PsiTreeChangePreprocessor; import com.intellij.psi.impl.cache.impl.id.IdIndex; import com.intellij.psi.impl.cache.impl.id.PlatformIdTableBuilding; import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.psi.search.EverythingGlobalScope; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.stubs.SerializationManagerEx; import com.intellij.util.*; import com.intellij.util.concurrency.Semaphore; import com.intellij.util.containers.ConcurrentHashSet; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.io.*; import com.intellij.util.io.DataOutputStream; import com.intellij.util.io.storage.HeavyProcessLatch; import com.intellij.util.messages.MessageBus; import com.intellij.util.messages.MessageBusConnection; import gnu.trove.*; import jsr166e.extra.SequenceLock; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.*; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Lock; /** * @author Eugene Zhuravlev * @since Dec 20, 2007 */ public class FileBasedIndexImpl extends FileBasedIndex { private static final Logger LOG = Logger.getInstance("#com.intellij.util.indexing.FileBasedIndexImpl"); @NonNls private static final String CORRUPTION_MARKER_NAME = "corruption.marker"; private final Map<ID<?, ?>, Pair<UpdatableIndex<?, ?, FileContent>, InputFilter>> myIndices = new THashMap<ID<?, ?>, Pair<UpdatableIndex<?, ?, FileContent>, InputFilter>>(); private final List<ID<?, ?>> myIndicesWithoutFileTypeInfo = new ArrayList<ID<?, ?>>(); private final Map<FileType, List<ID<?, ?>>> myFileType2IndicesWithFileTypeInfoMap = new THashMap<FileType, List<ID<?, ?>>>(); private final List<ID<?, ?>> myIndicesForDirectories = new SmartList<ID<?, ?>>(); private final Map<ID<?, ?>, Semaphore> myUnsavedDataIndexingSemaphores = new THashMap<ID<?, ?>, Semaphore>(); private final TObjectIntHashMap<ID<?, ?>> myIndexIdToVersionMap = new TObjectIntHashMap<ID<?, ?>>(); private final Set<ID<?, ?>> myNotRequiringContentIndices = new THashSet<ID<?, ?>>(); private final Set<ID<?, ?>> myRequiringContentIndices = new THashSet<ID<?, ?>>(); private final Set<ID<?, ?>> myPsiDependentIndices = new THashSet<ID<?, ?>>(); private final Set<FileType> myNoLimitCheckTypes = new THashSet<FileType>(); private final PerIndexDocumentVersionMap myLastIndexedDocStamps = new PerIndexDocumentVersionMap(); @NotNull private final ChangedFilesCollector myChangedFilesCollector; private final List<IndexableFileSet> myIndexableSets = ContainerUtil.createLockFreeCopyOnWriteList(); private final Map<IndexableFileSet, Project> myIndexableSetToProjectMap = new THashMap<IndexableFileSet, Project>(); private static final int OK = 1; private static final int REQUIRES_REBUILD = 2; private static final int REBUILD_IN_PROGRESS = 3; private static final Map<ID<?, ?>, AtomicInteger> ourRebuildStatus = new THashMap<ID<?, ?>, AtomicInteger>(); private final MessageBusConnection myConnection; private final FileDocumentManager myFileDocumentManager; private final FileTypeManagerImpl myFileTypeManager; private final SerializationManagerEx mySerializationManagerEx; private final ConcurrentHashSet<ID<?, ?>> myUpToDateIndicesForUnsavedOrTransactedDocuments = new ConcurrentHashSet<ID<?, ?>>(); private volatile SmartFMap<Document, PsiFile> myTransactionMap = SmartFMap.emptyMap(); @Nullable private final String myConfigPath; @Nullable private final String myLogPath; private final boolean myIsUnitTestMode; @Nullable private ScheduledFuture<?> myFlushingFuture; private volatile int myLocalModCount; private volatile int myFilesModCount; private final AtomicInteger myUpdatingFiles = new AtomicInteger(); private final ConcurrentHashSet<Project> myProjectsBeingUpdated = new ConcurrentHashSet<Project>(); @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"}) private volatile boolean myInitialized; // need this variable for memory barrier public FileBasedIndexImpl(@SuppressWarnings("UnusedParameters") VirtualFileManager vfManager, FileDocumentManager fdm, FileTypeManagerImpl fileTypeManager, @NotNull MessageBus bus, SerializationManagerEx sm) { myFileDocumentManager = fdm; myFileTypeManager = fileTypeManager; mySerializationManagerEx = sm; myIsUnitTestMode = ApplicationManager.getApplication().isUnitTestMode(); myConfigPath = calcConfigPath(PathManager.getConfigPath()); myLogPath = calcConfigPath(PathManager.getLogPath()); final MessageBusConnection connection = bus.connect(); connection.subscribe(PsiDocumentTransactionListener.TOPIC, new PsiDocumentTransactionListener() { @Override public void transactionStarted(@NotNull final Document doc, @NotNull final PsiFile file) { myTransactionMap = myTransactionMap.plus(doc, file); myUpToDateIndicesForUnsavedOrTransactedDocuments.clear(); } @Override public void transactionCompleted(@NotNull final Document doc, @NotNull final PsiFile file) { myTransactionMap = myTransactionMap.minus(doc); } }); connection.subscribe(FileTypeManager.TOPIC, new FileTypeListener() { @Nullable private Map<FileType, Set<String>> myTypeToExtensionMap; @Override public void beforeFileTypesChanged(@NotNull final FileTypeEvent event) { cleanupProcessedFlag(); myTypeToExtensionMap = new THashMap<FileType, Set<String>>(); for (FileType type : myFileTypeManager.getRegisteredFileTypes()) { myTypeToExtensionMap.put(type, getExtensions(type)); } } @Override public void fileTypesChanged(@NotNull final FileTypeEvent event) { final Map<FileType, Set<String>> oldExtensions = myTypeToExtensionMap; myTypeToExtensionMap = null; if (oldExtensions != null) { final Map<FileType, Set<String>> newExtensions = new THashMap<FileType, Set<String>>(); for (FileType type : myFileTypeManager.getRegisteredFileTypes()) { newExtensions.put(type, getExtensions(type)); } // we are interested only in extension changes or removals. // addition of an extension is handled separately by RootsChanged event if (!newExtensions.keySet().containsAll(oldExtensions.keySet())) { rebuildAllIndices(); return; } for (Map.Entry<FileType, Set<String>> entry : oldExtensions.entrySet()) { FileType fileType = entry.getKey(); Set<String> strings = entry.getValue(); if (!newExtensions.get(fileType).containsAll(strings)) { rebuildAllIndices(); return; } } } } @NotNull private Set<String> getExtensions(@NotNull FileType type) { final Set<String> set = new THashSet<String>(); for (FileNameMatcher matcher : myFileTypeManager.getAssociations(type)) { set.add(matcher.getPresentableString()); } return set; } private void rebuildAllIndices() { IndexingStamp.flushCaches(); for (ID<?, ?> indexId : myIndices.keySet()) { try { clearIndex(indexId); } catch (StorageException e) { LOG.info(e); } } scheduleIndexRebuild(); } }); connection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, new FileDocumentManagerAdapter() { @Override public void fileContentReloaded(@NotNull VirtualFile file, @NotNull Document document) { cleanupMemoryStorage(); } @Override public void unsavedDocumentsDropped() { cleanupMemoryStorage(); } }); ApplicationManager.getApplication().addApplicationListener(new ApplicationAdapter() { @Override public void writeActionStarted(Object action) { myUpToDateIndicesForUnsavedOrTransactedDocuments.clear(); } }); myChangedFilesCollector = new ChangedFilesCollector(); myConnection = connection; } public static boolean isProjectOrWorkspaceFile(@NotNull VirtualFile file, @Nullable FileType fileType) { if (fileType instanceof InternalFileType) return true; VirtualFile parent = file.isDirectory() ? file: file.getParent(); while(parent instanceof VirtualFileSystemEntry) { if (((VirtualFileSystemEntry)parent).compareNameTo(ProjectCoreUtil.DIRECTORY_BASED_PROJECT_DIR, !SystemInfoRt.isFileSystemCaseSensitive) == 0) return true; parent = parent.getParent(); } return false; } @Override public void requestReindex(@NotNull final VirtualFile file) { myChangedFilesCollector.invalidateIndices(file, true); } private void initExtensions() { try { final FileBasedIndexExtension[] extensions = Extensions.getExtensions(FileBasedIndexExtension.EXTENSION_POINT_NAME); for (FileBasedIndexExtension<?, ?> extension : extensions) { ourRebuildStatus.put(extension.getName(), new AtomicInteger(OK)); } final File corruptionMarker = new File(PathManager.getIndexRoot(), CORRUPTION_MARKER_NAME); final boolean currentVersionCorrupted = corruptionMarker.exists(); boolean versionChanged = false; for (FileBasedIndexExtension<?, ?> extension : extensions) { versionChanged |= registerIndexer(extension, currentVersionCorrupted); } for(List<ID<?, ?>> value: myFileType2IndicesWithFileTypeInfoMap.values()) { value.addAll(myIndicesWithoutFileTypeInfo); } FileUtil.delete(corruptionMarker); String rebuildNotification = null; if (currentVersionCorrupted) { rebuildNotification = "Index files on disk are corrupted. Indices will be rebuilt."; } else if (versionChanged) { rebuildNotification = "Index file format has changed for some indices. These indices will be rebuilt."; } if (rebuildNotification != null && !ApplicationManager.getApplication().isHeadlessEnvironment() && Registry.is("ide.showIndexRebuildMessage")) { new NotificationGroup("Indexing", NotificationDisplayType.BALLOON, false) .createNotification("Index Rebuild", rebuildNotification, NotificationType.INFORMATION, null).notify(null); } dropUnregisteredIndices(); // check if rebuild was requested for any index during registration for (ID<?, ?> indexId : myIndices.keySet()) { if (ourRebuildStatus.get(indexId).compareAndSet(REQUIRES_REBUILD, OK)) { try { clearIndex(indexId); } catch (StorageException e) { requestRebuild(indexId); LOG.error(e); } } } myConnection.subscribe(VirtualFileManager.VFS_CHANGES, myChangedFilesCollector); registerIndexableSet(new AdditionalIndexableFileSet(), null); } catch (IOException e) { throw new RuntimeException(e); } finally { ShutDownTracker.getInstance().registerShutdownTask(new Runnable() { @Override public void run() { performShutdown(); } }); saveRegisteredIndices(myIndices.keySet()); myFlushingFuture = FlushingDaemon.everyFiveSeconds(new Runnable() { private int lastModCount = 0; @Override public void run() { if (lastModCount == myLocalModCount) { flushAllIndices(lastModCount); } lastModCount = myLocalModCount; } }); myInitialized = true; // this will ensure that all changes to component's state will be visible to other threads } } @Override public void initComponent() { initExtensions(); } @Nullable private static String calcConfigPath(@NotNull String path) { try { final String _path = FileUtil.toSystemIndependentName(new File(path).getCanonicalPath()); return _path.endsWith("/") ? _path : _path + "/"; } catch (IOException e) { LOG.info(e); return null; } } /** * @return true if registered index requires full rebuild for some reason, e.g. is just created or corrupted */ private <K, V> boolean registerIndexer(@NotNull final FileBasedIndexExtension<K, V> extension, final boolean isCurrentVersionCorrupted) throws IOException { final ID<K, V> name = extension.getName(); final int version = extension.getVersion(); final File versionFile = IndexInfrastructure.getVersionFile(name); final boolean versionFileExisted = versionFile.exists(); boolean versionChanged = false; if (isCurrentVersionCorrupted || IndexingStamp.versionDiffers(versionFile, version)) { if (!isCurrentVersionCorrupted && versionFileExisted) { versionChanged = true; LOG.info("Version has changed for index " + name + ". The index will be rebuilt."); } if (extension.hasSnapshotMapping() && (isCurrentVersionCorrupted || versionChanged)) { safeDelete(IndexInfrastructure.getPersistentIndexRootDir(name)); } safeDelete(IndexInfrastructure.getIndexRootDir(name)); IndexingStamp.rewriteVersion(versionFile, version); } initIndexStorage(extension, version, versionFile); return versionChanged; } private <K, V> void initIndexStorage(@NotNull FileBasedIndexExtension<K, V> extension, int version, @NotNull File versionFile) throws IOException { MapIndexStorage<K, V> storage = null; final ID<K, V> name = extension.getName(); boolean contentHashesEnumeratorOk = false; for (int attempt = 0; attempt < 2; attempt++) { try { if (extension.hasSnapshotMapping()) { ContentHashesSupport.initContentHashesEnumerator(); contentHashesEnumeratorOk = true; } storage = new MapIndexStorage<K, V>( IndexInfrastructure.getStorageFile(name), extension.getKeyDescriptor(), extension.getValueExternalizer(), extension.getCacheSize(), extension.isKeyHighlySelective(), extension.traceKeyHashToVirtualFileMapping() ); final MemoryIndexStorage<K, V> memStorage = new MemoryIndexStorage<K, V>(storage); final UpdatableIndex<K, V, FileContent> index = createIndex(name, extension, memStorage); final InputFilter inputFilter = extension.getInputFilter(); myIndices.put(name, new Pair<UpdatableIndex<?, ?, FileContent>, InputFilter>(index, new IndexableFilesFilter(inputFilter))); if (inputFilter instanceof FileTypeSpecificInputFilter) { ((FileTypeSpecificInputFilter)inputFilter).registerFileTypesUsedForIndexing(new Consumer<FileType>() { final Set<FileType> addedTypes = new THashSet<FileType>(); @Override public void consume(FileType type) { if (type == null || !addedTypes.add(type)) { return; } List<ID<?, ?>> ids = myFileType2IndicesWithFileTypeInfoMap.get(type); if (ids == null) myFileType2IndicesWithFileTypeInfoMap.put(type, ids = new ArrayList<ID<?, ?>>(5)); ids.add(name); } }); } else { myIndicesWithoutFileTypeInfo.add(name); } myUnsavedDataIndexingSemaphores.put(name, new Semaphore()); myIndexIdToVersionMap.put(name, version); if (!extension.dependsOnFileContent()) { if (extension.indexDirectories()) myIndicesForDirectories.add(name); myNotRequiringContentIndices.add(name); } else { myRequiringContentIndices.add(name); } if (extension instanceof PsiDependentIndex) myPsiDependentIndices.add(name); myNoLimitCheckTypes.addAll(extension.getFileTypesWithSizeLimitNotApplicable()); break; } catch (Exception e) { LOG.info(e); boolean instantiatedStorage = storage != null; try { if (storage != null) storage.close(); storage = null; } catch (Exception ignored) { } safeDelete(IndexInfrastructure.getIndexRootDir(name)); if (extension.hasSnapshotMapping() && (!contentHashesEnumeratorOk || instantiatedStorage)) { safeDelete(IndexInfrastructure.getPersistentIndexRootDir(name)); // todo there is possibility of corruption of storage and content hashes } IndexingStamp.rewriteVersion(versionFile, version); } } } private static boolean safeDelete(File dir) { File directory = FileUtil.findSequentNonexistentFile(dir.getParentFile(), dir.getName(), ""); boolean success = dir.renameTo(directory); return FileUtil.delete(success ? directory:dir); } private static void saveRegisteredIndices(@NotNull Collection<ID<?, ?>> ids) { final File file = getRegisteredIndicesFile(); try { FileUtil.createIfDoesntExist(file); final DataOutputStream os = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); try { os.writeInt(ids.size()); for (ID<?, ?> id : ids) { IOUtil.writeString(id.toString(), os); } } finally { os.close(); } } catch (IOException ignored) { } } @NotNull private static Set<String> readRegisteredIndexNames() { final Set<String> result = new THashSet<String>(); try { final DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(getRegisteredIndicesFile()))); try { final int size = in.readInt(); for (int idx = 0; idx < size; idx++) { result.add(IOUtil.readString(in)); } } finally { in.close(); } } catch (IOException ignored) { } return result; } @NotNull private static File getRegisteredIndicesFile() { return new File(PathManager.getIndexRoot(), "registered"); } @NotNull private <K, V> UpdatableIndex<K, V, FileContent> createIndex(@NotNull final ID<K, V> indexId, @NotNull final FileBasedIndexExtension<K, V> extension, @NotNull final MemoryIndexStorage<K, V> storage) throws StorageException, IOException { final MapReduceIndex<K, V, FileContent> index; if (extension instanceof CustomImplementationFileBasedIndexExtension) { final UpdatableIndex<K, V, FileContent> custom = ((CustomImplementationFileBasedIndexExtension<K, V, FileContent>)extension).createIndexImplementation(indexId, this, storage); if (!(custom instanceof MapReduceIndex)) { return custom; } index = (MapReduceIndex<K, V, FileContent>)custom; } else { DataExternalizer<Collection<K>> externalizer = extension.hasSnapshotMapping() && IdIndex.ourSnapshotMappingsEnabled ? createInputsIndexExternalizer(extension, indexId, extension.getKeyDescriptor()) : null; index = new MapReduceIndex<K, V, FileContent>(indexId, extension.getIndexer(), storage, externalizer, extension.getValueExternalizer()); } index.setInputIdToDataKeysIndex(new Factory<PersistentHashMap<Integer, Collection<K>>>() { @Override public PersistentHashMap<Integer, Collection<K>> create() { try { return createIdToDataKeysIndex(extension, storage); } catch (IOException e) { throw new RuntimeException(e); } } }); return index; } @NotNull public static <K> PersistentHashMap<Integer, Collection<K>> createIdToDataKeysIndex(@NotNull FileBasedIndexExtension <K, ?> extension, @NotNull MemoryIndexStorage<K, ?> storage) throws IOException { ID<K, ?> indexId = extension.getName(); KeyDescriptor<K> keyDescriptor = extension.getKeyDescriptor(); final File indexStorageFile = IndexInfrastructure.getInputIndexStorageFile(indexId); final AtomicBoolean isBufferingMode = new AtomicBoolean(); final TIntObjectHashMap<Collection<K>> tempMap = new TIntObjectHashMap<Collection<K>>(); // Important! Update IdToDataKeysIndex depending on the sate of "buffering" flag from the MemoryStorage. // If buffering is on, all changes should be done in memory (similar to the way it is done in memory storage). // Otherwise data in IdToDataKeysIndex will not be in sync with the 'main' data in the index on disk and index updates will be based on the // wrong sets of keys for the given file. This will lead to unpredictable results in main index because it will not be // cleared properly before updating (removed data will still be present on disk). See IDEA-52223 for illustration of possible effects. final PersistentHashMap<Integer, Collection<K>> map = new PersistentHashMap<Integer, Collection<K>>( indexStorageFile, EnumeratorIntegerDescriptor.INSTANCE, createInputsIndexExternalizer(extension, indexId, keyDescriptor) ) { @Override protected Collection<K> doGet(Integer integer) throws IOException { if (isBufferingMode.get()) { final Collection<K> collection = tempMap.get(integer); if (collection != null) { return collection; } } return super.doGet(integer); } @Override protected void doPut(Integer integer, @Nullable Collection<K> ks) throws IOException { if (isBufferingMode.get()) { tempMap.put(integer, ks == null ? Collections.<K>emptySet() : ks); } else { super.doPut(integer, ks); } } @Override protected void doRemove(Integer integer) throws IOException { if (isBufferingMode.get()) { tempMap.put(integer, Collections.<K>emptySet()); } else { super.doRemove(integer); } } }; storage.addBufferingStateListener(new MemoryIndexStorage.BufferingStateListener() { @Override public void bufferingStateChanged(boolean newState) { synchronized (map) { isBufferingMode.set(newState); } } @Override public void memoryStorageCleared() { synchronized (map) { tempMap.clear(); } } }); return map; } private static <K> DataExternalizer<Collection<K>> createInputsIndexExternalizer(FileBasedIndexExtension<K, ?> extension, ID<K, ?> indexId, KeyDescriptor<K> keyDescriptor) { DataExternalizer<Collection<K>> externalizer; if (extension instanceof CustomInputsIndexFileBasedIndexExtension) { externalizer = ((CustomInputsIndexFileBasedIndexExtension<K>)extension).createExternalizer(); } else { externalizer = new InputIndexDataExternalizer<K>(keyDescriptor, indexId); } return externalizer; } @Override public void disposeComponent() { performShutdown(); } private final AtomicBoolean myShutdownPerformed = new AtomicBoolean(false); private void performShutdown() { if (!myShutdownPerformed.compareAndSet(false, true)) { return; // already shut down } try { if (myFlushingFuture != null) { myFlushingFuture.cancel(false); myFlushingFuture = null; } //myFileDocumentManager.saveAllDocuments(); // rev=Eugene Juravlev } finally { LOG.info("START INDEX SHUTDOWN"); try { myChangedFilesCollector.ensureAllInvalidateTasksCompleted(); IndexingStamp.flushCaches(); for (ID<?, ?> indexId : myIndices.keySet()) { final UpdatableIndex<?, ?, FileContent> index = getIndex(indexId); assert index != null; checkRebuild(indexId, true); // if the index was scheduled for rebuild, only clean it index.dispose(); } myConnection.disconnect(); } catch (Throwable e) { LOG.error("Problems during index shutdown", e); } LOG.info("END INDEX SHUTDOWN"); } } private void flushAllIndices(final long modCount) { if (HeavyProcessLatch.INSTANCE.isRunning()) { return; } IndexingStamp.flushCaches(); for (ID<?, ?> indexId : new ArrayList<ID<?, ?>>(myIndices.keySet())) { if (HeavyProcessLatch.INSTANCE.isRunning() || modCount != myLocalModCount) { return; // do not interfere with 'main' jobs } try { final UpdatableIndex<?, ?, FileContent> index = getIndex(indexId); if (index != null) { index.flush(); } } catch (StorageException e) { LOG.info(e); requestRebuild(indexId); } } if (!HeavyProcessLatch.INSTANCE.isRunning() && modCount == myLocalModCount) { // do not interfere with 'main' jobs mySerializationManagerEx.flushNameStorage(); } } @Override @NotNull public <K> Collection<K> getAllKeys(@NotNull final ID<K, ?> indexId, @NotNull Project project) { Set<K> allKeys = new THashSet<K>(); processAllKeys(indexId, new CommonProcessors.CollectProcessor<K>(allKeys), project); return allKeys; } @Override public <K> boolean processAllKeys(@NotNull final ID<K, ?> indexId, @NotNull Processor<K> processor, @Nullable Project project) { return processAllKeys(indexId, processor, project == null ? new EverythingGlobalScope() : GlobalSearchScope.allScope(project), null); } @Override public <K> boolean processAllKeys(@NotNull ID<K, ?> indexId, @NotNull Processor<K> processor, @NotNull GlobalSearchScope scope, @Nullable IdFilter idFilter) { try { final UpdatableIndex<K, ?, FileContent> index = getIndex(indexId); if (index == null) { return true; } ensureUpToDate(indexId, scope.getProject(), scope); return index.processAllKeys(processor, scope, idFilter); } catch (StorageException e) { scheduleRebuild(indexId, e); } catch (RuntimeException e) { final Throwable cause = e.getCause(); if (cause instanceof StorageException || cause instanceof IOException) { scheduleRebuild(indexId, cause); } else { throw e; } } return false; } private static final ThreadLocal<Integer> myUpToDateCheckState = new ThreadLocal<Integer>(); public static void disableUpToDateCheckForCurrentThread() { final Integer currentValue = myUpToDateCheckState.get(); myUpToDateCheckState.set(currentValue == null ? 1 : currentValue.intValue() + 1); } public static void enableUpToDateCheckForCurrentThread() { final Integer currentValue = myUpToDateCheckState.get(); if (currentValue != null) { final int newValue = currentValue.intValue() - 1; if (newValue != 0) { myUpToDateCheckState.set(newValue); } else { myUpToDateCheckState.remove(); } } } private static boolean isUpToDateCheckEnabled() { final Integer value = myUpToDateCheckState.get(); return value == null || value.intValue() == 0; } private final ThreadLocal<Boolean> myReentrancyGuard = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return Boolean.FALSE; } }; /** * DO NOT CALL DIRECTLY IN CLIENT CODE * The method is internal to indexing engine end is called internally. The method is public due to implementation details */ @Override public <K> void ensureUpToDate(@NotNull final ID<K, ?> indexId, @Nullable Project project, @Nullable GlobalSearchScope filter) { ensureUpToDate(indexId, project, filter, null); } protected <K> void ensureUpToDate(@NotNull final ID<K, ?> indexId, @Nullable Project project, @Nullable GlobalSearchScope filter, @Nullable VirtualFile restrictedFile) { ProgressManager.checkCanceled(); myContentlessIndicesUpdateQueue.ensureUpToDate(); // some content full indices depends on contentless ones if (!needsFileContentLoading(indexId)) { return; //indexed eagerly in foreground while building unindexed file list } if (filter == GlobalSearchScope.EMPTY_SCOPE) { return; } if (isDumb(project)) { handleDumbMode(project); } if (myReentrancyGuard.get().booleanValue()) { //assert false : "ensureUpToDate() is not reentrant!"; return; } myReentrancyGuard.set(Boolean.TRUE); try { myChangedFilesCollector.ensureAllInvalidateTasksCompleted(); if (isUpToDateCheckEnabled()) { try { checkRebuild(indexId, false); myChangedFilesCollector.forceUpdate(project, filter, restrictedFile); indexUnsavedDocuments(indexId, project, filter, restrictedFile); } catch (StorageException e) { scheduleRebuild(indexId, e); } catch (RuntimeException e) { final Throwable cause = e.getCause(); if (cause instanceof StorageException || cause instanceof IOException) { scheduleRebuild(indexId, e); } else { throw e; } } } } finally { myReentrancyGuard.set(Boolean.FALSE); } } private static void handleDumbMode(@Nullable Project project) { ProgressManager.checkCanceled(); // DumbModeAction.CANCEL if (project != null) { final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); if (progressIndicator instanceof BackgroundableProcessIndicator) { final BackgroundableProcessIndicator indicator = (BackgroundableProcessIndicator)progressIndicator; if (indicator.getDumbModeAction() == DumbModeAction.WAIT) { assert !ApplicationManager.getApplication().isDispatchThread(); DumbService.getInstance(project).waitForSmartMode(); return; } } } throw new IndexNotReadyException(); } private static boolean isDumb(@Nullable Project project) { if (project != null) { return DumbServiceImpl.getInstance(project).isDumb(); } for (Project proj : ProjectManager.getInstance().getOpenProjects()) { if (DumbServiceImpl.getInstance(proj).isDumb()) { return true; } } return false; } @Override @NotNull public <K, V> List<V> getValues(@NotNull final ID<K, V> indexId, @NotNull K dataKey, @NotNull final GlobalSearchScope filter) { final List<V> values = new SmartList<V>(); processValuesImpl(indexId, dataKey, true, null, new ValueProcessor<V>() { @Override public boolean process(final VirtualFile file, final V value) { values.add(value); return true; } }, filter, null); return values; } @Override @NotNull public <K, V> Collection<VirtualFile> getContainingFiles(@NotNull final ID<K, V> indexId, @NotNull K dataKey, @NotNull final GlobalSearchScope filter) { final Set<VirtualFile> files = new THashSet<VirtualFile>(); processValuesImpl(indexId, dataKey, false, null, new ValueProcessor<V>() { @Override public boolean process(final VirtualFile file, final V value) { files.add(file); return true; } }, filter, null); return files; } @Override public <K, V> boolean processValues(@NotNull final ID<K, V> indexId, @NotNull final K dataKey, @Nullable final VirtualFile inFile, @NotNull ValueProcessor<V> processor, @NotNull final GlobalSearchScope filter) { return processValues(indexId, dataKey, inFile, processor, filter, null); } @Override public <K, V> boolean processValues(@NotNull ID<K, V> indexId, @NotNull K dataKey, @Nullable VirtualFile inFile, @NotNull ValueProcessor<V> processor, @NotNull GlobalSearchScope filter, @Nullable IdFilter idFilter) { return processValuesImpl(indexId, dataKey, false, inFile, processor, filter, idFilter); } @Nullable private <K, V, R> R processExceptions(@NotNull final ID<K, V> indexId, @Nullable final VirtualFile restrictToFile, @NotNull final GlobalSearchScope filter, @NotNull ThrowableConvertor<UpdatableIndex<K, V, FileContent>, R, StorageException> computable) { try { final UpdatableIndex<K, V, FileContent> index = getIndex(indexId); if (index == null) { return null; } final Project project = filter.getProject(); //assert project != null : "GlobalSearchScope#getProject() should be not-null for all index queries"; ensureUpToDate(indexId, project, filter, restrictToFile); try { index.getReadLock().lock(); return computable.convert(index); } finally { index.getReadLock().unlock(); } } catch (StorageException e) { scheduleRebuild(indexId, e); } catch (RuntimeException e) { final Throwable cause = getCauseToRebuildIndex(e); if (cause != null) { scheduleRebuild(indexId, cause); } else { throw e; } } catch(AssertionError ae) { scheduleRebuild(indexId, ae); } return null; } private <K, V> boolean processValuesImpl(@NotNull final ID<K, V> indexId, @NotNull final K dataKey, final boolean ensureValueProcessedOnce, @Nullable final VirtualFile restrictToFile, @NotNull final ValueProcessor<V> processor, @NotNull final GlobalSearchScope scope, @Nullable final IdFilter idFilter) { ThrowableConvertor<UpdatableIndex<K, V, FileContent>, Boolean, StorageException> keyProcessor = new ThrowableConvertor<UpdatableIndex<K, V, FileContent>, Boolean, StorageException>() { @Override public Boolean convert(@NotNull UpdatableIndex<K, V, FileContent> index) throws StorageException { final ValueContainer<V> container = index.getData(dataKey); boolean shouldContinue = true; if (restrictToFile != null) { if (restrictToFile instanceof VirtualFileWithId) { final int restrictedFileId = getFileId(restrictToFile); for (final Iterator<V> valueIt = container.getValueIterator(); valueIt.hasNext(); ) { final V value = valueIt.next(); if (container.isAssociated(value, restrictedFileId)) { shouldContinue = processor.process(restrictToFile, value); if (!shouldContinue) { break; } } } } } else { final PersistentFS fs = (PersistentFS)ManagingFS.getInstance(); final IdFilter filter = idFilter != null ? idFilter : projectIndexableFiles(scope.getProject()); VALUES_LOOP: for (final Iterator<V> valueIt = container.getValueIterator(); valueIt.hasNext(); ) { final V value = valueIt.next(); for (final ValueContainer.IntIterator inputIdsIterator = container.getInputIdsIterator(value); inputIdsIterator.hasNext(); ) { final int id = inputIdsIterator.next(); if (filter != null && !filter.containsFileId(id)) continue; VirtualFile file = IndexInfrastructure.findFileByIdIfCached(fs, id); if (file != null && scope.accept(file)) { shouldContinue = processor.process(file, value); if (!shouldContinue) { break VALUES_LOOP; } if (ensureValueProcessedOnce) { break; // continue with the next value } } } } } return shouldContinue; } }; final Boolean result = processExceptions(indexId, restrictToFile, scope, keyProcessor); return result == null || result.booleanValue(); } @Override public <K, V> boolean processFilesContainingAllKeys(@NotNull final ID<K, V> indexId, @NotNull final Collection<K> dataKeys, @NotNull final GlobalSearchScope filter, @Nullable Condition<V> valueChecker, @NotNull final Processor<VirtualFile> processor) { ProjectIndexableFilesFilter filesSet = projectIndexableFiles(filter.getProject()); final TIntHashSet set = collectFileIdsContainingAllKeys(indexId, dataKeys, filter, valueChecker, filesSet); return set != null && processVirtualFiles(set, filter, processor); } private static final Key<SoftReference<ProjectIndexableFilesFilter>> ourProjectFilesSetKey = Key.create("projectFiles"); public void filesUpdateEnumerationFinished() { myContentlessIndicesUpdateQueue.ensureUpToDate(); myContentlessIndicesUpdateQueue.signalUpdateEnd(); } public static final class ProjectIndexableFilesFilter extends IdFilter { private static final int SHIFT = 6; private static final int MASK = (1 << SHIFT) - 1; private final long[] myBitMask; private final int myModificationCount; private final int myMinId; private final int myMaxId; private ProjectIndexableFilesFilter(@NotNull TIntArrayList set, int modificationCount) { myModificationCount = modificationCount; final int[] minMax = new int[2]; if (!set.isEmpty()) { minMax[0] = minMax[1] = set.get(0); } set.forEach(new TIntProcedure() { @Override public boolean execute(int value) { if (value < 0) value = -value; minMax[0] = Math.min(minMax[0], value); minMax[1] = Math.max(minMax[1], value); return true; } }); myMaxId = minMax[1]; myMinId = minMax[0]; myBitMask = new long[((myMaxId - myMinId) >> SHIFT) + 1]; set.forEach(new TIntProcedure() { @Override public boolean execute(int value) { if (value < 0) value = -value; value -= myMinId; myBitMask[value >> SHIFT] |= (1L << (value & MASK)); return true; } }); } @Override public boolean containsFileId(int id) { if (id < myMinId) return false; if (id > myMaxId) return false; id -= myMinId; return (myBitMask[id >> SHIFT] & (1L << (id & MASK))) != 0; } } void filesUpdateStarted(Project project) { myContentlessIndicesUpdateQueue.signalUpdateStart(); myContentlessIndicesUpdateQueue.ensureUpToDate(); myProjectsBeingUpdated.add(project); } void filesUpdateFinished(@NotNull Project project) { myProjectsBeingUpdated.remove(project); ++myFilesModCount; } private final Lock myCalcIndexableFilesLock = new SequenceLock(); @Nullable public ProjectIndexableFilesFilter projectIndexableFiles(@Nullable Project project) { if (project == null || myUpdatingFiles.get() > 0) return null; if (myProjectsBeingUpdated.contains(project)) return null; SoftReference<ProjectIndexableFilesFilter> reference = project.getUserData(ourProjectFilesSetKey); ProjectIndexableFilesFilter data = com.intellij.reference.SoftReference.dereference(reference); if (data != null && data.myModificationCount == myFilesModCount) return data; if (myCalcIndexableFilesLock.tryLock()) { // make best effort for calculating filter try { reference = project.getUserData(ourProjectFilesSetKey); data = com.intellij.reference.SoftReference.dereference(reference); if (data != null && data.myModificationCount == myFilesModCount) { return data; } long start = System.currentTimeMillis(); final TIntArrayList filesSet = new TIntArrayList(); iterateIndexableFiles(new ContentIterator() { @Override public boolean processFile(@NotNull VirtualFile fileOrDir) { filesSet.add(((VirtualFileWithId)fileOrDir).getId()); return true; } }, project, SilentProgressIndicator.create()); ProjectIndexableFilesFilter filter = new ProjectIndexableFilesFilter(filesSet, myFilesModCount); project.putUserData(ourProjectFilesSetKey, new SoftReference<ProjectIndexableFilesFilter>(filter)); long finish = System.currentTimeMillis(); LOG.debug(filesSet.size() + " files iterated in " + (finish - start) + " ms"); return filter; } finally { myCalcIndexableFilesLock.unlock(); } } return null; // ok, no filtering } @Nullable private <K, V> TIntHashSet collectFileIdsContainingAllKeys(@NotNull final ID<K, V> indexId, @NotNull final Collection<K> dataKeys, @NotNull final GlobalSearchScope filter, @Nullable final Condition<V> valueChecker, @Nullable final ProjectIndexableFilesFilter projectFilesFilter) { final ThrowableConvertor<UpdatableIndex<K, V, FileContent>, TIntHashSet, StorageException> convertor = new ThrowableConvertor<UpdatableIndex<K, V, FileContent>, TIntHashSet, StorageException>() { @Nullable @Override public TIntHashSet convert(@NotNull UpdatableIndex<K, V, FileContent> index) throws StorageException { TIntHashSet mainIntersection = null; for (K dataKey : dataKeys) { ProgressManager.checkCanceled(); final TIntHashSet copy = new TIntHashSet(); final ValueContainer<V> container = index.getData(dataKey); for (final Iterator<V> valueIt = container.getValueIterator(); valueIt.hasNext(); ) { final V value = valueIt.next(); if (valueChecker != null && !valueChecker.value(value)) { continue; } ValueContainer.IntIterator iterator = container.getInputIdsIterator(value); if (mainIntersection == null || iterator.size() < mainIntersection.size()) { while (iterator.hasNext()) { final int id = iterator.next(); if (mainIntersection == null && (projectFilesFilter == null || projectFilesFilter.containsFileId(id)) || mainIntersection != null && mainIntersection.contains(id) ) { copy.add(id); } } } else { mainIntersection.forEach(new TIntProcedure() { final ValueContainer.IntPredicate predicate = container.getValueAssociationPredicate(value); @Override public boolean execute(int id) { if (predicate.contains(id)) copy.add(id); return true; } }); } } mainIntersection = copy; if (mainIntersection.isEmpty()) { return new TIntHashSet(); } } return mainIntersection; } }; return processExceptions(indexId, null, filter, convertor); } private static boolean processVirtualFiles(@NotNull TIntHashSet ids, @NotNull final GlobalSearchScope filter, @NotNull final Processor<VirtualFile> processor) { final PersistentFS fs = (PersistentFS)ManagingFS.getInstance(); return ids.forEach(new TIntProcedure() { @Override public boolean execute(int id) { ProgressManager.checkCanceled(); VirtualFile file = IndexInfrastructure.findFileByIdIfCached(fs, id); if (file != null && filter.accept(file)) { return processor.process(file); } return true; } }); } @Nullable public static Throwable getCauseToRebuildIndex(@NotNull RuntimeException e) { Throwable cause = e.getCause(); if (cause instanceof StorageException || cause instanceof IOException || cause instanceof IllegalArgumentException) return cause; return null; } @Override public <K, V> boolean getFilesWithKey(@NotNull final ID<K, V> indexId, @NotNull final Set<K> dataKeys, @NotNull Processor<VirtualFile> processor, @NotNull GlobalSearchScope filter) { return processFilesContainingAllKeys(indexId, dataKeys, filter, null, processor); } @Override public <K> void scheduleRebuild(@NotNull final ID<K, ?> indexId, @NotNull final Throwable e) { requestRebuild(indexId, new Throwable(e)); try { checkRebuild(indexId, false); } catch (ProcessCanceledException ignored) { } } private void checkRebuild(@NotNull final ID<?, ?> indexId, final boolean cleanupOnly) { final AtomicInteger status = ourRebuildStatus.get(indexId); if (status.get() == OK) { return; } if (status.compareAndSet(REQUIRES_REBUILD, REBUILD_IN_PROGRESS)) { cleanupProcessedFlag(); advanceIndexVersion(indexId); final Runnable rebuildRunnable = new Runnable() { @Override public void run() { try { doClearIndex(indexId); if (!cleanupOnly) { scheduleIndexRebuild(); } } catch (StorageException e) { requestRebuild(indexId); LOG.info(e); } finally { status.compareAndSet(REBUILD_IN_PROGRESS, OK); } } }; if (cleanupOnly || myIsUnitTestMode) { rebuildRunnable.run(); } else { //noinspection SSBasedInspection ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { new Task.Modal(null, "Updating index", false) { @Override public void run(@NotNull final ProgressIndicator indicator) { indicator.setIndeterminate(true); rebuildRunnable.run(); } }.queue(); } }, ModalityState.NON_MODAL); } } if (status.get() == REBUILD_IN_PROGRESS) { throw new ProcessCanceledException(); } } private static void scheduleIndexRebuild() { for (Project project : ProjectManager.getInstance().getOpenProjects()) { DumbService.getInstance(project).queueTask(new UnindexedFilesUpdater(project, false)); } } private void clearIndex(@NotNull final ID<?, ?> indexId) throws StorageException { advanceIndexVersion(indexId); doClearIndex(indexId); } private void doClearIndex(ID<?, ?> indexId) throws StorageException { final UpdatableIndex<?, ?, FileContent> index = getIndex(indexId); assert index != null : "Index with key " + indexId + " not found or not registered properly"; index.clear(); } private void advanceIndexVersion(ID<?, ?> indexId) { try { IndexingStamp.rewriteVersion(IndexInfrastructure.getVersionFile(indexId), myIndexIdToVersionMap.get(indexId)); } catch (IOException e) { LOG.error(e); } } @NotNull private Set<Document> getUnsavedDocuments() { return new THashSet<Document>(Arrays.asList(myFileDocumentManager.getUnsavedDocuments())); } @NotNull private Set<Document> getTransactedDocuments() { return myTransactionMap.keySet(); } private void indexUnsavedDocuments(@NotNull ID<?, ?> indexId, @Nullable Project project, GlobalSearchScope filter, VirtualFile restrictedFile) throws StorageException { if (myUpToDateIndicesForUnsavedOrTransactedDocuments.contains(indexId)) { return; // no need to index unsaved docs } Set<Document> documents = getUnsavedDocuments(); boolean psiBasedIndex = myPsiDependentIndices.contains(indexId); if(psiBasedIndex) { documents.addAll(getTransactedDocuments()); } if (!documents.isEmpty()) { // now index unsaved data final StorageGuard.StorageModeExitHandler guard = setDataBufferingEnabled(true); try { final Semaphore semaphore = myUnsavedDataIndexingSemaphores.get(indexId); assert semaphore != null : "Semaphore for unsaved data indexing was not initialized for index " + indexId; semaphore.down(); boolean allDocsProcessed = true; try { for (Document document : documents) { if (psiBasedIndex && project != null && PsiDocumentManager.getInstance(project).isUncommited(document)) { continue; } allDocsProcessed &= indexUnsavedDocument(document, indexId, project, filter, restrictedFile); ProgressManager.checkCanceled(); } } finally { semaphore.up(); while (!semaphore.waitFor(500)) { // may need to wait until another thread is done with indexing ProgressManager.checkCanceled(); if (Thread.holdsLock(PsiLock.LOCK)) { break; // hack. Most probably that other indexing threads is waiting for PsiLock, which we're are holding. } } if (allDocsProcessed && !hasActiveTransactions()) { ProgressManager.checkCanceled(); // assume all tasks were finished or cancelled in the same time // safe to set the flag here, because it will be cleared under the WriteAction myUpToDateIndicesForUnsavedOrTransactedDocuments.add(indexId); } } } finally { guard.leave(); } } } private boolean hasActiveTransactions() { return !myTransactionMap.isEmpty(); } private interface DocumentContent { CharSequence getText(); long getModificationStamp(); } private static class AuthenticContent implements DocumentContent { private final Document myDocument; private AuthenticContent(final Document document) { myDocument = document; } @Override public CharSequence getText() { return myDocument.getImmutableCharSequence(); } @Override public long getModificationStamp() { return myDocument.getModificationStamp(); } } private static class PsiContent implements DocumentContent { private final Document myDocument; private final PsiFile myFile; private PsiContent(final Document document, final PsiFile file) { myDocument = document; myFile = file; } @Override public CharSequence getText() { if (myFile.getViewProvider().getModificationStamp() != myDocument.getModificationStamp()) { final ASTNode node = myFile.getNode(); assert node != null; return node.getChars(); } return myDocument.getImmutableCharSequence(); } @Override public long getModificationStamp() { return myFile.getViewProvider().getModificationStamp(); } } private static final Key<WeakReference<FileContentImpl>> ourFileContentKey = Key.create("unsaved.document.index.content"); // returns false if doc was not indexed because the file does not fit in scope private boolean indexUnsavedDocument(@NotNull final Document document, @NotNull final ID<?, ?> requestedIndexId, final Project project, @Nullable GlobalSearchScope filter, @Nullable VirtualFile restrictedFile) { final VirtualFile vFile = myFileDocumentManager.getFile(document); if (!(vFile instanceof VirtualFileWithId) || !vFile.isValid()) { return true; } if (restrictedFile != null) { if (!Comparing.equal(vFile, restrictedFile)) { return false; } } else if (filter != null && !filter.accept(vFile)) { return false; } final PsiFile dominantContentFile = findDominantPsiForDocument(document, project); final DocumentContent content; if (dominantContentFile != null && dominantContentFile.getViewProvider().getModificationStamp() != document.getModificationStamp()) { content = new PsiContent(document, dominantContentFile); } else { content = new AuthenticContent(document); } final long currentDocStamp = content.getModificationStamp(); final long previousDocStamp = myLastIndexedDocStamps.getAndSet(document, requestedIndexId, currentDocStamp); if (currentDocStamp != previousDocStamp) { final CharSequence contentText = content.getText(); FileTypeManagerImpl.cacheFileType(vFile, vFile.getFileType()); try { if (!isTooLarge(vFile, contentText.length()) && getAffectedIndexCandidates(vFile).contains(requestedIndexId) && getInputFilter(requestedIndexId).acceptInput(vFile)) { // Reasonably attempt to use same file content when calculating indices as we can evaluate them several at once and store in file content WeakReference<FileContentImpl> previousContentRef = document.getUserData(ourFileContentKey); FileContentImpl previousContent = com.intellij.reference.SoftReference.dereference(previousContentRef); final FileContentImpl newFc; if (previousContent != null && previousContent.getStamp() == currentDocStamp) { newFc = previousContent; } else { newFc = new FileContentImpl(vFile, contentText, vFile.getCharset(), currentDocStamp); document.putUserData(ourFileContentKey, new WeakReference<FileContentImpl>(newFc)); } initFileContent(newFc, project, dominantContentFile); if (content instanceof AuthenticContent) { newFc.putUserData(PlatformIdTableBuilding.EDITOR_HIGHLIGHTER, EditorHighlighterCache.getEditorHighlighterForCachesBuilding(document)); } final int inputId = Math.abs(getFileId(vFile)); try { getIndex(requestedIndexId).update(inputId, newFc).compute(); } catch (ProcessCanceledException pce) { myLastIndexedDocStamps.getAndSet(document, requestedIndexId, previousDocStamp); throw pce; } finally { cleanFileContent(newFc, dominantContentFile); } } } finally { FileTypeManagerImpl.cacheFileType(vFile, null); } } return true; } private final TaskQueue myContentlessIndicesUpdateQueue = new TaskQueue(10000); @Nullable private PsiFile findDominantPsiForDocument(@NotNull Document document, @Nullable Project project) { PsiFile psiFile = myTransactionMap.get(document); if (psiFile != null) return psiFile; return project == null ? null : findLatestKnownPsiForUncomittedDocument(document, project); } private final StorageGuard myStorageLock = new StorageGuard(); private volatile boolean myPreviousDataBufferingState; private final Object myBufferingStateUpdateLock = new Object(); @NotNull private StorageGuard.StorageModeExitHandler setDataBufferingEnabled(final boolean enabled) { StorageGuard.StorageModeExitHandler storageModeExitHandler = myStorageLock.enter(enabled); if (myPreviousDataBufferingState != enabled) { synchronized (myBufferingStateUpdateLock) { if (myPreviousDataBufferingState != enabled) { for (ID<?, ?> indexId : myIndices.keySet()) { final MapReduceIndex index = (MapReduceIndex)getIndex(indexId); assert index != null; ((MemoryIndexStorage)index.getStorage()).setBufferingEnabled(enabled); } myPreviousDataBufferingState = enabled; } } } return storageModeExitHandler; } private void cleanupMemoryStorage() { myLastIndexedDocStamps.clear(); for (ID<?, ?> indexId : myIndices.keySet()) { final MapReduceIndex index = (MapReduceIndex)getIndex(indexId); assert index != null; final MemoryIndexStorage memStorage = (MemoryIndexStorage)index.getStorage(); index.getWriteLock().lock(); try { memStorage.clearMemoryMap(); } finally { index.getWriteLock().unlock(); } memStorage.fireMemoryStorageCleared(); } } private void dropUnregisteredIndices() { final Set<String> indicesToDrop = readRegisteredIndexNames(); for (ID<?, ?> key : myIndices.keySet()) { indicesToDrop.remove(key.toString()); } for (String s : indicesToDrop) { safeDelete(IndexInfrastructure.getIndexRootDir(ID.create(s))); } } @Override public void requestRebuild(ID<?, ?> indexId, Throwable throwable) { cleanupProcessedFlag(); boolean requiresRebuildWasSet = ourRebuildStatus.get(indexId).compareAndSet(OK, REQUIRES_REBUILD); if (requiresRebuildWasSet) LOG.info("Rebuild requested for index " + indexId, throwable); } private <K, V> UpdatableIndex<K, V, FileContent> getIndex(ID<K, V> indexId) { final Pair<UpdatableIndex<?, ?, FileContent>, InputFilter> pair = myIndices.get(indexId); assert pair != null : "Index data is absent for index " + indexId; //noinspection unchecked return (UpdatableIndex<K, V, FileContent>)pair.getFirst(); } private InputFilter getInputFilter(@NotNull ID<?, ?> indexId) { final Pair<UpdatableIndex<?, ?, FileContent>, InputFilter> pair = myIndices.get(indexId); assert pair != null : "Index data is absent for index " + indexId; return pair.getSecond(); } public int getNumberOfPendingInvalidations() { return myChangedFilesCollector.getNumberOfPendingInvalidations(); } public int getChangedFileCount() { return myChangedFilesCollector.getAllFilesToUpdate().size(); } @NotNull public Collection<VirtualFile> getFilesToUpdate(final Project project) { return ContainerUtil.findAll(myChangedFilesCollector.getAllFilesToUpdate(), new Condition<VirtualFile>() { @Override public boolean value(VirtualFile virtualFile) { for (IndexableFileSet set : myIndexableSets) { final Project proj = myIndexableSetToProjectMap.get(set); if (proj != null && !proj.equals(project)) { continue; // skip this set as associated with a different project } if (set.isInSet(virtualFile)) { return true; } } return false; } }); } public boolean isFileUpToDate(VirtualFile file) { return !myChangedFilesCollector.myFilesToUpdate.contains(file); } void processRefreshedFile(@NotNull Project project, @NotNull final com.intellij.ide.caches.FileContent fileContent) { myChangedFilesCollector.ensureAllInvalidateTasksCompleted(); myChangedFilesCollector.processFileImpl(project, fileContent); // ProcessCanceledException will cause re-adding the file to processing list } public void indexFileContent(@Nullable Project project, @NotNull com.intellij.ide.caches.FileContent content) { VirtualFile file = content.getVirtualFile(); // if file was scheduled for update due to vfs events then it is present in myFilesToUpdate // in this case we consider that current indexing (out of roots backed CacheUpdater) will cover its content // todo this assumption isn't correct for vfs events happened between content loading and indexing itself // proper fix will when events handling will be out of direct execution by EDT myChangedFilesCollector.myFilesToUpdate.remove(file); doIndexFileContent(project, content); } private void doIndexFileContent(@Nullable Project project, @NotNull com.intellij.ide.caches.FileContent content) { myChangedFilesCollector.ensureAllInvalidateTasksCompleted(); final VirtualFile file = content.getVirtualFile(); FileType fileType = file.getFileType(); FileTypeManagerImpl.cacheFileType(file, fileType); try { PsiFile psiFile = null; FileContentImpl fc = null; final List<ID<?, ?>> affectedIndexCandidates = getAffectedIndexCandidates(file); //noinspection ForLoopReplaceableByForEach for (int i = 0, size = affectedIndexCandidates.size(); i < size; ++i) { final ID<?, ?> indexId = affectedIndexCandidates.get(i); if (shouldIndexFile(file, indexId)) { if (fc == null) { byte[] currentBytes; byte[] hash; try { currentBytes = content.getBytes(); hash = fileType.isBinary() || !IdIndex.ourSnapshotMappingsEnabled ? null:ContentHashesSupport.calcContentHashWithFileType(currentBytes, fileType); } catch (IOException e) { currentBytes = ArrayUtil.EMPTY_BYTE_ARRAY; hash = null; } fc = new FileContentImpl(file, currentBytes, hash); if (project == null) { project = ProjectUtil.guessProjectForFile(file); } psiFile = content.getUserData(IndexingDataKeys.PSI_FILE); initFileContent(fc, project, psiFile); } try { ProgressManager.checkCanceled(); updateSingleIndex(indexId, file, fc); } catch (ProcessCanceledException e) { cleanFileContent(fc, psiFile); myChangedFilesCollector.scheduleForUpdate(file); throw e; } catch (StorageException e) { requestRebuild(indexId); LOG.info(e); } } } if (psiFile != null) { psiFile.putUserData(PsiFileImpl.BUILDING_STUB, null); } } finally { FileTypeManagerImpl.cacheFileType(file, null); } } public boolean isIndexingCandidate(@NotNull VirtualFile file, @NotNull ID<?, ?> indexId) { return !isTooLarge(file) && getAffectedIndexCandidates(file).contains(indexId); } @NotNull private List<ID<?, ?>> getAffectedIndexCandidates(@NotNull VirtualFile file) { if (file.isDirectory()) { return isProjectOrWorkspaceFile(file, null) ? Collections.<ID<?,?>>emptyList() : myIndicesForDirectories; } FileType fileType = file.getFileType(); if(isProjectOrWorkspaceFile(file, fileType)) return Collections.emptyList(); List<ID<?, ?>> ids = myFileType2IndicesWithFileTypeInfoMap.get(fileType); if (ids == null) ids = myIndicesWithoutFileTypeInfo; return ids; } private static void cleanFileContent(@NotNull FileContentImpl fc, PsiFile psiFile) { if (psiFile != null) psiFile.putUserData(PsiFileImpl.BUILDING_STUB, false); fc.putUserData(IndexingDataKeys.PSI_FILE, null); } private static void initFileContent(@NotNull FileContentImpl fc, Project project, PsiFile psiFile) { if (psiFile != null) { psiFile.putUserData(PsiFileImpl.BUILDING_STUB, true); fc.putUserData(IndexingDataKeys.PSI_FILE, psiFile); } fc.putUserData(IndexingDataKeys.PROJECT, project); } private void updateSingleIndex(@NotNull ID<?, ?> indexId, @NotNull final VirtualFile file, @Nullable FileContent currentFC) throws StorageException { if (ourRebuildStatus.get(indexId).get() == REQUIRES_REBUILD) { return; // the index is scheduled for rebuild, no need to update } myLocalModCount++; final int inputId = Math.abs(getFileId(file)); final UpdatableIndex<?, ?, FileContent> index = getIndex(indexId); assert index != null; if (currentFC != null && currentFC.getUserData(ourPhysicalContentKey) == null) { currentFC.putUserData(ourPhysicalContentKey, Boolean.TRUE); } // important: no hard referencing currentFC to avoid OOME, the methods introduced for this purpose! final Computable<Boolean> update = index.update(inputId, currentFC); scheduleUpdate(indexId, createUpdateComputableWithBufferingDisabled(update), createIndexedStampUpdateRunnable(indexId, file, currentFC != null) ); } static final Key<Boolean> ourPhysicalContentKey = Key.create("physical.content.flag"); @NotNull private Runnable createIndexedStampUpdateRunnable(@NotNull final ID<?, ?> indexId, @NotNull final VirtualFile file, final boolean hasContent) { return new Runnable() { @Override public void run() { if (file.isValid()) { if (hasContent) { IndexingStamp.setFileIndexedStateCurrent(file, indexId); } else { IndexingStamp.setFileIndexedStateUnindexed(file, indexId); } if (myNotRequiringContentIndices.contains(indexId)) IndexingStamp.flushCache(file); } } }; } @NotNull private Computable<Boolean> createUpdateComputableWithBufferingDisabled(@NotNull final Computable<Boolean> update) { return new Computable<Boolean>() { @Override public Boolean compute() { Boolean result; final StorageGuard.StorageModeExitHandler lock = setDataBufferingEnabled(false); try { result = update.compute(); } finally { lock.leave(); } return result; } }; } private void scheduleUpdate(@NotNull ID<?, ?> indexId, @NotNull Computable<Boolean> update, @NotNull Runnable successRunnable) { if (myNotRequiringContentIndices.contains(indexId)) { myContentlessIndicesUpdateQueue.submit(update, successRunnable); } else { Boolean result = update.compute(); if (result == Boolean.TRUE) ApplicationManager.getApplication().runReadAction(successRunnable); } } private boolean needsFileContentLoading(@NotNull ID<?, ?> indexId) { return !myNotRequiringContentIndices.contains(indexId); } private abstract static class InvalidationTask implements Runnable { private final VirtualFile mySubj; protected InvalidationTask(@NotNull VirtualFile subj) { mySubj = subj; } @NotNull public VirtualFile getSubj() { return mySubj; } } private static class SilentProgressIndicator extends DelegatingProgressIndicator { // suppress verbose messages private SilentProgressIndicator(ProgressIndicator indicator) { super(indicator); } @Nullable private static SilentProgressIndicator create() { final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); return indicator != null ? new SilentProgressIndicator(indicator) : null; } @Override public void setText(String text) { } @Override public String getText() { return ""; } @Override public void setText2(String text) { } @Override public String getText2() { return ""; } } private final class ChangedFilesCollector extends VirtualFileAdapter implements BulkFileListener { private final Set<VirtualFile> myFilesToUpdate = new ConcurrentHashSet<VirtualFile>(); private final Queue<InvalidationTask> myFutureInvalidations = new ConcurrentLinkedQueue<InvalidationTask>(); private final ManagingFS myManagingFS = ManagingFS.getInstance(); @Override public void fileMoved(@NotNull VirtualFileMoveEvent event) { markDirty(event, false); } @Override public void fileCreated(@NotNull final VirtualFileEvent event) { markDirty(event, false); } @Override public void fileCopied(@NotNull final VirtualFileCopyEvent event) { markDirty(event, false); } @Override public void beforeFileDeletion(@NotNull final VirtualFileEvent event) { invalidateIndices(event.getFile(), false); } @Override public void beforeContentsChange(@NotNull final VirtualFileEvent event) { invalidateIndices(event.getFile(), true); } @Override public void contentsChanged(@NotNull final VirtualFileEvent event) { markDirty(event, true); } @Override public void beforePropertyChange(@NotNull final VirtualFilePropertyEvent event) { if (event.getPropertyName().equals(VirtualFile.PROP_NAME)) { // indexes may depend on file name final VirtualFile file = event.getFile(); // name change may lead to filetype change so the file might become not indexable // in general case have to 'unindex' the file and index it again if needed after the name has been changed invalidateIndices(file, false); } } @Override public void propertyChanged(@NotNull final VirtualFilePropertyEvent event) { if (event.getPropertyName().equals(VirtualFile.PROP_NAME)) { // indexes may depend on file name markDirty(event, false); } } private void markDirty(@NotNull final VirtualFileEvent event, final boolean contentChange) { final VirtualFile eventFile = event.getFile(); cleanProcessedFlag(eventFile); if (!contentChange) { myUpdatingFiles.incrementAndGet(); } iterateIndexableFiles(eventFile, new Processor<VirtualFile>() { @Override public boolean process(@NotNull final VirtualFile file) { // handle 'content-less' indices separately boolean fileIsDirectory = file.isDirectory(); if (!contentChange) { FileContent fileContent = null; for (ID<?, ?> indexId : fileIsDirectory ? myIndicesForDirectories : myNotRequiringContentIndices) { if (getInputFilter(indexId).acceptInput(file)) { try { if (fileContent == null) { fileContent = new FileContentImpl(file); } updateSingleIndex(indexId, file, fileContent); } catch (StorageException e) { LOG.info(e); requestRebuild(indexId); } } } } // For 'normal indices' schedule the file for update and reset stamps for all affected indices (there // can be client that used indices between before and after events, in such case indices are up to date due to force update // with old content) if (!fileIsDirectory && !isTooLarge(file)) { FileTypeManagerImpl.cacheFileType(file, file.getFileType()); try { final List<ID<?, ?>> candidates = getAffectedIndexCandidates(file); //noinspection ForLoopReplaceableByForEach boolean scheduleForUpdate = false; boolean resetStamp = false; //noinspection ForLoopReplaceableByForEach for (int i = 0, size = candidates.size(); i < size; ++i) { final ID<?, ?> indexId = candidates.get(i); if (needsFileContentLoading(indexId) && getInputFilter(indexId).acceptInput(file)) { if (IndexingStamp.isFileIndexedStateCurrent(file, indexId)) { IndexingStamp.setFileIndexedStateOutdated(file, indexId); resetStamp = true; } scheduleForUpdate = true; } } if (scheduleForUpdate) { if (resetStamp) IndexingStamp.flushCache(file); scheduleForUpdate(file); } } finally { FileTypeManagerImpl.cacheFileType(file, null); } } return true; } }); IndexingStamp.flushCaches(); if (!contentChange) { if (myUpdatingFiles.decrementAndGet() == 0) { ++myFilesModCount; } } } private void scheduleForUpdate(VirtualFile file) { myFilesToUpdate.add(file); } private void invalidateIndices(@NotNull final VirtualFile file, final boolean markForReindex) { VfsUtilCore.visitChildrenRecursively(file, new VirtualFileVisitor() { @Override public boolean visitFile(@NotNull VirtualFile file) { if (isUnderConfigOrSystem(file)) { return false; } if (file.isDirectory()) { invalidateIndicesForFile(file, markForReindex); if (!isMock(file) && !myManagingFS.wereChildrenAccessed(file)) { return false; } } else { invalidateIndicesForFile(file, markForReindex); } return true; } @Override public Iterable<VirtualFile> getChildrenIterable(@NotNull VirtualFile file) { return file instanceof NewVirtualFile ? ((NewVirtualFile)file).iterInDbChildren() : null; } }); } private void invalidateIndicesForFile(@NotNull final VirtualFile file, boolean markForReindex) { cleanProcessedFlag(file); IndexingStamp.flushCache(file); List<ID<?, ?>> nontrivialFileIndexedStates = IndexingStamp.getNontrivialFileIndexedStates(file); if (!markForReindex) { // markForReindex really means content changed for (ID<?, ?> indexId : nontrivialFileIndexedStates) { if (myNotRequiringContentIndices.contains(indexId)) { try { updateSingleIndex(indexId, file, null); } catch (StorageException e) { LOG.info(e); requestRebuild(indexId); } } } myFilesToUpdate.remove(file); // no need to update it anymore } Collection<ID<?, ?>> fileIndexedStatesToUpdate = ContainerUtil.intersection(nontrivialFileIndexedStates, myRequiringContentIndices); if (markForReindex) { // only mark the file as outdated, reindex will be done lazily if (!fileIndexedStatesToUpdate.isEmpty()) { final List<ID<?, ?>> finalNontrivialFileIndexedStates = nontrivialFileIndexedStates; ApplicationManager.getApplication().runReadAction(new Runnable() { @Override public void run() { //noinspection ForLoopReplaceableByForEach for (int i = 0, size = finalNontrivialFileIndexedStates.size(); i < size; ++i) { final ID<?, ?> indexId = finalNontrivialFileIndexedStates.get(i); if (needsFileContentLoading(indexId) && IndexingStamp.isFileIndexedStateCurrent(file, indexId)) { IndexingStamp.setFileIndexedStateOutdated(file, indexId); } } } }); // the file is for sure not a dir and it was previously indexed by at least one index if (!isTooLarge(file)) scheduleForUpdate(file); } } else if (!fileIndexedStatesToUpdate.isEmpty()) { // file was removed, its data should be (lazily) wiped for every index final Collection<ID<?, ?>> finalFileIndexedStatesToUpdate = fileIndexedStatesToUpdate; myFutureInvalidations.offer(new InvalidationTask(file) { @Override public void run() { removeFileDataFromIndices(finalFileIndexedStatesToUpdate, file); } }); } IndexingStamp.flushCache(file); } private void removeFileDataFromIndices(@NotNull Collection<ID<?, ?>> affectedIndices, @NotNull VirtualFile file) { Throwable unexpectedError = null; for (ID<?, ?> indexId : affectedIndices) { try { updateSingleIndex(indexId, file, null); } catch (StorageException e) { LOG.info(e); requestRebuild(indexId); } catch (ProcessCanceledException pce) { LOG.error(pce); } catch (Throwable e) { LOG.info(e); if (unexpectedError == null) { unexpectedError = e; } } } IndexingStamp.flushCache(file); if (unexpectedError != null) { LOG.error(unexpectedError); } } public int getNumberOfPendingInvalidations() { return myFutureInvalidations.size(); } public void ensureAllInvalidateTasksCompleted() { final int size = getNumberOfPendingInvalidations(); if (size == 0) { return; } // we must avoid PCE interruptions when removing data from indices ProgressManager.getInstance().executeNonCancelableSection( new Runnable() { @Override public void run() { final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); indicator.setText(""); int count = 0; while (true) { InvalidationTask task = myFutureInvalidations.poll(); if (task == null) { break; } indicator.setFraction((double)count++ / size); task.run(); } } } ); } private void iterateIndexableFiles(@NotNull final VirtualFile file, @NotNull final Processor<VirtualFile> processor) { if (file.isDirectory()) { final ContentIterator iterator = new ContentIterator() { @Override public boolean processFile(@NotNull final VirtualFile fileOrDir) { processor.process(fileOrDir); return true; } }; for (IndexableFileSet set : myIndexableSets) { if (set.isInSet(file)) { set.iterateIndexableFilesIn(file, iterator); } } } else { for (IndexableFileSet set : myIndexableSets) { if (set.isInSet(file)) { processor.process(file); break; } } } } public Collection<VirtualFile> getAllFilesToUpdate() { if (myFilesToUpdate.isEmpty()) { return Collections.emptyList(); } return new ArrayList<VirtualFile>(myFilesToUpdate); } private final AtomicReference<UpdateSemaphore> myUpdateSemaphoreRef = new AtomicReference<UpdateSemaphore>(null); @NotNull private UpdateSemaphore obtainForceUpdateSemaphore() { UpdateSemaphore newValue = null; while (true) { final UpdateSemaphore currentValue = myUpdateSemaphoreRef.get(); if (currentValue != null) { return currentValue; } if (newValue == null) { // lazy init newValue = new UpdateSemaphore(); } if (myUpdateSemaphoreRef.compareAndSet(null, newValue)) { return newValue; } } } private void releaseForceUpdateSemaphore(UpdateSemaphore semaphore) { myUpdateSemaphoreRef.compareAndSet(semaphore, null); } private void forceUpdate(@Nullable Project project, @Nullable GlobalSearchScope filter, @Nullable VirtualFile restrictedTo) { myChangedFilesCollector.ensureAllInvalidateTasksCompleted(); ProjectIndexableFilesFilter indexableFilesFilter = projectIndexableFiles(project); UpdateSemaphore updateSemaphore; do { updateSemaphore = obtainForceUpdateSemaphore(); try { for (VirtualFile file : getAllFilesToUpdate()) { if (indexableFilesFilter != null && file instanceof VirtualFileWithId && !indexableFilesFilter.containsFileId( ((VirtualFileWithId)file).getId())) { continue; } if (filter == null || filter.accept(file) || Comparing.equal(file, restrictedTo)) { try { updateSemaphore.down(); // process only files that can affect result processFileImpl(project, new com.intellij.ide.caches.FileContent(file)); } catch (ProcessCanceledException e) { updateSemaphore.reportUpdateCanceled(); throw e; } finally { updateSemaphore.up(); } } } // If several threads entered the method at the same time and there were files to update, // all the threads should leave the method synchronously after all the files scheduled for update are reindexed, // no matter which thread will do reindexing job. // Thus we ensure that all the threads that entered the method will get the most recent data while (!updateSemaphore.waitFor(500)) { // may need to wait until another thread is done with indexing if (Thread.holdsLock(PsiLock.LOCK)) { break; // hack. Most probably that other indexing threads is waiting for PsiLock, which we're are holding. } } } finally { releaseForceUpdateSemaphore(updateSemaphore); } // if some other thread was unable to complete indexing because of PCE, // we should try again and ensure the file is indexed before proceeding further } while (updateSemaphore.isUpdateCanceled()); } private void processFileImpl(Project project, @NotNull final com.intellij.ide.caches.FileContent fileContent) { final VirtualFile file = fileContent.getVirtualFile(); final boolean reallyRemoved = myFilesToUpdate.remove(file); if (reallyRemoved && file.isValid()) { try { if (isTooLarge(file)) { removeFileDataFromIndices(ContainerUtil.intersection(IndexingStamp.getNontrivialFileIndexedStates(file), myRequiringContentIndices), file); } else { doIndexFileContent(project, fileContent); } } finally { IndexingStamp.flushCache(file); } } } @Override public void before(@NotNull List<? extends VFileEvent> events) { myContentlessIndicesUpdateQueue.signalUpdateStart(); myContentlessIndicesUpdateQueue.ensureUpToDate(); for (VFileEvent event : events) { Object requestor = event.getRequestor(); if (requestor instanceof FileDocumentManager || requestor instanceof PsiManager || requestor == LocalHistory.VFS_EVENT_REQUESTOR) { cleanupMemoryStorage(); break; } } for (VFileEvent event : events) { BulkVirtualFileListenerAdapter.fireBefore(this, event); } } @Override public void after(@NotNull List<? extends VFileEvent> events) { myContentlessIndicesUpdateQueue.ensureUpToDate(); for (VFileEvent event : events) { BulkVirtualFileListenerAdapter.fireAfter(this, event); } myContentlessIndicesUpdateQueue.signalUpdateEnd(); } } private class UnindexedFilesFinder implements CollectingContentIterator { private final List<VirtualFile> myFiles = new ArrayList<VirtualFile>(); @Nullable private final ProgressIndicator myProgressIndicator; private UnindexedFilesFinder(@Nullable ProgressIndicator indicator) { myProgressIndicator = indicator; } @NotNull @Override public List<VirtualFile> getFiles() { return myFiles; } @Override public boolean processFile(@NotNull final VirtualFile file) { if (!file.isValid()) { return true; } if (file instanceof VirtualFileSystemEntry && ((VirtualFileSystemEntry)file).isFileIndexed()) { return true; } if (!(file instanceof VirtualFileWithId)) { return true; } try { FileType type = file.getFileType(); FileTypeManagerImpl.cacheFileType(file, type); boolean oldStuff = true; if (file.isDirectory() || !isTooLarge(file)) { final List<ID<?, ?>> affectedIndexCandidates = getAffectedIndexCandidates(file); //noinspection ForLoopReplaceableByForEach for (int i = 0, size = affectedIndexCandidates.size(); i < size; ++i) { final ID<?, ?> indexId = affectedIndexCandidates.get(i); try { if (needsFileContentLoading(indexId) && shouldIndexFile(file, indexId)) { myFiles.add(file); oldStuff = false; break; } } catch (RuntimeException e) { final Throwable cause = e.getCause(); if (cause instanceof IOException || cause instanceof StorageException) { LOG.info(e); requestRebuild(indexId); } else { throw e; } } } } FileContent fileContent = null; for (ID<?, ?> indexId : myNotRequiringContentIndices) { if (shouldIndexFile(file, indexId)) { oldStuff = false; try { if (fileContent == null) { fileContent = new FileContentImpl(file); } updateSingleIndex(indexId, file, fileContent); } catch (StorageException e) { LOG.info(e); requestRebuild(indexId); } } } IndexingStamp.flushCache(file); if (oldStuff && file instanceof VirtualFileSystemEntry) { ((VirtualFileSystemEntry)file).setFileIndexed(true); } } finally { FileTypeManagerImpl.cacheFileType(file, null); } if (myProgressIndicator != null && file.isDirectory()) { // once for dir is cheap enough myProgressIndicator.checkCanceled(); myProgressIndicator.setText("Scanning files to index"); } return true; } } private boolean shouldIndexFile(@NotNull VirtualFile file, @NotNull ID<?, ?> indexId) { return getInputFilter(indexId).acceptInput(file) && (isMock(file) || !isFileIndexed(file, indexId)); } private static boolean isFileIndexed(VirtualFile file, @NotNull ID<?, ?> indexId) { return IndexingStamp.isFileIndexedStateCurrent(file, indexId); } private boolean isUnderConfigOrSystem(@NotNull VirtualFile file) { final String filePath = file.getPath(); return myConfigPath != null && FileUtil.startsWith(filePath, myConfigPath) || myLogPath != null && FileUtil.startsWith(filePath, myLogPath); } private static boolean isMock(final VirtualFile file) { return !(file instanceof NewVirtualFile); } private boolean isTooLarge(@NotNull VirtualFile file) { if (SingleRootFileViewProvider.isTooLargeForIntelligence(file)) { return !myNoLimitCheckTypes.contains(file.getFileType()); } return false; } private boolean isTooLarge(@NotNull VirtualFile file, long contentSize) { if (SingleRootFileViewProvider.isTooLargeForIntelligence(file, contentSize)) { return !myNoLimitCheckTypes.contains(file.getFileType()); } return false; } @NotNull public CollectingContentIterator createContentIterator(@Nullable ProgressIndicator indicator) { return new UnindexedFilesFinder(indicator); } @Override public void registerIndexableSet(@NotNull IndexableFileSet set, @Nullable Project project) { myIndexableSets.add(set); myIndexableSetToProjectMap.put(set, project); if (project != null) { ((PsiManagerImpl)PsiManager.getInstance(project)).addTreeChangePreprocessor(new PsiTreeChangePreprocessor() { @Override public void treeChanged(@NotNull PsiTreeChangeEventImpl event) { if (event.isGenericChange() && event.getCode() == PsiTreeChangeEventImpl.PsiEventType.CHILDREN_CHANGED) { PsiFile file = event.getFile(); if (file != null) { VirtualFile virtualFile = file.getVirtualFile(); Document document = myFileDocumentManager.getDocument(virtualFile); if (document != null && myFileDocumentManager.isDocumentUnsaved(document)) { for(ID<?,?> psiBackedIndex:myPsiDependentIndices) { myUpToDateIndicesForUnsavedOrTransactedDocuments.remove(psiBackedIndex); } } else { // change in persistent file if (virtualFile instanceof VirtualFileWithId) { boolean wasIndexed = false; for (ID<?, ?> psiBackedIndex : myPsiDependentIndices) { if (isFileIndexed(virtualFile, psiBackedIndex)) { IndexingStamp.setFileIndexedStateOutdated(virtualFile, psiBackedIndex); wasIndexed = true; } } if (wasIndexed) { myChangedFilesCollector.scheduleForUpdate(virtualFile); IndexingStamp.flushCache(virtualFile); } } } } } } }); } } @Override public void removeIndexableSet(@NotNull IndexableFileSet set) { if (!myIndexableSetToProjectMap.containsKey(set)) return; myChangedFilesCollector.ensureAllInvalidateTasksCompleted(); IndexingStamp.flushCaches(); myIndexableSets.remove(set); myIndexableSetToProjectMap.remove(set); } @Override public VirtualFile findFileById(Project project, int id) { return IndexInfrastructure.findFileById((PersistentFS) ManagingFS.getInstance(), id); } @Nullable private static PsiFile findLatestKnownPsiForUncomittedDocument(@NotNull Document doc, @NotNull Project project) { return PsiDocumentManager.getInstance(project).getCachedPsiFile(doc); } private static class IndexableFilesFilter implements InputFilter { private final InputFilter myDelegate; private IndexableFilesFilter(InputFilter delegate) { myDelegate = delegate; } @Override public boolean acceptInput(@NotNull final VirtualFile file) { return file instanceof VirtualFileWithId && myDelegate.acceptInput(file); } } private static void cleanupProcessedFlag() { final VirtualFile[] roots = ManagingFS.getInstance().getRoots(); for (VirtualFile root : roots) { cleanProcessedFlag(root); } } private static void cleanProcessedFlag(@NotNull final VirtualFile file) { if (!(file instanceof VirtualFileSystemEntry)) return; final VirtualFileSystemEntry nvf = (VirtualFileSystemEntry)file; if (file.isDirectory()) { nvf.setFileIndexed(false); for (VirtualFile child : nvf.getCachedChildren()) { cleanProcessedFlag(child); } } else { nvf.setFileIndexed(false); } } @Override public void iterateIndexableFiles(@NotNull final ContentIterator processor, @NotNull Project project, ProgressIndicator indicator) { if (project.isDisposed()) { return; } final ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex(); // iterate project content projectFileIndex.iterateContent(processor); if (project.isDisposed()) { return; } Set<VirtualFile> visitedRoots = new THashSet<VirtualFile>(); for (IndexedRootsProvider provider : Extensions.getExtensions(IndexedRootsProvider.EP_NAME)) { //important not to depend on project here, to support per-project background reindex // each client gives a project to FileBasedIndex if (project.isDisposed()) { return; } for (VirtualFile root : IndexableSetContributor.getRootsToIndex(provider)) { if (visitedRoots.add(root)) { iterateRecursively(root, processor, indicator, visitedRoots); } } for (VirtualFile root : IndexableSetContributor.getProjectRootsToIndex(provider, project)) { if (visitedRoots.add(root)) { iterateRecursively(root, processor, indicator, visitedRoots); } } } if (project.isDisposed()) { return; } // iterate associated libraries for (Module module : ModuleManager.getInstance(project).getModules()) { if (module.isDisposed()) { return; } OrderEntry[] orderEntries = ModuleRootManager.getInstance(module).getOrderEntries(); for (OrderEntry orderEntry : orderEntries) { if (orderEntry instanceof LibraryOrSdkOrderEntry) { if (orderEntry.isValid()) { final LibraryOrSdkOrderEntry entry = (LibraryOrSdkOrderEntry)orderEntry; final VirtualFile[] libSources = entry.getRootFiles(OrderRootType.SOURCES); final VirtualFile[] libClasses = entry.getRootFiles(OrderRootType.CLASSES); for (VirtualFile[] roots : new VirtualFile[][]{libSources, libClasses}) { for (VirtualFile root : roots) { if (visitedRoots.add(root)) { iterateRecursively(root, processor, indicator, null); } } } } } } } } private static void iterateRecursively(@Nullable final VirtualFile root, @NotNull final ContentIterator processor, @Nullable final ProgressIndicator indicator, @Nullable final Set<VirtualFile> visitedRoots ) { if (root == null) { return; } VfsUtilCore.visitChildrenRecursively(root, new VirtualFileVisitor() { @Override public boolean visitFile(@NotNull VirtualFile file) { if (visitedRoots != null && root != file && file.isDirectory() && !visitedRoots.add(file)) { return false; // avoid visiting files more than once, e.g. additional indexed roots intersect sometimes } if (indicator != null) indicator.checkCanceled(); processor.processFile(file); return true; } }); } @SuppressWarnings({"WhileLoopSpinsOnField", "SynchronizeOnThis"}) private static class StorageGuard { private int myHolds = 0; private int myWaiters = 0; public interface StorageModeExitHandler { void leave(); } private final StorageModeExitHandler myTrueStorageModeExitHandler = new StorageModeExitHandler() { @Override public void leave() { StorageGuard.this.leave(true); } }; private final StorageModeExitHandler myFalseStorageModeExitHandler = new StorageModeExitHandler() { @Override public void leave() { StorageGuard.this.leave(false); } }; @NotNull private synchronized StorageModeExitHandler enter(boolean mode) { if (mode) { while (myHolds < 0) { doWait(); } myHolds++; return myTrueStorageModeExitHandler; } else { while (myHolds > 0) { doWait(); } myHolds--; return myFalseStorageModeExitHandler; } } private void doWait() { try { ++myWaiters; wait(); } catch (InterruptedException ignored) { } finally { --myWaiters; } } private synchronized void leave(boolean mode) { myHolds += mode ? -1 : 1; if (myHolds == 0 && myWaiters > 0) { notifyAll(); } } } }
less allocations in FileBasedIndexImpl.getUnsavedDocuments
platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java
less allocations in FileBasedIndexImpl.getUnsavedDocuments
Java
apache-2.0
b2997180362d9a1cec5647259eaa7cdca844cb72
0
ened/ExoPlayer,KiminRyu/ExoPlayer,androidx/media,KiminRyu/ExoPlayer,superbderrick/ExoPlayer,saki4510t/ExoPlayer,tntcrowd/ExoPlayer,superbderrick/ExoPlayer,MaTriXy/ExoPlayer,tntcrowd/ExoPlayer,stari4ek/ExoPlayer,kiall/ExoPlayer,androidx/media,androidx/media,kiall/ExoPlayer,ened/ExoPlayer,tntcrowd/ExoPlayer,michalliu/ExoPlayer,saki4510t/ExoPlayer,michalliu/ExoPlayer,google/ExoPlayer,ebr11/ExoPlayer,ened/ExoPlayer,michalliu/ExoPlayer,stari4ek/ExoPlayer,amzn/exoplayer-amazon-port,google/ExoPlayer,ebr11/ExoPlayer,MaTriXy/ExoPlayer,amzn/exoplayer-amazon-port,KiminRyu/ExoPlayer,MaTriXy/ExoPlayer,stari4ek/ExoPlayer,ebr11/ExoPlayer,saki4510t/ExoPlayer,amzn/exoplayer-amazon-port,kiall/ExoPlayer,superbderrick/ExoPlayer,google/ExoPlayer
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2.upstream.cache; import android.os.ConditionVariable; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.util.Assertions; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.NavigableSet; import java.util.Set; import java.util.TreeSet; /** * A {@link Cache} implementation that maintains an in-memory representation. */ public final class SimpleCache implements Cache { private final File cacheDir; private final CacheEvictor evictor; private final HashMap<String, CacheSpan> lockedSpans; private final CachedContentIndex index; private final HashMap<String, ArrayList<Listener>> listeners; private long totalSpace = 0; private CacheException initializationException; /** * Constructs the cache. The cache will delete any unrecognized files from the directory. Hence * the directory cannot be used to store other files. * * @param cacheDir A dedicated cache directory. * @param evictor The evictor to be used. */ public SimpleCache(File cacheDir, CacheEvictor evictor) { this(cacheDir, evictor, null); } /** * Constructs the cache. The cache will delete any unrecognized files from the directory. Hence * the directory cannot be used to store other files. * * @param cacheDir A dedicated cache directory. * @param evictor The evictor to be used. * @param secretKey If not null, cache keys will be stored encrypted on filesystem using AES/CBC. * The key must be 16 bytes long. */ public SimpleCache(File cacheDir, CacheEvictor evictor, byte[] secretKey) { this.cacheDir = cacheDir; this.evictor = evictor; this.lockedSpans = new HashMap<>(); this.index = new CachedContentIndex(cacheDir, secretKey); this.listeners = new HashMap<>(); // Start cache initialization. final ConditionVariable conditionVariable = new ConditionVariable(); new Thread("SimpleCache.initialize()") { @Override public void run() { synchronized (SimpleCache.this) { conditionVariable.open(); try { initialize(); } catch (CacheException e) { initializationException = e; } SimpleCache.this.evictor.onCacheInitialized(); } } }.start(); conditionVariable.block(); } @Override public synchronized NavigableSet<CacheSpan> addListener(String key, Listener listener) { ArrayList<Listener> listenersForKey = listeners.get(key); if (listenersForKey == null) { listenersForKey = new ArrayList<>(); listeners.put(key, listenersForKey); } listenersForKey.add(listener); return getCachedSpans(key); } @Override public synchronized void removeListener(String key, Listener listener) { ArrayList<Listener> listenersForKey = listeners.get(key); if (listenersForKey != null) { listenersForKey.remove(listener); if (listenersForKey.isEmpty()) { listeners.remove(key); } } } @Override public synchronized NavigableSet<CacheSpan> getCachedSpans(String key) { CachedContent cachedContent = index.get(key); return cachedContent == null ? null : new TreeSet<CacheSpan>(cachedContent.getSpans()); } @Override public synchronized Set<String> getKeys() { return new HashSet<>(index.getKeys()); } @Override public synchronized long getCacheSpace() { return totalSpace; } @Override public synchronized SimpleCacheSpan startReadWrite(String key, long position) throws InterruptedException, CacheException { while (true) { SimpleCacheSpan span = startReadWriteNonBlocking(key, position); if (span != null) { return span; } else { // Write case, lock not available. We'll be woken up when a locked span is released (if the // released lock is for the requested key then we'll be able to make progress) or when a // span is added to the cache (if the span is for the requested key and covers the requested // position, then we'll become a read and be able to make progress). wait(); } } } @Override public synchronized SimpleCacheSpan startReadWriteNonBlocking(String key, long position) throws CacheException { if (initializationException != null) { throw initializationException; } SimpleCacheSpan cacheSpan = getSpan(key, position); // Read case. if (cacheSpan.isCached) { // Obtain a new span with updated last access timestamp. SimpleCacheSpan newCacheSpan = index.get(key).touch(cacheSpan); notifySpanTouched(cacheSpan, newCacheSpan); return newCacheSpan; } // Write case, lock available. if (!lockedSpans.containsKey(key)) { lockedSpans.put(key, cacheSpan); return cacheSpan; } // Write case, lock not available. return null; } @Override public synchronized File startFile(String key, long position, long maxLength) throws CacheException { Assertions.checkState(lockedSpans.containsKey(key)); if (!cacheDir.exists()) { // For some reason the cache directory doesn't exist. Make a best effort to create it. removeStaleSpansAndCachedContents(); cacheDir.mkdirs(); } evictor.onStartFile(this, key, position, maxLength); return SimpleCacheSpan.getCacheFile(cacheDir, index.assignIdForKey(key), position, System.currentTimeMillis()); } @Override public synchronized void commitFile(File file) throws CacheException { SimpleCacheSpan span = SimpleCacheSpan.createCacheEntry(file, index); Assertions.checkState(span != null); Assertions.checkState(lockedSpans.containsKey(span.key)); // If the file doesn't exist, don't add it to the in-memory representation. if (!file.exists()) { return; } // If the file has length 0, delete it and don't add it to the in-memory representation. if (file.length() == 0) { file.delete(); return; } // Check if the span conflicts with the set content length Long length = getContentLength(span.key); if (length != C.LENGTH_UNSET) { Assertions.checkState((span.position + span.length) <= length); } addSpan(span); index.store(); notifyAll(); } @Override public synchronized void releaseHoleSpan(CacheSpan holeSpan) { Assertions.checkState(holeSpan == lockedSpans.remove(holeSpan.key)); notifyAll(); } /** * Returns the cache {@link SimpleCacheSpan} corresponding to the provided lookup {@link * SimpleCacheSpan}. * * <p>If the lookup position is contained by an existing entry in the cache, then the returned * {@link SimpleCacheSpan} defines the file in which the data is stored. If the lookup position is * not contained by an existing entry, then the returned {@link SimpleCacheSpan} defines the * maximum extents of the hole in the cache. * * @param key The key of the span being requested. * @param position The position of the span being requested. * @return The corresponding cache {@link SimpleCacheSpan}. */ private SimpleCacheSpan getSpan(String key, long position) throws CacheException { CachedContent cachedContent = index.get(key); if (cachedContent == null) { return SimpleCacheSpan.createOpenHole(key, position); } while (true) { SimpleCacheSpan span = cachedContent.getSpan(position); if (span.isCached && !span.file.exists()) { // The file has been deleted from under us. It's likely that other files will have been // deleted too, so scan the whole in-memory representation. removeStaleSpansAndCachedContents(); continue; } return span; } } /** * Ensures that the cache's in-memory representation has been initialized. */ private void initialize() throws CacheException { if (!cacheDir.exists()) { cacheDir.mkdirs(); return; } index.load(); File[] files = cacheDir.listFiles(); if (files == null) { return; } for (File file : files) { if (file.getName().equals(CachedContentIndex.FILE_NAME)) { continue; } SimpleCacheSpan span = file.length() > 0 ? SimpleCacheSpan.createCacheEntry(file, index) : null; if (span != null) { addSpan(span); } else { file.delete(); } } index.removeEmpty(); index.store(); } /** * Adds a cached span to the in-memory representation. * * @param span The span to be added. */ private void addSpan(SimpleCacheSpan span) { index.add(span.key).addSpan(span); totalSpace += span.length; notifySpanAdded(span); } private void removeSpan(CacheSpan span, boolean removeEmptyCachedContent) throws CacheException { CachedContent cachedContent = index.get(span.key); if (cachedContent == null || !cachedContent.removeSpan(span)) { return; } totalSpace -= span.length; if (removeEmptyCachedContent && cachedContent.isEmpty()) { index.removeEmpty(cachedContent.key); index.store(); } notifySpanRemoved(span); } @Override public synchronized void removeSpan(CacheSpan span) throws CacheException { removeSpan(span, true); } /** * Scans all of the cached spans in the in-memory representation, removing any for which files * no longer exist. */ private void removeStaleSpansAndCachedContents() throws CacheException { LinkedList<CacheSpan> spansToBeRemoved = new LinkedList<>(); for (CachedContent cachedContent : index.getAll()) { for (CacheSpan span : cachedContent.getSpans()) { if (!span.file.exists()) { spansToBeRemoved.add(span); } } } for (CacheSpan span : spansToBeRemoved) { // Remove span but not CachedContent to prevent multiple index.store() calls. removeSpan(span, false); } index.removeEmpty(); index.store(); } private void notifySpanRemoved(CacheSpan span) { ArrayList<Listener> keyListeners = listeners.get(span.key); if (keyListeners != null) { for (int i = keyListeners.size() - 1; i >= 0; i--) { keyListeners.get(i).onSpanRemoved(this, span); } } evictor.onSpanRemoved(this, span); } private void notifySpanAdded(SimpleCacheSpan span) { ArrayList<Listener> keyListeners = listeners.get(span.key); if (keyListeners != null) { for (int i = keyListeners.size() - 1; i >= 0; i--) { keyListeners.get(i).onSpanAdded(this, span); } } evictor.onSpanAdded(this, span); } private void notifySpanTouched(SimpleCacheSpan oldSpan, CacheSpan newSpan) { ArrayList<Listener> keyListeners = listeners.get(oldSpan.key); if (keyListeners != null) { for (int i = keyListeners.size() - 1; i >= 0; i--) { keyListeners.get(i).onSpanTouched(this, oldSpan, newSpan); } } evictor.onSpanTouched(this, oldSpan, newSpan); } @Override public synchronized boolean isCached(String key, long position, long length) { CachedContent cachedContent = index.get(key); return cachedContent != null && cachedContent.getCachedBytes(position, length) >= length; } @Override public synchronized long getCachedBytes(String key, long position, long length) { CachedContent cachedContent = index.get(key); return cachedContent != null ? cachedContent.getCachedBytes(position, length) : -length; } @Override public synchronized void setContentLength(String key, long length) throws CacheException { index.setContentLength(key, length); index.store(); } @Override public synchronized long getContentLength(String key) { return index.getContentLength(key); } }
library/core/src/main/java/com/google/android/exoplayer2/upstream/cache/SimpleCache.java
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2.upstream.cache; import android.os.ConditionVariable; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.util.Assertions; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.NavigableSet; import java.util.Set; import java.util.TreeSet; /** * A {@link Cache} implementation that maintains an in-memory representation. */ public final class SimpleCache implements Cache { private final File cacheDir; private final CacheEvictor evictor; private final HashMap<String, CacheSpan> lockedSpans; private final CachedContentIndex index; private final HashMap<String, ArrayList<Listener>> listeners; private long totalSpace = 0; private CacheException initializationException; /** * Constructs the cache. The cache will delete any unrecognized files from the directory. Hence * the directory cannot be used to store other files. * * @param cacheDir A dedicated cache directory. * @param evictor The evictor to be used. */ public SimpleCache(File cacheDir, CacheEvictor evictor) { this(cacheDir, evictor, null); } /** * Constructs the cache. The cache will delete any unrecognized files from the directory. Hence * the directory cannot be used to store other files. * * @param cacheDir A dedicated cache directory. * @param evictor The evictor to be used. * @param secretKey If not null, cache keys will be stored encrypted on filesystem using AES/CBC. * The key must be 16 bytes long. */ public SimpleCache(File cacheDir, CacheEvictor evictor, byte[] secretKey) { this.cacheDir = cacheDir; this.evictor = evictor; this.lockedSpans = new HashMap<>(); this.index = new CachedContentIndex(cacheDir, secretKey); this.listeners = new HashMap<>(); // Start cache initialization. final ConditionVariable conditionVariable = new ConditionVariable(); new Thread("SimpleCache.initialize()") { @Override public void run() { synchronized (SimpleCache.this) { conditionVariable.open(); try { initialize(); } catch (CacheException e) { initializationException = e; } SimpleCache.this.evictor.onCacheInitialized(); } } }.start(); conditionVariable.block(); } @Override public synchronized NavigableSet<CacheSpan> addListener(String key, Listener listener) { ArrayList<Listener> listenersForKey = listeners.get(key); if (listenersForKey == null) { listenersForKey = new ArrayList<>(); listeners.put(key, listenersForKey); } listenersForKey.add(listener); return getCachedSpans(key); } @Override public synchronized void removeListener(String key, Listener listener) { ArrayList<Listener> listenersForKey = listeners.get(key); if (listenersForKey != null) { listenersForKey.remove(listener); if (listenersForKey.isEmpty()) { listeners.remove(key); } } } @Override public synchronized NavigableSet<CacheSpan> getCachedSpans(String key) { CachedContent cachedContent = index.get(key); return cachedContent == null ? null : new TreeSet<CacheSpan>(cachedContent.getSpans()); } @Override public synchronized Set<String> getKeys() { return new HashSet<>(index.getKeys()); } @Override public synchronized long getCacheSpace() { return totalSpace; } @Override public synchronized SimpleCacheSpan startReadWrite(String key, long position) throws InterruptedException, CacheException { while (true) { SimpleCacheSpan span = startReadWriteNonBlocking(key, position); if (span != null) { return span; } else { // Write case, lock not available. We'll be woken up when a locked span is released (if the // released lock is for the requested key then we'll be able to make progress) or when a // span is added to the cache (if the span is for the requested key and covers the requested // position, then we'll become a read and be able to make progress). wait(); } } } @Override public synchronized SimpleCacheSpan startReadWriteNonBlocking(String key, long position) throws CacheException { if (initializationException != null) { throw initializationException; } SimpleCacheSpan cacheSpan = getSpan(key, position); // Read case. if (cacheSpan.isCached) { // Obtain a new span with updated last access timestamp. SimpleCacheSpan newCacheSpan = index.get(key).touch(cacheSpan); notifySpanTouched(cacheSpan, newCacheSpan); return newCacheSpan; } // Write case, lock available. if (!lockedSpans.containsKey(key)) { lockedSpans.put(key, cacheSpan); return cacheSpan; } // Write case, lock not available. return null; } @Override public synchronized File startFile(String key, long position, long maxLength) throws CacheException { Assertions.checkState(lockedSpans.containsKey(key)); if (!cacheDir.exists()) { // For some reason the cache directory doesn't exist. Make a best effort to create it. removeStaleSpansAndCachedContents(); cacheDir.mkdirs(); } evictor.onStartFile(this, key, position, maxLength); return SimpleCacheSpan.getCacheFile(cacheDir, index.assignIdForKey(key), position, System.currentTimeMillis()); } @Override public synchronized void commitFile(File file) throws CacheException { SimpleCacheSpan span = SimpleCacheSpan.createCacheEntry(file, index); Assertions.checkState(span != null); Assertions.checkState(lockedSpans.containsKey(span.key)); // If the file doesn't exist, don't add it to the in-memory representation. if (!file.exists()) { return; } // If the file has length 0, delete it and don't add it to the in-memory representation. if (file.length() == 0) { file.delete(); return; } // Check if the span conflicts with the set content length Long length = getContentLength(span.key); if (length != C.LENGTH_UNSET) { Assertions.checkState((span.position + span.length) <= length); } addSpan(span); index.store(); notifyAll(); } @Override public synchronized void releaseHoleSpan(CacheSpan holeSpan) { Assertions.checkState(holeSpan == lockedSpans.remove(holeSpan.key)); notifyAll(); } /** * Returns the cache {@link SimpleCacheSpan} corresponding to the provided lookup {@link * SimpleCacheSpan}. * * <p>If the lookup position is contained by an existing entry in the cache, then the returned * {@link SimpleCacheSpan} defines the file in which the data is stored. If the lookup position is * not contained by an existing entry, then the returned {@link SimpleCacheSpan} defines the * maximum extents of the hole in the cache. * * @param key The key of the span being requested. * @param position The position of the span being requested. * @return The corresponding cache {@link SimpleCacheSpan}. */ private SimpleCacheSpan getSpan(String key, long position) throws CacheException { CachedContent cachedContent = index.get(key); if (cachedContent == null) { return SimpleCacheSpan.createOpenHole(key, position); } while (true) { SimpleCacheSpan span = cachedContent.getSpan(position); if (span.isCached && !span.file.exists()) { // The file has been deleted from under us. It's likely that other files will have been // deleted too, so scan the whole in-memory representation. removeStaleSpansAndCachedContents(); continue; } return span; } } /** * Ensures that the cache's in-memory representation has been initialized. */ private void initialize() throws CacheException { if (!cacheDir.exists()) { cacheDir.mkdirs(); return; } index.load(); File[] files = cacheDir.listFiles(); if (files == null) { return; } for (File file : files) { if (file.getName().equals(CachedContentIndex.FILE_NAME)) { continue; } SimpleCacheSpan span = file.length() > 0 ? SimpleCacheSpan.createCacheEntry(file, index) : null; if (span != null) { addSpan(span); } else { file.delete(); } } index.removeEmpty(); index.store(); } /** * Adds a cached span to the in-memory representation. * * @param span The span to be added. */ private void addSpan(SimpleCacheSpan span) { index.add(span.key).addSpan(span); totalSpace += span.length; notifySpanAdded(span); } private void removeSpan(CacheSpan span, boolean removeEmptyCachedContent) throws CacheException { CachedContent cachedContent = index.get(span.key); Assertions.checkState(cachedContent.removeSpan(span)); totalSpace -= span.length; if (removeEmptyCachedContent && cachedContent.isEmpty()) { index.removeEmpty(cachedContent.key); index.store(); } notifySpanRemoved(span); } @Override public synchronized void removeSpan(CacheSpan span) throws CacheException { removeSpan(span, true); } /** * Scans all of the cached spans in the in-memory representation, removing any for which files * no longer exist. */ private void removeStaleSpansAndCachedContents() throws CacheException { LinkedList<CacheSpan> spansToBeRemoved = new LinkedList<>(); for (CachedContent cachedContent : index.getAll()) { for (CacheSpan span : cachedContent.getSpans()) { if (!span.file.exists()) { spansToBeRemoved.add(span); } } } for (CacheSpan span : spansToBeRemoved) { // Remove span but not CachedContent to prevent multiple index.store() calls. removeSpan(span, false); } index.removeEmpty(); index.store(); } private void notifySpanRemoved(CacheSpan span) { ArrayList<Listener> keyListeners = listeners.get(span.key); if (keyListeners != null) { for (int i = keyListeners.size() - 1; i >= 0; i--) { keyListeners.get(i).onSpanRemoved(this, span); } } evictor.onSpanRemoved(this, span); } private void notifySpanAdded(SimpleCacheSpan span) { ArrayList<Listener> keyListeners = listeners.get(span.key); if (keyListeners != null) { for (int i = keyListeners.size() - 1; i >= 0; i--) { keyListeners.get(i).onSpanAdded(this, span); } } evictor.onSpanAdded(this, span); } private void notifySpanTouched(SimpleCacheSpan oldSpan, CacheSpan newSpan) { ArrayList<Listener> keyListeners = listeners.get(oldSpan.key); if (keyListeners != null) { for (int i = keyListeners.size() - 1; i >= 0; i--) { keyListeners.get(i).onSpanTouched(this, oldSpan, newSpan); } } evictor.onSpanTouched(this, oldSpan, newSpan); } @Override public synchronized boolean isCached(String key, long position, long length) { CachedContent cachedContent = index.get(key); return cachedContent != null && cachedContent.getCachedBytes(position, length) >= length; } @Override public synchronized long getCachedBytes(String key, long position, long length) { CachedContent cachedContent = index.get(key); return cachedContent != null ? cachedContent.getCachedBytes(position, length) : -length; } @Override public synchronized void setContentLength(String key, long length) throws CacheException { index.setContentLength(key, length); index.store(); } @Override public synchronized long getContentLength(String key) { return index.getContentLength(key); } }
Make removal of non-existent cache span a no-op ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=155413733
library/core/src/main/java/com/google/android/exoplayer2/upstream/cache/SimpleCache.java
Make removal of non-existent cache span a no-op
Java
apache-2.0
5a1294b66d6406132d44de33705ad99ce550b0d2
0
ernestp/consulo,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,Lekanich/intellij-community,slisson/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,da1z/intellij-community,ibinti/intellij-community,supersven/intellij-community,asedunov/intellij-community,allotria/intellij-community,semonte/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,jexp/idea2,slisson/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,slisson/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,kool79/intellij-community,clumsy/intellij-community,xfournet/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,ernestp/consulo,orekyuu/intellij-community,nicolargo/intellij-community,kool79/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,fnouama/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,fitermay/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,diorcety/intellij-community,jagguli/intellij-community,hurricup/intellij-community,petteyg/intellij-community,robovm/robovm-studio,samthor/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,semonte/intellij-community,ernestp/consulo,dslomov/intellij-community,jagguli/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,joewalnes/idea-community,fitermay/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,hurricup/intellij-community,amith01994/intellij-community,ryano144/intellij-community,consulo/consulo,orekyuu/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,fitermay/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,consulo/consulo,ryano144/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,consulo/consulo,alphafoobar/intellij-community,ernestp/consulo,wreckJ/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,diorcety/intellij-community,supersven/intellij-community,tmpgit/intellij-community,signed/intellij-community,mglukhikh/intellij-community,caot/intellij-community,mglukhikh/intellij-community,consulo/consulo,caot/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,clumsy/intellij-community,apixandru/intellij-community,retomerz/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,supersven/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,fnouama/intellij-community,samthor/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,slisson/intellij-community,kool79/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,consulo/consulo,FHannes/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,hurricup/intellij-community,caot/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,kool79/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,retomerz/intellij-community,dslomov/intellij-community,slisson/intellij-community,amith01994/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,vladmm/intellij-community,supersven/intellij-community,allotria/intellij-community,holmes/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,hurricup/intellij-community,izonder/intellij-community,clumsy/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,Lekanich/intellij-community,caot/intellij-community,kdwink/intellij-community,amith01994/intellij-community,xfournet/intellij-community,robovm/robovm-studio,robovm/robovm-studio,ahb0327/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,caot/intellij-community,supersven/intellij-community,ryano144/intellij-community,signed/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,ibinti/intellij-community,retomerz/intellij-community,joewalnes/idea-community,ryano144/intellij-community,ibinti/intellij-community,kool79/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,joewalnes/idea-community,Lekanich/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,izonder/intellij-community,ernestp/consulo,da1z/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,joewalnes/idea-community,idea4bsd/idea4bsd,da1z/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,adedayo/intellij-community,xfournet/intellij-community,FHannes/intellij-community,robovm/robovm-studio,samthor/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,clumsy/intellij-community,da1z/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,semonte/intellij-community,blademainer/intellij-community,dslomov/intellij-community,da1z/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,kool79/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,signed/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,samthor/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,jagguli/intellij-community,amith01994/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,dslomov/intellij-community,ryano144/intellij-community,da1z/intellij-community,apixandru/intellij-community,joewalnes/idea-community,FHannes/intellij-community,pwoodworth/intellij-community,signed/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,kool79/intellij-community,allotria/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,samthor/intellij-community,supersven/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,diorcety/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,kool79/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,hurricup/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,apixandru/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,asedunov/intellij-community,dslomov/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,suncycheng/intellij-community,allotria/intellij-community,xfournet/intellij-community,hurricup/intellij-community,slisson/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,jexp/idea2,ol-loginov/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,slisson/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,signed/intellij-community,izonder/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,ryano144/intellij-community,diorcety/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,caot/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,ibinti/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,nicolargo/intellij-community,signed/intellij-community,apixandru/intellij-community,joewalnes/idea-community,Distrotech/intellij-community,diorcety/intellij-community,retomerz/intellij-community,xfournet/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,ryano144/intellij-community,supersven/intellij-community,clumsy/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,apixandru/intellij-community,holmes/intellij-community,caot/intellij-community,consulo/consulo,gnuhub/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,samthor/intellij-community,jexp/idea2,kdwink/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,joewalnes/idea-community,adedayo/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,kdwink/intellij-community,izonder/intellij-community,ibinti/intellij-community,amith01994/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,izonder/intellij-community,Distrotech/intellij-community,signed/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,jexp/idea2,semonte/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,da1z/intellij-community,nicolargo/intellij-community,signed/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,joewalnes/idea-community,blademainer/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,vladmm/intellij-community,hurricup/intellij-community,holmes/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,youdonghai/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,diorcety/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,caot/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,caot/intellij-community,jexp/idea2,da1z/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,adedayo/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,caot/intellij-community,samthor/intellij-community,samthor/intellij-community,jexp/idea2,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,jexp/idea2,michaelgallacher/intellij-community,jexp/idea2,asedunov/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,adedayo/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,holmes/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,ernestp/consulo,hurricup/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,ryano144/intellij-community,vladmm/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,slisson/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,diorcety/intellij-community,adedayo/intellij-community,jagguli/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,signed/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,joewalnes/idea-community,SerCeMan/intellij-community
package com.intellij.lang.ant.psi.impl; import com.intellij.extapi.psi.LightPsiFileBase; import com.intellij.lang.StdLanguages; import com.intellij.lang.ant.AntElementRole; import com.intellij.lang.ant.AntSupport; import com.intellij.lang.ant.config.AntConfigurationBase; import com.intellij.lang.ant.config.impl.AntBuildFileImpl; import com.intellij.lang.ant.config.impl.AntClassLoader; import com.intellij.lang.ant.config.impl.AntInstallation; import com.intellij.lang.ant.psi.AntElement; import com.intellij.lang.ant.psi.AntFile; import com.intellij.lang.ant.psi.AntProject; import com.intellij.lang.ant.psi.AntProperty; import com.intellij.lang.ant.psi.introspection.AntAttributeType; import com.intellij.lang.ant.psi.introspection.AntTypeDefinition; import com.intellij.lang.ant.psi.introspection.AntTypeId; import com.intellij.lang.ant.psi.introspection.impl.AntTypeDefinitionImpl; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.FileViewProvider; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiLock; import com.intellij.psi.xml.XmlDocument; import com.intellij.psi.xml.XmlFile; import com.intellij.psi.xml.XmlTag; import org.apache.tools.ant.IntrospectionHelper; import org.apache.tools.ant.Project; import org.apache.tools.ant.Target; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Method; import java.util.*; @SuppressWarnings({"UseOfObsoleteCollectionType"}) public class AntFileImpl extends LightPsiFileBase implements AntFile { private AntProject myProject; private AntElement myPrologElement; private AntElement myEpilogueElement; private PsiElement[] myChildren; private AntClassLoader myClassLoader; private Hashtable myProjectProperties; /** * Map of propeties set outside. */ private Map<String, String> myExternalProperties; /** * Map of class names to task definitions. */ private Map<String, AntTypeDefinition> myTypeDefinitions; private AntTypeDefinition[] myTypeDefinitionArray; private AntTypeDefinition myTargetDefinition; /** * Map of nested elements specially for the project element. * It's updated together with the set of custom definitons. */ private HashMap<AntTypeId, String> myProjectElements; @NonNls private static final String INIT_METHOD_NAME = "init"; @NonNls private static final String GET_TASK_DEFINITIONS_METHOD_NAME = "getTaskDefinitions"; @NonNls private static final String GET_DATA_TYPE_DEFINITIONS_METHOD_NAME = "getDataTypeDefinitions"; @NonNls private static final String GET_PROPERTIES_METHOD_NAME = "getProperties"; public AntFileImpl(final FileViewProvider viewProvider) { super(viewProvider, AntSupport.getLanguage()); } @NotNull public FileType getFileType() { return getViewProvider().getVirtualFile().getFileType(); } public VirtualFile getVirtualFile() { return getSourceElement().getVirtualFile(); } public AntElementRole getRole() { return AntElementRole.NULL_ROLE; } public void setProperty(@NotNull final String name, @NotNull final String value) { synchronized (PsiLock.LOCK) { if (myExternalProperties == null) { myExternalProperties = new HashMap<String, String>(); } myExternalProperties.put(name, value); } } @NotNull public PsiElement[] getChildren() { synchronized (PsiLock.LOCK) { if (myChildren == null) { final AntProject project = getAntProject(); final ArrayList<PsiElement> children = new ArrayList<PsiElement>(3); if (myPrologElement != null) { children.add(myPrologElement); } children.add(project); if (myEpilogueElement != null) { children.add(myEpilogueElement); } myChildren = children.toArray(new PsiElement[children.size()]); } return myChildren; } } public PsiElement getFirstChild() { return getChildren()[0]; } public PsiElement getLastChild() { final PsiElement[] psiElements = getChildren(); return psiElements[psiElements.length - 1]; } public AntFileImpl copyLight(final FileViewProvider viewProvider) { return new AntFileImpl(viewProvider); } @SuppressWarnings({"HardCodedStringLiteral"}) public String toString() { return "AntFile[" + getName() + "]"; } public void clearCaches() { synchronized (PsiLock.LOCK) { myChildren = null; myPrologElement = null; myProject = null; myEpilogueElement = null; myTargetDefinition = null; } } public void subtreeChanged() { clearCaches(); } @NotNull public XmlFile getSourceElement() { return (XmlFile)getViewProvider().getPsi(StdLanguages.XML); } @NotNull public AntClassLoader getClassLoader() { if (myClassLoader == null) { final AntBuildFileImpl buildFile = (AntBuildFileImpl)getSourceElement().getCopyableUserData(XmlFile.ANT_BUILD_FILE); if (buildFile != null) { myClassLoader = buildFile.getClassLoader(); } else { final AntConfigurationBase configuration = AntConfigurationBase.getInstance(getProject()); final AntInstallation antInstallation = configuration != null ? configuration.getProjectDefaultAnt() : null; if (antInstallation != null) { myClassLoader = antInstallation.getClassLoader(); } else { myClassLoader = new AntClassLoader(); } } } return myClassLoader; } @Nullable public AntElement getAntParent() { return null; } public AntFile getAntFile() { return this; } public AntProject getAntProject() { // the following line is necessary only to satisfy the "sync/unsync context" inspection synchronized (PsiLock.LOCK) { if (myProject == null) { final XmlFile baseFile = getSourceElement(); final XmlDocument document = baseFile.getDocument(); assert document != null; final XmlTag tag = document.getRootTag(); if (tag == null) return null; final String fileText = baseFile.getText(); final int projectStart = tag.getTextRange().getStartOffset(); if (projectStart > 0) { myPrologElement = new AntOuterProjectElement(this, 0, fileText.substring(0, projectStart)); } final int projectEnd = tag.getTextRange().getEndOffset(); if (projectEnd < fileText.length()) { myEpilogueElement = new AntOuterProjectElement(this, projectEnd, fileText.substring(projectEnd)); } final AntProjectImpl project = new AntProjectImpl(this, tag, createProjectDefinition()); project.loadPredefinedProperties(myProjectProperties, myExternalProperties); myProject = project; } return myProject; } } @Nullable public AntProperty getProperty(final String name) { return null; } public void setProperty(final String name, final AntProperty element) { throw new RuntimeException("Invoke AntProject.setProperty() instead."); } @NotNull public AntProperty[] getProperties() { return AntProperty.EMPTY_ARRAY; } public AntElement lightFindElementAt(int offset) { synchronized (PsiLock.LOCK) { if (myProject == null) return this; final TextRange projectRange = myProject.getTextRange(); if (offset < projectRange.getStartOffset() || offset >= projectRange.getEndOffset()) return this; final AntElement prolog = myPrologElement; return myProject.lightFindElementAt(offset - ((prolog == null) ? 0 : prolog.getTextLength())); } } @NotNull public AntTypeDefinition[] getBaseTypeDefinitions() { synchronized (PsiLock.LOCK) { final int defCount = myTypeDefinitions.size(); if (myTypeDefinitionArray == null || myTypeDefinitionArray.length != defCount) { getBaseTypeDefinition(null); myTypeDefinitionArray = myTypeDefinitions.values().toArray(new AntTypeDefinition[defCount]); } return myTypeDefinitionArray; } } @Nullable public AntTypeDefinition getBaseTypeDefinition(final String className) { synchronized (PsiLock.LOCK) { if (myTypeDefinitions == null) { myTypeDefinitions = new HashMap<String, AntTypeDefinition>(); myProjectElements = new HashMap<AntTypeId, String>(); final ReflectedProject reflectedProject = new ReflectedProject(getClassLoader()); if (reflectedProject.myProject != null) { // first, create task definitons updateTypeDefinitions(reflectedProject.myTaskDefinitions, true); // second, create definitions of data types updateTypeDefinitions(reflectedProject.myDataTypeDefinitions, false); myProjectProperties = reflectedProject.myProperties; } } return myTypeDefinitions.get(className); } } @NotNull public AntTypeDefinition getTargetDefinition() { getBaseTypeDefinition(null); synchronized (PsiLock.LOCK) { if (myTargetDefinition == null) { @NonNls final HashMap<String, AntAttributeType> targetAttrs = new HashMap<String, AntAttributeType>(); targetAttrs.put("name", AntAttributeType.STRING); targetAttrs.put("depends", AntAttributeType.STRING); targetAttrs.put("if", AntAttributeType.STRING); targetAttrs.put("unless", AntAttributeType.STRING); targetAttrs.put("description", AntAttributeType.STRING); final HashMap<AntTypeId, String> targetElements = new HashMap<AntTypeId, String>(); for (AntTypeDefinition def : getBaseTypeDefinitions()) { if (def.isTask() || targetElements.get(def.getTypeId()) == null) { targetElements.put(def.getTypeId(), def.getClassName()); } } myTargetDefinition = new AntTypeDefinitionImpl(new AntTypeId("target"), Target.class.getName(), false, targetAttrs, targetElements); registerCustomType(myTargetDefinition); } return myTargetDefinition; } } public void registerCustomType(final AntTypeDefinition def) { synchronized (PsiLock.LOCK) { myTypeDefinitionArray = null; final String classname = def.getClassName(); myTypeDefinitions.put(classname, def); myProjectElements.put(def.getTypeId(), classname); if (myTargetDefinition != null && myTargetDefinition != def) { myTargetDefinition = null; } } } public void unregisterCustomType(final AntTypeDefinition def) { synchronized (PsiLock.LOCK) { myTypeDefinitionArray = null; final String classname = def.getClassName(); myTypeDefinitions.remove(classname); myProjectElements.remove(def.getTypeId()); if (myTargetDefinition != null && myTargetDefinition != def) { myTargetDefinition = null; } } } @SuppressWarnings({"HardCodedStringLiteral"}) private void updateTypeDefinitions(final Hashtable ht, final boolean isTask) { if (ht == null) return; final Enumeration types = ht.keys(); while (types.hasMoreElements()) { String typeName = (String)types.nextElement(); /** * Hardcode for <javadoc> task (IDEADEV-6731). */ if (isTask && typeName.equals("javadoc2")) { typeName = "javadoc"; } /** * Hardcode for <unwar> and <unjar> tasks (IDEADEV-6830). */ if (isTask && (typeName.equals("unwar") || typeName.equals("unjar"))) { typeName = "unzip"; } final Class typeClass = (Class)ht.get(typeName); final AntTypeId typeId = new AntTypeId(typeName); final AntTypeDefinition def = createTypeDefinition(typeId, typeClass, isTask); if (def != null) { final String className = def.getClassName(); myTypeDefinitions.put(className, def); myProjectElements.put(typeId, className); /** * some types are defined only as nested elements, project doesn't return their classes * these elements can exist only in context of another element and are defined as subclasses of its class * so we should manually update our type definitions map with such elements */ final IntrospectionHelper helper = getHelperExceptionSafe(typeClass); if (helper != null) { try { final Enumeration nestedEnum = helper.getNestedElements(); while (nestedEnum.hasMoreElements()) { final String nestedElement = (String)nestedEnum.nextElement(); final Class clazz = (Class)helper.getNestedElementMap().get(nestedElement); if (myTypeDefinitions.get(clazz.getName()) == null) { final AntTypeDefinition nestedDef = createTypeDefinition(new AntTypeId(nestedElement), clazz, false); if (nestedDef != null) { myTypeDefinitions.put(nestedDef.getClassName(), nestedDef); } } } } finally { helper.buildFinished(null); } } } } } private AntTypeDefinition createProjectDefinition() { getBaseTypeDefinition(null); @NonNls final HashMap<String, AntAttributeType> projectAttrs = new HashMap<String, AntAttributeType>(); projectAttrs.put("name", AntAttributeType.STRING); projectAttrs.put("default", AntAttributeType.STRING); projectAttrs.put("basedir", AntAttributeType.STRING); final AntTypeDefinition def = getTargetDefinition(); myProjectElements.put(def.getTypeId(), def.getClassName()); return new AntTypeDefinitionImpl(new AntTypeId("project"), Project.class.getName(), false, projectAttrs, myProjectElements); } @Nullable static AntTypeDefinition createTypeDefinition(final AntTypeId id, final Class typeClass, final boolean isTask) { final IntrospectionHelper helper = getHelperExceptionSafe(typeClass); if (helper == null) return null; try { final HashMap<String, AntAttributeType> attributes = new HashMap<String, AntAttributeType>(); final Enumeration attrEnum = helper.getAttributes(); while (attrEnum.hasMoreElements()) { final String attr = (String)attrEnum.nextElement(); final Class attrClass = helper.getAttributeType(attr); if (int.class.equals(attrClass)) { attributes.put(attr, AntAttributeType.INTEGER); } else if (boolean.class.equals(attrClass)) { attributes.put(attr, AntAttributeType.BOOLEAN); } else { attributes.put(attr.toLowerCase(Locale.US), AntAttributeType.STRING); } } final HashMap<AntTypeId, String> nestedDefinitions = new HashMap<AntTypeId, String>(); final Enumeration nestedEnum = helper.getNestedElements(); while (nestedEnum.hasMoreElements()) { final String nestedElement = (String)nestedEnum.nextElement(); final String className = ((Class)helper.getNestedElementMap().get(nestedElement)).getName(); nestedDefinitions.put(new AntTypeId(nestedElement), className); } return new AntTypeDefinitionImpl(id, typeClass.getName(), isTask, attributes, nestedDefinitions); } finally { helper.buildFinished(null); } } @Nullable private static IntrospectionHelper getHelperExceptionSafe(Class c) { try { return IntrospectionHelper.getHelper(c); } catch (Throwable e) { // can't be } return null; } private static final class ReflectedProject { private Object myProject; private Hashtable myTaskDefinitions; private Hashtable myDataTypeDefinitions; private Hashtable myProperties; public ReflectedProject(final AntClassLoader classLoader) { try { final Class projectClass = classLoader.loadClass("org.apache.tools.ant.Project"); myProject = projectClass.newInstance(); Method method = projectClass.getMethod(INIT_METHOD_NAME); method.invoke(myProject); method = getMethod(projectClass, GET_TASK_DEFINITIONS_METHOD_NAME); myTaskDefinitions = (Hashtable)method.invoke(myProject); method = getMethod(projectClass, GET_DATA_TYPE_DEFINITIONS_METHOD_NAME); myDataTypeDefinitions = (Hashtable)method.invoke(myProject); method = getMethod(projectClass, GET_PROPERTIES_METHOD_NAME); myProperties = (Hashtable)method.invoke(myProject); } catch (Exception e) { myProject = null; } } private static Method getMethod(final Class introspectionHelperClass, final String name) throws NoSuchMethodException { final Method method; method = introspectionHelperClass.getMethod(name); if (!method.isAccessible()) { method.setAccessible(true); } return method; } } }
plugins/ant/src/com/intellij/lang/ant/psi/impl/AntFileImpl.java
package com.intellij.lang.ant.psi.impl; import com.intellij.extapi.psi.LightPsiFileBase; import com.intellij.lang.StdLanguages; import com.intellij.lang.ant.AntElementRole; import com.intellij.lang.ant.AntSupport; import com.intellij.lang.ant.config.AntConfigurationBase; import com.intellij.lang.ant.config.impl.AntBuildFileImpl; import com.intellij.lang.ant.config.impl.AntClassLoader; import com.intellij.lang.ant.config.impl.AntInstallation; import com.intellij.lang.ant.psi.AntElement; import com.intellij.lang.ant.psi.AntFile; import com.intellij.lang.ant.psi.AntProject; import com.intellij.lang.ant.psi.AntProperty; import com.intellij.lang.ant.psi.introspection.AntAttributeType; import com.intellij.lang.ant.psi.introspection.AntTypeDefinition; import com.intellij.lang.ant.psi.introspection.AntTypeId; import com.intellij.lang.ant.psi.introspection.impl.AntTypeDefinitionImpl; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.FileViewProvider; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiLock; import com.intellij.psi.xml.XmlDocument; import com.intellij.psi.xml.XmlFile; import com.intellij.psi.xml.XmlTag; import org.apache.tools.ant.IntrospectionHelper; import org.apache.tools.ant.Project; import org.apache.tools.ant.Target; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Method; import java.util.*; @SuppressWarnings({"UseOfObsoleteCollectionType"}) public class AntFileImpl extends LightPsiFileBase implements AntFile { private AntProject myProject; private AntElement myPrologElement; private AntElement myEpilogueElement; private PsiElement[] myChildren; private AntClassLoader myClassLoader; private Hashtable myProjectProperties; /** * Map of propeties set outside. */ private Map<String, String> myExternalProperties; /** * Map of class names to task definitions. */ private Map<String, AntTypeDefinition> myTypeDefinitions; private AntTypeDefinition[] myTypeDefinitionArray; private AntTypeDefinition myTargetDefinition; /** * Map of nested elements specially for the project element. * It's updated together with the set of custom definitons. */ private HashMap<AntTypeId, String> myProjectElements; @NonNls private static final String INIT_METHOD_NAME = "init"; @NonNls private static final String GET_TASK_DEFINITIONS_METHOD_NAME = "getTaskDefinitions"; @NonNls private static final String GET_DATA_TYPE_DEFINITIONS_METHOD_NAME = "getDataTypeDefinitions"; @NonNls private static final String GET_PROPERTIES_METHOD_NAME = "getProperties"; public AntFileImpl(final FileViewProvider viewProvider) { super(viewProvider, AntSupport.getLanguage()); } @NotNull public FileType getFileType() { return getViewProvider().getVirtualFile().getFileType(); } public VirtualFile getVirtualFile() { return getSourceElement().getVirtualFile(); } public AntElementRole getRole() { return AntElementRole.NULL_ROLE; } public void setProperty(@NotNull final String name, @NotNull final String value) { synchronized (PsiLock.LOCK) { if (myExternalProperties == null) { myExternalProperties = new HashMap<String, String>(); } myExternalProperties.put(name, value); } } @NotNull public PsiElement[] getChildren() { synchronized (PsiLock.LOCK) { if (myChildren == null) { final AntProject project = getAntProject(); final ArrayList<PsiElement> children = new ArrayList<PsiElement>(3); if (myPrologElement != null) { children.add(myPrologElement); } children.add(project); if (myEpilogueElement != null) { children.add(myEpilogueElement); } myChildren = children.toArray(new PsiElement[children.size()]); } return myChildren; } } public PsiElement getFirstChild() { return getChildren()[0]; } public PsiElement getLastChild() { final PsiElement[] psiElements = getChildren(); return psiElements[psiElements.length - 1]; } public AntFileImpl copyLight(final FileViewProvider viewProvider) { return new AntFileImpl(viewProvider); } @SuppressWarnings({"HardCodedStringLiteral"}) public String toString() { return "AntFile[" + getName() + "]"; } public void clearCaches() { synchronized (PsiLock.LOCK) { myChildren = null; myPrologElement = null; myProject = null; myEpilogueElement = null; myTargetDefinition = null; } } public void subtreeChanged() { clearCaches(); } @NotNull public XmlFile getSourceElement() { return (XmlFile)getViewProvider().getPsi(StdLanguages.XML); } @NotNull public AntClassLoader getClassLoader() { if (myClassLoader == null) { final AntBuildFileImpl buildFile = (AntBuildFileImpl)getSourceElement().getCopyableUserData(XmlFile.ANT_BUILD_FILE); if (buildFile != null) { myClassLoader = buildFile.getClassLoader(); } else { final AntConfigurationBase configuration = AntConfigurationBase.getInstance(getProject()); final AntInstallation antInstallation = configuration != null ? configuration.getProjectDefaultAnt() : null; if (antInstallation != null) { myClassLoader = antInstallation.getClassLoader(); } else { myClassLoader = new AntClassLoader(); } } } return myClassLoader; } @Nullable public AntElement getAntParent() { return null; } public AntFile getAntFile() { return this; } public AntProject getAntProject() { // the following line is necessary only to satisfy the "sync/unsync context" inspection synchronized (PsiLock.LOCK) { if (myProject == null) { final XmlFile baseFile = getSourceElement(); final XmlDocument document = baseFile.getDocument(); assert document != null; final XmlTag tag = document.getRootTag(); if (tag == null) return null; final String fileText = baseFile.getText(); final int projectStart = tag.getTextRange().getStartOffset(); if (projectStart > 0) { myPrologElement = new AntOuterProjectElement(this, 0, fileText.substring(0, projectStart)); } final int projectEnd = tag.getTextRange().getEndOffset(); if (projectEnd < fileText.length()) { myEpilogueElement = new AntOuterProjectElement(this, projectEnd, fileText.substring(projectEnd)); } final AntProjectImpl project = new AntProjectImpl(this, tag, createProjectDefinition()); project.loadPredefinedProperties(myProjectProperties, myExternalProperties); myProject = project; } return myProject; } } @Nullable public AntProperty getProperty(final String name) { return null; } public void setProperty(final String name, final AntProperty element) { throw new RuntimeException("Invoke AntProject.setProperty() instead."); } @NotNull public AntProperty[] getProperties() { return AntProperty.EMPTY_ARRAY; } public AntElement lightFindElementAt(int offset) { synchronized (PsiLock.LOCK) { if (myProject == null) return this; final TextRange projectRange = myProject.getTextRange(); if (offset < projectRange.getStartOffset() || offset >= projectRange.getEndOffset()) return this; return myProject.lightFindElementAt(offset); } } @NotNull public AntTypeDefinition[] getBaseTypeDefinitions() { synchronized (PsiLock.LOCK) { final int defCount = myTypeDefinitions.size(); if (myTypeDefinitionArray == null || myTypeDefinitionArray.length != defCount) { getBaseTypeDefinition(null); myTypeDefinitionArray = myTypeDefinitions.values().toArray(new AntTypeDefinition[defCount]); } return myTypeDefinitionArray; } } @Nullable public AntTypeDefinition getBaseTypeDefinition(final String className) { synchronized (PsiLock.LOCK) { if (myTypeDefinitions == null) { myTypeDefinitions = new HashMap<String, AntTypeDefinition>(); myProjectElements = new HashMap<AntTypeId, String>(); final ReflectedProject reflectedProject = new ReflectedProject(getClassLoader()); if (reflectedProject.myProject != null) { // first, create task definitons updateTypeDefinitions(reflectedProject.myTaskDefinitions, true); // second, create definitions of data types updateTypeDefinitions(reflectedProject.myDataTypeDefinitions, false); myProjectProperties = reflectedProject.myProperties; } } return myTypeDefinitions.get(className); } } @NotNull public AntTypeDefinition getTargetDefinition() { getBaseTypeDefinition(null); synchronized (PsiLock.LOCK) { if (myTargetDefinition == null) { @NonNls final HashMap<String, AntAttributeType> targetAttrs = new HashMap<String, AntAttributeType>(); targetAttrs.put("name", AntAttributeType.STRING); targetAttrs.put("depends", AntAttributeType.STRING); targetAttrs.put("if", AntAttributeType.STRING); targetAttrs.put("unless", AntAttributeType.STRING); targetAttrs.put("description", AntAttributeType.STRING); final HashMap<AntTypeId, String> targetElements = new HashMap<AntTypeId, String>(); for (AntTypeDefinition def : getBaseTypeDefinitions()) { if (def.isTask() || targetElements.get(def.getTypeId()) == null) { targetElements.put(def.getTypeId(), def.getClassName()); } } myTargetDefinition = new AntTypeDefinitionImpl(new AntTypeId("target"), Target.class.getName(), false, targetAttrs, targetElements); registerCustomType(myTargetDefinition); } return myTargetDefinition; } } public void registerCustomType(final AntTypeDefinition def) { synchronized (PsiLock.LOCK) { myTypeDefinitionArray = null; final String classname = def.getClassName(); myTypeDefinitions.put(classname, def); myProjectElements.put(def.getTypeId(), classname); if (myTargetDefinition != null && myTargetDefinition != def) { myTargetDefinition = null; } } } public void unregisterCustomType(final AntTypeDefinition def) { synchronized (PsiLock.LOCK) { myTypeDefinitionArray = null; final String classname = def.getClassName(); myTypeDefinitions.remove(classname); myProjectElements.remove(def.getTypeId()); if (myTargetDefinition != null && myTargetDefinition != def) { myTargetDefinition = null; } } } @SuppressWarnings({"HardCodedStringLiteral"}) private void updateTypeDefinitions(final Hashtable ht, final boolean isTask) { if (ht == null) return; final Enumeration types = ht.keys(); while (types.hasMoreElements()) { String typeName = (String)types.nextElement(); /** * Hardcode for <javadoc> task (IDEADEV-6731). */ if (isTask && typeName.equals("javadoc2")) { typeName = "javadoc"; } /** * Hardcode for <unwar> and <unjar> tasks (IDEADEV-6830). */ if (isTask && (typeName.equals("unwar") || typeName.equals("unjar"))) { typeName = "unzip"; } final Class typeClass = (Class)ht.get(typeName); final AntTypeId typeId = new AntTypeId(typeName); final AntTypeDefinition def = createTypeDefinition(typeId, typeClass, isTask); if (def != null) { final String className = def.getClassName(); myTypeDefinitions.put(className, def); myProjectElements.put(typeId, className); /** * some types are defined only as nested elements, project doesn't return their classes * these elements can exist only in context of another element and are defined as subclasses of its class * so we should manually update our type definitions map with such elements */ final IntrospectionHelper helper = getHelperExceptionSafe(typeClass); if (helper != null) { try { final Enumeration nestedEnum = helper.getNestedElements(); while (nestedEnum.hasMoreElements()) { final String nestedElement = (String)nestedEnum.nextElement(); final Class clazz = (Class)helper.getNestedElementMap().get(nestedElement); if (myTypeDefinitions.get(clazz.getName()) == null) { final AntTypeDefinition nestedDef = createTypeDefinition(new AntTypeId(nestedElement), clazz, false); if (nestedDef != null) { myTypeDefinitions.put(nestedDef.getClassName(), nestedDef); } } } } finally { helper.buildFinished(null); } } } } } private AntTypeDefinition createProjectDefinition() { getBaseTypeDefinition(null); @NonNls final HashMap<String, AntAttributeType> projectAttrs = new HashMap<String, AntAttributeType>(); projectAttrs.put("name", AntAttributeType.STRING); projectAttrs.put("default", AntAttributeType.STRING); projectAttrs.put("basedir", AntAttributeType.STRING); final AntTypeDefinition def = getTargetDefinition(); myProjectElements.put(def.getTypeId(), def.getClassName()); return new AntTypeDefinitionImpl(new AntTypeId("project"), Project.class.getName(), false, projectAttrs, myProjectElements); } @Nullable static AntTypeDefinition createTypeDefinition(final AntTypeId id, final Class typeClass, final boolean isTask) { final IntrospectionHelper helper = getHelperExceptionSafe(typeClass); if (helper == null) return null; try { final HashMap<String, AntAttributeType> attributes = new HashMap<String, AntAttributeType>(); final Enumeration attrEnum = helper.getAttributes(); while (attrEnum.hasMoreElements()) { final String attr = (String)attrEnum.nextElement(); final Class attrClass = helper.getAttributeType(attr); if (int.class.equals(attrClass)) { attributes.put(attr, AntAttributeType.INTEGER); } else if (boolean.class.equals(attrClass)) { attributes.put(attr, AntAttributeType.BOOLEAN); } else { attributes.put(attr.toLowerCase(Locale.US), AntAttributeType.STRING); } } final HashMap<AntTypeId, String> nestedDefinitions = new HashMap<AntTypeId, String>(); final Enumeration nestedEnum = helper.getNestedElements(); while (nestedEnum.hasMoreElements()) { final String nestedElement = (String)nestedEnum.nextElement(); final String className = ((Class)helper.getNestedElementMap().get(nestedElement)).getName(); nestedDefinitions.put(new AntTypeId(nestedElement), className); } return new AntTypeDefinitionImpl(id, typeClass.getName(), isTask, attributes, nestedDefinitions); } finally { helper.buildFinished(null); } } @Nullable private static IntrospectionHelper getHelperExceptionSafe(Class c) { try { return IntrospectionHelper.getHelper(c); } catch (Throwable e) { // can't be } return null; } private static final class ReflectedProject { private Object myProject; private Hashtable myTaskDefinitions; private Hashtable myDataTypeDefinitions; private Hashtable myProperties; public ReflectedProject(final AntClassLoader classLoader) { try { final Class projectClass = classLoader.loadClass("org.apache.tools.ant.Project"); myProject = projectClass.newInstance(); Method method = projectClass.getMethod(INIT_METHOD_NAME); method.invoke(myProject); method = getMethod(projectClass, GET_TASK_DEFINITIONS_METHOD_NAME); myTaskDefinitions = (Hashtable)method.invoke(myProject); method = getMethod(projectClass, GET_DATA_TYPE_DEFINITIONS_METHOD_NAME); myDataTypeDefinitions = (Hashtable)method.invoke(myProject); method = getMethod(projectClass, GET_PROPERTIES_METHOD_NAME); myProperties = (Hashtable)method.invoke(myProject); } catch (Exception e) { myProject = null; } } private static Method getMethod(final Class introspectionHelperClass, final String name) throws NoSuchMethodException { final Method method; method = introspectionHelperClass.getMethod(name); if (!method.isAccessible()) { method.setAccessible(true); } return method; } } }
fixed lightFindElementAt() which led to incorrect error-highligthing in case of presence of a prolog element
plugins/ant/src/com/intellij/lang/ant/psi/impl/AntFileImpl.java
fixed lightFindElementAt() which led to incorrect error-highligthing in case of presence of a prolog element
Java
apache-2.0
cc1b201505224e000f4a03c6c43b72358a4bde08
0
idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,semonte/intellij-community,apixandru/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,fitermay/intellij-community,ibinti/intellij-community,apixandru/intellij-community,semonte/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,allotria/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,fitermay/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,semonte/intellij-community,ibinti/intellij-community,ibinti/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,allotria/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,clumsy/intellij-community,apixandru/intellij-community,signed/intellij-community,xfournet/intellij-community,retomerz/intellij-community,clumsy/intellij-community,retomerz/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,suncycheng/intellij-community,signed/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,signed/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,signed/intellij-community,xfournet/intellij-community,da1z/intellij-community,youdonghai/intellij-community,semonte/intellij-community,xfournet/intellij-community,retomerz/intellij-community,semonte/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,signed/intellij-community,hurricup/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,da1z/intellij-community,clumsy/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,allotria/intellij-community,ibinti/intellij-community,signed/intellij-community,hurricup/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,signed/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,asedunov/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,allotria/intellij-community,allotria/intellij-community,youdonghai/intellij-community,semonte/intellij-community,da1z/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,apixandru/intellij-community,FHannes/intellij-community,apixandru/intellij-community,fitermay/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,ibinti/intellij-community,ibinti/intellij-community,retomerz/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,signed/intellij-community,hurricup/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,signed/intellij-community,xfournet/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,kdwink/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,clumsy/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,semonte/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,semonte/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,xfournet/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,kdwink/intellij-community,signed/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,clumsy/intellij-community,hurricup/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,fitermay/intellij-community,FHannes/intellij-community,signed/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,da1z/intellij-community,asedunov/intellij-community,clumsy/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,FHannes/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,signed/intellij-community,kdwink/intellij-community,da1z/intellij-community,retomerz/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,kdwink/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,ibinti/intellij-community,kdwink/intellij-community,allotria/intellij-community
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.project; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ex.PathManagerEx; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ex.ProjectManagerEx; import com.intellij.openapi.project.impl.ProjectImpl; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.testFramework.LeakHunter; import com.intellij.testFramework.PlatformTestCase; import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl; public class LoadProjectTest extends PlatformTestCase { @Override protected void setUpProject() throws Exception { String projectPath = PathManagerEx.getTestDataPath() + "/model/model.ipr"; myProject = ProjectManager.getInstance().loadAndOpenProject(projectPath); ((ProjectImpl)getProject()).registerComponentImplementation(FileEditorManager.class, FileEditorManagerImpl.class); } @Override protected void tearDown() throws Exception { myProject = null; super.tearDown(); } public void testLoadProject() throws Exception { VirtualFile src = ProjectRootManager.getInstance(getProject()).getContentSourceRoots()[0]; VirtualFile a = src.findFileByRelativePath("/x/AClass.java"); assertNotNull(a); PsiFile fileA = getPsiManager().findFile(a); assertNotNull(fileA); fileA.navigate(true); Editor editorA = FileEditorManager.getInstance(getProject()).openTextEditor(new OpenFileDescriptor(getProject(), a), true); PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); assertNotNull(editorA); CodeInsightTestFixtureImpl.instantiateAndRun(fileA, editorA, new int[0], false); VirtualFile b = src.findFileByRelativePath("/x/BClass.java"); assertNotNull(b); PsiFile fileB = getPsiManager().findFile(b); assertNotNull(fileB); fileB.navigate(true); Editor editorB = FileEditorManager.getInstance(getProject()).openTextEditor(new OpenFileDescriptor(getProject(), b), true); PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); assertNotNull(editorB); CodeInsightTestFixtureImpl.instantiateAndRun(fileB, editorB, new int[0], false); FileEditor[] allEditors = FileEditorManager.getInstance(getProject()).getAllEditors(); assertEquals(2, allEditors.length); FileEditorManager.getInstance(getProject()).closeFile(a); FileEditorManager.getInstance(getProject()).closeFile(b); ProjectManagerEx.getInstanceEx().closeAndDispose(getProject()); LeakHunter.checkLeak(ApplicationManager.getApplication(), PsiFileImpl.class, psiFile -> psiFile.getViewProvider().getVirtualFile().getFileSystem() instanceof LocalFileSystem && psiFile.getProject() == getProject()); } @Override protected boolean isRunInWriteAction() { return false; } }
java/java-tests/testSrc/com/intellij/project/LoadProjectTest.java
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.project; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ex.PathManagerEx; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ex.ProjectManagerEx; import com.intellij.openapi.project.impl.ProjectImpl; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.testFramework.LeakHunter; import com.intellij.testFramework.PlatformTestCase; import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl; public class LoadProjectTest extends PlatformTestCase { @Override protected void setUpProject() throws Exception { String projectPath = PathManagerEx.getTestDataPath() + "/model/model.ipr"; myProject = ProjectManager.getInstance().loadAndOpenProject(projectPath); ((ProjectImpl)getProject()).registerComponentImplementation(FileEditorManager.class, FileEditorManagerImpl.class); } @Override protected void tearDown() throws Exception { myProject = null; super.tearDown(); } public void testLoadProject() throws Exception { VirtualFile src = ProjectRootManager.getInstance(getProject()).getContentSourceRoots()[0]; VirtualFile a = src.findFileByRelativePath("/x/AClass.java"); assertNotNull(a); PsiFile fileA = getPsiManager().findFile(a); assertNotNull(fileA); fileA.navigate(true); Editor editorA = FileEditorManager.getInstance(getProject()).openTextEditor(new OpenFileDescriptor(getProject(), a), true); PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); assertNotNull(editorA); CodeInsightTestFixtureImpl.instantiateAndRun(fileA, editorA, new int[0], false); VirtualFile b = src.findFileByRelativePath("/x/BClass.java"); assertNotNull(b); PsiFile fileB = getPsiManager().findFile(b); assertNotNull(fileB); fileB.navigate(true); Editor editorB = FileEditorManager.getInstance(getProject()).openTextEditor(new OpenFileDescriptor(getProject(), b), true); PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); assertNotNull(editorB); CodeInsightTestFixtureImpl.instantiateAndRun(fileB, editorB, new int[0], false); FileEditor[] allEditors = FileEditorManager.getInstance(getProject()).getAllEditors(); assertEquals(2, allEditors.length); FileEditorManager.getInstance(getProject()).closeFile(a); FileEditorManager.getInstance(getProject()).closeFile(b); ProjectManagerEx.getInstanceEx().closeAndDispose(getProject()); LeakHunter.checkLeak(ApplicationManager.getApplication(), PsiFileImpl.class, psiFile -> psiFile.getViewProvider().getVirtualFile().getFileSystem() instanceof LocalFileSystem); } @Override protected boolean isRunInWriteAction() { return false; } }
LoadProjectTest: don't fail when a file from another project is found (although it's a valid leak to care about, it causes this unrelated test to blink)
java/java-tests/testSrc/com/intellij/project/LoadProjectTest.java
LoadProjectTest: don't fail when a file from another project is found (although it's a valid leak to care about, it causes this unrelated test to blink)
Java
apache-2.0
89a533902e45f2c182de90edf22f13ce0f75b5c4
0
apixandru/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,hurricup/intellij-community,asedunov/intellij-community,hurricup/intellij-community,ibinti/intellij-community,hurricup/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,semonte/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,allotria/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,ibinti/intellij-community,fitermay/intellij-community,hurricup/intellij-community,FHannes/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,hurricup/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,signed/intellij-community,fitermay/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,FHannes/intellij-community,allotria/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,fitermay/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,signed/intellij-community,semonte/intellij-community,signed/intellij-community,ibinti/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,vvv1559/intellij-community,da1z/intellij-community,fitermay/intellij-community,xfournet/intellij-community,allotria/intellij-community,FHannes/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,signed/intellij-community,ibinti/intellij-community,signed/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,allotria/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,allotria/intellij-community,allotria/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,xfournet/intellij-community,semonte/intellij-community,signed/intellij-community,semonte/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,fitermay/intellij-community,allotria/intellij-community,xfournet/intellij-community,FHannes/intellij-community,apixandru/intellij-community,da1z/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,apixandru/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,da1z/intellij-community,allotria/intellij-community,apixandru/intellij-community,FHannes/intellij-community,fitermay/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,youdonghai/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,apixandru/intellij-community,apixandru/intellij-community,signed/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,signed/intellij-community,FHannes/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,asedunov/intellij-community,fitermay/intellij-community,signed/intellij-community,da1z/intellij-community,xfournet/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,ibinti/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,xfournet/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,semonte/intellij-community,da1z/intellij-community,semonte/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,ibinti/intellij-community,da1z/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,apixandru/intellij-community,xfournet/intellij-community,FHannes/intellij-community
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.refactoring; import com.intellij.ide.fileTemplates.FileTemplate; import com.intellij.ide.fileTemplates.FileTemplateManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.search.ProjectScope; import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesProcessor; import com.intellij.testFramework.PlatformTestUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.SystemProperties; import com.intellij.util.containers.ContainerUtil; import com.jetbrains.python.PythonTestUtil; import com.jetbrains.python.codeInsight.PyCodeInsightSettings; import com.jetbrains.python.fixtures.PyTestCase; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.stubs.PyClassNameIndex; import com.jetbrains.python.psi.stubs.PyFunctionNameIndex; import com.jetbrains.python.psi.stubs.PyVariableNameIndex; import com.jetbrains.python.refactoring.move.PyMoveModuleMembersHelper; import com.jetbrains.python.refactoring.move.PyMoveModuleMembersProcessor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.Collection; import java.util.List; import static com.jetbrains.python.refactoring.move.PyMoveModuleMembersHelper.isMovableModuleMember; /** * @author vlan */ public class PyMoveTest extends PyTestCase { @Override protected void setUp() throws Exception { super.setUp(); SystemProperties.setTestUserName("user1"); } @Override protected void tearDown() throws Exception { SystemProperties.setTestUserName(null); super.tearDown(); } public void testFunction() { doMoveSymbolTest("f", "b.py"); } public void testClass() { doMoveSymbolTest("C", "b.py"); } // PY-11923 public void testTopLevelVariable() { doMoveSymbolTest("Y", "b.py"); } // PY-11923 public void testMovableTopLevelAssignmentDetection() { runWithLanguageLevel(LanguageLevel.PYTHON30, () -> { myFixture.configureByFile("/refactoring/move/" + getTestName(true) + ".py"); assertFalse(isMovableModuleMember(findFirstNamedElement("X1"))); assertFalse(isMovableModuleMember(findFirstNamedElement("X3"))); assertFalse(isMovableModuleMember(findFirstNamedElement("X2"))); assertFalse(isMovableModuleMember(findFirstNamedElement("X4"))); assertFalse(isMovableModuleMember(findFirstNamedElement("X5"))); assertFalse(isMovableModuleMember(findFirstNamedElement("X6"))); assertFalse(isMovableModuleMember(findFirstNamedElement("X7"))); assertTrue(isMovableModuleMember(findFirstNamedElement("X8"))); }); } // PY-15348 public void testCollectMovableModuleMembers() { myFixture.configureByFile("/refactoring/move/" + getTestName(true) + ".py"); final List<PyElement> members = PyMoveModuleMembersHelper.getTopLevelModuleMembers((PyFile)myFixture.getFile()); final List<String> names = ContainerUtil.map(members, element -> element.getName()); assertSameElements(names, "CONST", "C", "outer_func"); } // PY-3929 // PY-4095 public void testImportAs() { doMoveSymbolTest("f", "b.py"); } // PY-3929 public void testQualifiedImport() { doMoveSymbolTest("f", "b.py"); } // PY-4074 public void testNewModule() { doMoveSymbolTest("f", "b.py"); } // PY-4098 public void testPackageImport() { doMoveSymbolTest("f", "b.py"); } // PY-4130 // PY-4131 public void testDocstringTypes() { doMoveSymbolTest("C", "b.py"); } // PY-4182 public void testInnerImports() { doMoveSymbolTest("f", "b.py"); } // PY-5489 public void testImportSlash() { doMoveSymbolTest("function_2", "file2.py"); } // PY-5489 public void testImportFirstWithSlash() { doMoveSymbolTest("function_1", "file2.py"); } // PY-4545 public void testBaseClass() { doMoveSymbolTest("B", "b.py"); } // PY-4379 public void testModule() { doMoveFileTest("p1/p2/m1.py", "p1"); } // PY-5168 public void testModuleToNonPackage() { doMoveFileTest("p1/p2/m1.py", "nonp3"); } // PY-6432, PY-15347 public void testStarImportWithUsages() { doMoveSymbolTest("f", "c.py"); } // PY-6447 public void testFunctionToUsage() { doMoveSymbolTest("f", "b.py"); } // PY-5850 public void testSubModuleUsage() { doMoveSymbolTest("f", "b.py"); } // PY-6465 public void testUsageFromFunction() { doMoveSymbolTest("use_f", "b.py"); } // PY-6571 public void testStarImportUsage() { doMoveSymbolTest("g", "c.py"); } // PY-13870 public void testConditionalImport() { doMoveFileTest("mod2.py", "pkg1"); } // PY-13870 public void testConditionalImportFromPackage() { doMoveFileTest("pkg1/mod2.py", ""); } // PY-14439 public void testConditionalImportFromPackageToPackage() { doMoveFileTest("pkg1", "pkg2"); } // PY-14979 public void testTemplateAttributesExpansionInCreatedDestinationModule() { final FileTemplateManager instance = FileTemplateManager.getInstance(myFixture.getProject()); final FileTemplate template = instance.getInternalTemplate("Python Script"); assertNotNull(template); final String oldTemplateContent = template.getText(); try { template.setText("NAME = '${NAME}'"); doMoveSymbolTest("C", "b.py"); } finally { template.setText(oldTemplateContent); } } // PY-7378 public void testMoveNamespacePackage1() { runWithLanguageLevel(LanguageLevel.PYTHON33, () -> doMoveFileTest("nspkg/nssubpkg", "")); } // PY-7378 public void testMoveNamespacePackage2() { runWithLanguageLevel(LanguageLevel.PYTHON33, () -> doMoveFileTest("nspkg/nssubpkg/a.py", "")); } // PY-7378 public void testMoveNamespacePackage3() { runWithLanguageLevel(LanguageLevel.PYTHON33, () -> doMoveFileTest("nspkg/nssubpkg/a.py", "nspkg")); } // PY-14384 public void testRelativeImportInsideNamespacePackage() { runWithLanguageLevel(LanguageLevel.PYTHON33, () -> doMoveFileTest("nspkg/nssubpkg", "")); } // PY-14384 public void testRelativeImportInsideNormalPackage() { doMoveFileTest("nspkg/nssubpkg", ""); } // PY-14432 public void testRelativeImportsInsideMovedModule() { doMoveFileTest("pkg1/subpkg1", ""); } // PY-14432 public void testRelativeImportSourceWithSpacesInsideMovedModule() { doMoveFileTest("pkg/subpkg1/a.py", ""); } // PY-14595 public void testNamespacePackageUsedInMovedFunction() { runWithLanguageLevel(LanguageLevel.PYTHON33, () -> doMoveSymbolTest("func", "b.py")); } // PY-14599 public void testMoveFunctionFromUnimportableModule() { doMoveSymbolTest("func", "dst.py"); } // PY-14599 public void testMoveUnreferencedFunctionToUnimportableModule() { doMoveSymbolTest("func", "dst-unimportable.py"); } // PY-14599 public void testMoveReferencedFunctionToUnimportableModule() { try { doMoveSymbolTest("func", "dst-unimportable.py"); fail(); } catch (IncorrectOperationException e) { assertEquals("Cannot use module name 'dst-unimportable.py' in imports", e.getMessage()); } } public void testRelativeImportOfNameFromInitPy() { doMoveFileTest("pkg/subpkg2", ""); } // PY-15218 public void testImportForMovedElementWithPreferredQualifiedImportStyle() { final boolean defaultImportStyle = PyCodeInsightSettings.getInstance().PREFER_FROM_IMPORT; try { PyCodeInsightSettings.getInstance().PREFER_FROM_IMPORT = false; doMoveSymbolTest("bar", "b.py"); } finally { PyCodeInsightSettings.getInstance().PREFER_FROM_IMPORT = defaultImportStyle; } } // PY-10553 public void testMoveModuleWithSameNameAsSymbolInside() { doMoveFileTest("Animals/Carnivore.py", "Animals/test"); } // PY-14617 public void testOldStyleRelativeImport() { doMoveFileTest("pkg/a.py", ""); } // PY-14617 public void testRelativeImportsToModulesInSameMovedPackageNotUpdated() { doMoveFileTest("pkg/subpkg", ""); } // PY-14617 public void testUsagesOfUnqualifiedOldStyleRelativeImportsInsideMovedModule() { doMoveFileTest("pkg/m1.py", ""); } // PY-15324 public void testInterdependentSymbols() { doMoveSymbolsTest("b.py", "f", "A"); } // PY-15343 public void testDunderAll() { doMoveSymbolTest("func", "b.py"); } // PY-15343 public void testDunderAllSingleElementTuple() { doMoveSymbolTest("func", "b.py"); } // PY-15343 public void testDunderAllTwoElementsTuple() { doMoveSymbolTest("func", "b.py"); } // PY-15342 public void testGlobalStatementWithSingleName() { doMoveSymbolTest("VAR", "b.py"); } // PY-15342 public void testGlobalStatementWithTwoNames() { doMoveSymbolTest("VAR", "b.py"); } // PY-15342 public void testGlobalStatementOnly() { doMoveSymbolTest("VAR", "b.py"); } // PY-15350 public void testMoveSymbolFromStatementList() { doMoveSymbolsTest("b.py", "func", "C"); } // PY-14811 public void testUsageFromFunctionResolvesToDunderAll() { doMoveSymbolTest("use_foo", "c.py"); } // PY-14811 public void testUsageFromFunctionResolvesToDunderAllWithAlias() { doMoveSymbolTest("use_foo", "c.py"); } private void doMoveFileTest(String fileName, String toDirName) { Project project = myFixture.getProject(); PsiManager manager = PsiManager.getInstance(project); String root = "/refactoring/move/" + getTestName(true); String rootBefore = root + "/before/src"; String rootAfter = root + "/after/src"; VirtualFile dir1 = myFixture.copyDirectoryToProject(rootBefore, ""); PsiDocumentManager.getInstance(project).commitAllDocuments(); VirtualFile virtualFile = dir1.findFileByRelativePath(fileName); assertNotNull(virtualFile); PsiElement file = manager.findFile(virtualFile); if (file == null) { file = manager.findDirectory(virtualFile); } assertNotNull(file); VirtualFile toVirtualDir = dir1.findFileByRelativePath(toDirName); assertNotNull(toVirtualDir); PsiDirectory toDir = manager.findDirectory(toVirtualDir); new MoveFilesOrDirectoriesProcessor(project, new PsiElement[]{file}, toDir, false, false, null, null).run(); VirtualFile dir2 = getVirtualFileByName(PythonTestUtil.getTestDataPath() + rootAfter); try { PlatformTestUtil.assertDirectoriesEqual(dir2, dir1); } catch (IOException e) { throw new RuntimeException(e); } } private void doMoveSymbolsTest(@NotNull String toFileName, String... symbolNames) { String root = "/refactoring/move/" + getTestName(true); String rootBefore = root + "/before/src"; String rootAfter = root + "/after/src"; VirtualFile dir1 = myFixture.copyDirectoryToProject(rootBefore, ""); PsiDocumentManager.getInstance(myFixture.getProject()).commitAllDocuments(); final PsiNamedElement[] symbols = ContainerUtil.map2Array(symbolNames, PsiNamedElement.class, name -> { final PsiNamedElement found = findFirstNamedElement(name); assertNotNull("Symbol '" + name + "' does not exist", found); return found; }); VirtualFile toVirtualFile = dir1.findFileByRelativePath(toFileName); String path = toVirtualFile != null ? toVirtualFile.getPath() : (dir1.getPath() + "/" + toFileName); new PyMoveModuleMembersProcessor(myFixture.getProject(), symbols, path, false).run(); VirtualFile dir2 = getVirtualFileByName(PythonTestUtil.getTestDataPath() + rootAfter); try { PlatformTestUtil.assertDirectoriesEqual(dir2, dir1); } catch (IOException e) { throw new RuntimeException(e); } } private void doMoveSymbolTest(String symbolName, String toFileName) { doMoveSymbolsTest(toFileName, symbolName); } @Nullable private PsiNamedElement findFirstNamedElement(String name) { final Project project = myFixture.getProject(); final Collection<PyClass> classes = PyClassNameIndex.find(name, project, false); if (classes.size() > 0) { return classes.iterator().next(); } final Collection<PyFunction> functions = PyFunctionNameIndex.find(name, project); if (functions.size() > 0) { return functions.iterator().next(); } final Collection<PyTargetExpression> targets = PyVariableNameIndex.find(name, project, ProjectScope.getAllScope(project)); if (targets.size() > 0) { return targets.iterator().next(); } return null; } }
python/testSrc/com/jetbrains/python/refactoring/PyMoveTest.java
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.refactoring; import com.intellij.ide.fileTemplates.FileTemplate; import com.intellij.ide.fileTemplates.FileTemplateManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.search.ProjectScope; import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesProcessor; import com.intellij.testFramework.PlatformTestUtil; import com.intellij.util.Function; import com.intellij.util.IncorrectOperationException; import com.intellij.util.SystemProperties; import com.intellij.util.containers.ContainerUtil; import com.jetbrains.python.PythonTestUtil; import com.jetbrains.python.codeInsight.PyCodeInsightSettings; import com.jetbrains.python.fixtures.PyTestCase; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.stubs.PyClassNameIndex; import com.jetbrains.python.psi.stubs.PyFunctionNameIndex; import com.jetbrains.python.psi.stubs.PyVariableNameIndex; import com.jetbrains.python.refactoring.move.PyMoveModuleMembersHelper; import com.jetbrains.python.refactoring.move.PyMoveModuleMembersProcessor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.Collection; import java.util.List; import static com.jetbrains.python.refactoring.move.PyMoveModuleMembersHelper.isMovableModuleMember; /** * @author vlan */ public class PyMoveTest extends PyTestCase { @Override protected void setUp() throws Exception { super.setUp(); SystemProperties.setTestUserName("user1"); } public void testFunction() { doMoveSymbolTest("f", "b.py"); } public void testClass() { doMoveSymbolTest("C", "b.py"); } // PY-11923 public void testTopLevelVariable() { doMoveSymbolTest("Y", "b.py"); } // PY-11923 public void testMovableTopLevelAssignmentDetection() { runWithLanguageLevel(LanguageLevel.PYTHON30, () -> { myFixture.configureByFile("/refactoring/move/" + getTestName(true) + ".py"); assertFalse(isMovableModuleMember(findFirstNamedElement("X1"))); assertFalse(isMovableModuleMember(findFirstNamedElement("X3"))); assertFalse(isMovableModuleMember(findFirstNamedElement("X2"))); assertFalse(isMovableModuleMember(findFirstNamedElement("X4"))); assertFalse(isMovableModuleMember(findFirstNamedElement("X5"))); assertFalse(isMovableModuleMember(findFirstNamedElement("X6"))); assertFalse(isMovableModuleMember(findFirstNamedElement("X7"))); assertTrue(isMovableModuleMember(findFirstNamedElement("X8"))); }); } // PY-15348 public void testCollectMovableModuleMembers() { myFixture.configureByFile("/refactoring/move/" + getTestName(true) + ".py"); final List<PyElement> members = PyMoveModuleMembersHelper.getTopLevelModuleMembers((PyFile)myFixture.getFile()); final List<String> names = ContainerUtil.map(members, element -> element.getName()); assertSameElements(names, "CONST", "C", "outer_func"); } // PY-3929 // PY-4095 public void testImportAs() { doMoveSymbolTest("f", "b.py"); } // PY-3929 public void testQualifiedImport() { doMoveSymbolTest("f", "b.py"); } // PY-4074 public void testNewModule() { doMoveSymbolTest("f", "b.py"); } // PY-4098 public void testPackageImport() { doMoveSymbolTest("f", "b.py"); } // PY-4130 // PY-4131 public void testDocstringTypes() { doMoveSymbolTest("C", "b.py"); } // PY-4182 public void testInnerImports() { doMoveSymbolTest("f", "b.py"); } // PY-5489 public void testImportSlash() { doMoveSymbolTest("function_2", "file2.py"); } // PY-5489 public void testImportFirstWithSlash() { doMoveSymbolTest("function_1", "file2.py"); } // PY-4545 public void testBaseClass() { doMoveSymbolTest("B", "b.py"); } // PY-4379 public void testModule() { doMoveFileTest("p1/p2/m1.py", "p1"); } // PY-5168 public void testModuleToNonPackage() { doMoveFileTest("p1/p2/m1.py", "nonp3"); } // PY-6432, PY-15347 public void testStarImportWithUsages() { doMoveSymbolTest("f", "c.py"); } // PY-6447 public void testFunctionToUsage() { doMoveSymbolTest("f", "b.py"); } // PY-5850 public void testSubModuleUsage() { doMoveSymbolTest("f", "b.py"); } // PY-6465 public void testUsageFromFunction() { doMoveSymbolTest("use_f", "b.py"); } // PY-6571 public void testStarImportUsage() { doMoveSymbolTest("g", "c.py"); } // PY-13870 public void testConditionalImport() { doMoveFileTest("mod2.py", "pkg1"); } // PY-13870 public void testConditionalImportFromPackage() { doMoveFileTest("pkg1/mod2.py", ""); } // PY-14439 public void testConditionalImportFromPackageToPackage() { doMoveFileTest("pkg1", "pkg2"); } // PY-14979 public void testTemplateAttributesExpansionInCreatedDestinationModule() { final FileTemplateManager instance = FileTemplateManager.getInstance(myFixture.getProject()); final FileTemplate template = instance.getInternalTemplate("Python Script"); assertNotNull(template); final String oldTemplateContent = template.getText(); try { template.setText("NAME = '${NAME}'"); doMoveSymbolTest("C", "b.py"); } finally { template.setText(oldTemplateContent); } } // PY-7378 public void testMoveNamespacePackage1() { runWithLanguageLevel(LanguageLevel.PYTHON33, () -> doMoveFileTest("nspkg/nssubpkg", "")); } // PY-7378 public void testMoveNamespacePackage2() { runWithLanguageLevel(LanguageLevel.PYTHON33, () -> doMoveFileTest("nspkg/nssubpkg/a.py", "")); } // PY-7378 public void testMoveNamespacePackage3() { runWithLanguageLevel(LanguageLevel.PYTHON33, () -> doMoveFileTest("nspkg/nssubpkg/a.py", "nspkg")); } // PY-14384 public void testRelativeImportInsideNamespacePackage() { runWithLanguageLevel(LanguageLevel.PYTHON33, () -> doMoveFileTest("nspkg/nssubpkg", "")); } // PY-14384 public void testRelativeImportInsideNormalPackage() { doMoveFileTest("nspkg/nssubpkg", ""); } // PY-14432 public void testRelativeImportsInsideMovedModule() { doMoveFileTest("pkg1/subpkg1", ""); } // PY-14432 public void testRelativeImportSourceWithSpacesInsideMovedModule() { doMoveFileTest("pkg/subpkg1/a.py", ""); } // PY-14595 public void testNamespacePackageUsedInMovedFunction() { runWithLanguageLevel(LanguageLevel.PYTHON33, () -> doMoveSymbolTest("func", "b.py")); } // PY-14599 public void testMoveFunctionFromUnimportableModule() { doMoveSymbolTest("func", "dst.py"); } // PY-14599 public void testMoveUnreferencedFunctionToUnimportableModule() { doMoveSymbolTest("func", "dst-unimportable.py"); } // PY-14599 public void testMoveReferencedFunctionToUnimportableModule() { try { doMoveSymbolTest("func", "dst-unimportable.py"); fail(); } catch (IncorrectOperationException e) { assertEquals("Cannot use module name 'dst-unimportable.py' in imports", e.getMessage()); } } public void testRelativeImportOfNameFromInitPy() { doMoveFileTest("pkg/subpkg2", ""); } // PY-15218 public void testImportForMovedElementWithPreferredQualifiedImportStyle() { final boolean defaultImportStyle = PyCodeInsightSettings.getInstance().PREFER_FROM_IMPORT; try { PyCodeInsightSettings.getInstance().PREFER_FROM_IMPORT = false; doMoveSymbolTest("bar", "b.py"); } finally { PyCodeInsightSettings.getInstance().PREFER_FROM_IMPORT = defaultImportStyle; } } // PY-10553 public void testMoveModuleWithSameNameAsSymbolInside() { doMoveFileTest("Animals/Carnivore.py", "Animals/test"); } // PY-14617 public void testOldStyleRelativeImport() { doMoveFileTest("pkg/a.py", ""); } // PY-14617 public void testRelativeImportsToModulesInSameMovedPackageNotUpdated() { doMoveFileTest("pkg/subpkg", ""); } // PY-14617 public void testUsagesOfUnqualifiedOldStyleRelativeImportsInsideMovedModule() { doMoveFileTest("pkg/m1.py", ""); } // PY-15324 public void testInterdependentSymbols() { doMoveSymbolsTest("b.py", "f", "A"); } // PY-15343 public void testDunderAll() { doMoveSymbolTest("func", "b.py"); } // PY-15343 public void testDunderAllSingleElementTuple() { doMoveSymbolTest("func", "b.py"); } // PY-15343 public void testDunderAllTwoElementsTuple() { doMoveSymbolTest("func", "b.py"); } // PY-15342 public void testGlobalStatementWithSingleName() { doMoveSymbolTest("VAR", "b.py"); } // PY-15342 public void testGlobalStatementWithTwoNames() { doMoveSymbolTest("VAR", "b.py"); } // PY-15342 public void testGlobalStatementOnly() { doMoveSymbolTest("VAR", "b.py"); } // PY-15350 public void testMoveSymbolFromStatementList() { doMoveSymbolsTest("b.py", "func", "C"); } // PY-14811 public void testUsageFromFunctionResolvesToDunderAll() { doMoveSymbolTest("use_foo", "c.py"); } // PY-14811 public void testUsageFromFunctionResolvesToDunderAllWithAlias() { doMoveSymbolTest("use_foo", "c.py"); } private void doMoveFileTest(String fileName, String toDirName) { Project project = myFixture.getProject(); PsiManager manager = PsiManager.getInstance(project); String root = "/refactoring/move/" + getTestName(true); String rootBefore = root + "/before/src"; String rootAfter = root + "/after/src"; VirtualFile dir1 = myFixture.copyDirectoryToProject(rootBefore, ""); PsiDocumentManager.getInstance(project).commitAllDocuments(); VirtualFile virtualFile = dir1.findFileByRelativePath(fileName); assertNotNull(virtualFile); PsiElement file = manager.findFile(virtualFile); if (file == null) { file = manager.findDirectory(virtualFile); } assertNotNull(file); VirtualFile toVirtualDir = dir1.findFileByRelativePath(toDirName); assertNotNull(toVirtualDir); PsiDirectory toDir = manager.findDirectory(toVirtualDir); new MoveFilesOrDirectoriesProcessor(project, new PsiElement[]{file}, toDir, false, false, null, null).run(); VirtualFile dir2 = getVirtualFileByName(PythonTestUtil.getTestDataPath() + rootAfter); try { PlatformTestUtil.assertDirectoriesEqual(dir2, dir1); } catch (IOException e) { throw new RuntimeException(e); } } private void doMoveSymbolsTest(@NotNull String toFileName, String... symbolNames) { String root = "/refactoring/move/" + getTestName(true); String rootBefore = root + "/before/src"; String rootAfter = root + "/after/src"; VirtualFile dir1 = myFixture.copyDirectoryToProject(rootBefore, ""); PsiDocumentManager.getInstance(myFixture.getProject()).commitAllDocuments(); final PsiNamedElement[] symbols = ContainerUtil.map2Array(symbolNames, PsiNamedElement.class, name -> { final PsiNamedElement found = findFirstNamedElement(name); assertNotNull("Symbol '" + name + "' does not exist", found); return found; }); VirtualFile toVirtualFile = dir1.findFileByRelativePath(toFileName); String path = toVirtualFile != null ? toVirtualFile.getPath() : (dir1.getPath() + "/" + toFileName); new PyMoveModuleMembersProcessor(myFixture.getProject(), symbols, path, false).run(); VirtualFile dir2 = getVirtualFileByName(PythonTestUtil.getTestDataPath() + rootAfter); try { PlatformTestUtil.assertDirectoriesEqual(dir2, dir1); } catch (IOException e) { throw new RuntimeException(e); } } private void doMoveSymbolTest(String symbolName, String toFileName) { doMoveSymbolsTest(toFileName, symbolName); } @Nullable private PsiNamedElement findFirstNamedElement(String name) { final Project project = myFixture.getProject(); final Collection<PyClass> classes = PyClassNameIndex.find(name, project, false); if (classes.size() > 0) { return classes.iterator().next(); } final Collection<PyFunction> functions = PyFunctionNameIndex.find(name, project); if (functions.size() > 0) { return functions.iterator().next(); } final Collection<PyTargetExpression> targets = PyVariableNameIndex.find(name, project, ProjectScope.getAllScope(project)); if (targets.size() > 0) { return targets.iterator().next(); } return null; } }
[tests] correct state restore in PyMoveTest
python/testSrc/com/jetbrains/python/refactoring/PyMoveTest.java
[tests] correct state restore in PyMoveTest
Java
apache-2.0
a2a9ed2990f9f76253bfdcb728efd517c69ecea3
0
Distrotech/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,izonder/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,jagguli/intellij-community,kool79/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,apixandru/intellij-community,izonder/intellij-community,da1z/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,retomerz/intellij-community,fitermay/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,jagguli/intellij-community,retomerz/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,blademainer/intellij-community,vladmm/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,kool79/intellij-community,slisson/intellij-community,dslomov/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,dslomov/intellij-community,signed/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,samthor/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,vvv1559/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,adedayo/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,ryano144/intellij-community,slisson/intellij-community,tmpgit/intellij-community,caot/intellij-community,allotria/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,supersven/intellij-community,samthor/intellij-community,fnouama/intellij-community,amith01994/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,izonder/intellij-community,ibinti/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,xfournet/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,vladmm/intellij-community,samthor/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,fitermay/intellij-community,caot/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,samthor/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,holmes/intellij-community,caot/intellij-community,clumsy/intellij-community,dslomov/intellij-community,samthor/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,ibinti/intellij-community,kdwink/intellij-community,caot/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,slisson/intellij-community,adedayo/intellij-community,fitermay/intellij-community,da1z/intellij-community,Distrotech/intellij-community,signed/intellij-community,clumsy/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,ibinti/intellij-community,blademainer/intellij-community,fnouama/intellij-community,hurricup/intellij-community,amith01994/intellij-community,fnouama/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,xfournet/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,fitermay/intellij-community,slisson/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,holmes/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,caot/intellij-community,samthor/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,ibinti/intellij-community,blademainer/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,adedayo/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,signed/intellij-community,allotria/intellij-community,signed/intellij-community,allotria/intellij-community,apixandru/intellij-community,FHannes/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,holmes/intellij-community,retomerz/intellij-community,caot/intellij-community,kdwink/intellij-community,hurricup/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,holmes/intellij-community,FHannes/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,caot/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,hurricup/intellij-community,apixandru/intellij-community,vladmm/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,signed/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,da1z/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,amith01994/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,kool79/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,xfournet/intellij-community,semonte/intellij-community,da1z/intellij-community,apixandru/intellij-community,vladmm/intellij-community,kdwink/intellij-community,xfournet/intellij-community,caot/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,holmes/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,robovm/robovm-studio,hurricup/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,fitermay/intellij-community,allotria/intellij-community,xfournet/intellij-community,clumsy/intellij-community,ibinti/intellij-community,semonte/intellij-community,fitermay/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,signed/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,vladmm/intellij-community,apixandru/intellij-community,apixandru/intellij-community,adedayo/intellij-community,fnouama/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,samthor/intellij-community,blademainer/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,signed/intellij-community,nicolargo/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,xfournet/intellij-community,dslomov/intellij-community,izonder/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,signed/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,blademainer/intellij-community,ibinti/intellij-community,blademainer/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,semonte/intellij-community,tmpgit/intellij-community,da1z/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,kool79/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,caot/intellij-community,signed/intellij-community,youdonghai/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,dslomov/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,supersven/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,caot/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,izonder/intellij-community,FHannes/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,izonder/intellij-community,nicolargo/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,samthor/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,caot/intellij-community,hurricup/intellij-community,ibinti/intellij-community,caot/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,amith01994/intellij-community,kool79/intellij-community,supersven/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,semonte/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,da1z/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,signed/intellij-community,da1z/intellij-community,amith01994/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,dslomov/intellij-community,asedunov/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,izonder/intellij-community,semonte/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,amith01994/intellij-community,supersven/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community
/* * Copyright 2000-2010 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.execution.testframework.export; import com.intellij.execution.ExecutionBundle; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.execution.filters.*; import com.intellij.execution.filters.Filter; import com.intellij.execution.impl.RunManagerImpl; import com.intellij.execution.impl.RunnerAndConfigurationSettingsImpl; import com.intellij.execution.testframework.*; import com.intellij.execution.ui.ConsoleViewContentType; import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.UserDataHolder; import com.intellij.openapi.util.WriteExternalException; import com.intellij.openapi.util.text.StringUtil; import org.jdom.Attribute; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; import java.text.SimpleDateFormat; import java.util.*; public class TestResultsXmlFormatter { private static final String ELEM_RUN = "testrun"; public static final String ELEM_TEST = "test"; public static final String ELEM_SUITE = "suite"; public static final String ATTR_NAME = "name"; public static final String ATTR_DURATION = "duration"; public static final String ATTR_LOCATION = "locationUrl"; public static final String ELEM_COUNT = "count"; public static final String ATTR_VALUE = "value"; public static final String ELEM_OUTPUT = "output"; public static final String ATTR_OUTPUT_TYPE = "type"; public static final String ATTR_STATUS = "status"; public static final String TOTAL_STATUS = "total"; private static final String ATTR_FOORTER_TEXT = "footerText"; public static final String ATTR_CONFIG = "isConfig"; public static final String STATUS_PASSED = "passed"; public static final String STATUS_FAILED = "failed"; public static final String STATUS_ERROR = "error"; public static final String STATUS_IGNORED = "ignored"; public static final String STATUS_SKIPPED = "skipped"; public static final String ROOT_ELEM = "root"; private final RunConfiguration myRuntimeConfiguration; private final ContentHandler myResultHandler; private final AbstractTestProxy myTestRoot; private final boolean myHidePassedConfig; public static void execute(AbstractTestProxy root, RunConfiguration runtimeConfiguration, TestConsoleProperties properties, ContentHandler resultHandler) throws SAXException { new TestResultsXmlFormatter(root, runtimeConfiguration, properties, resultHandler).execute(); } private TestResultsXmlFormatter(AbstractTestProxy root, RunConfiguration runtimeConfiguration, TestConsoleProperties properties, ContentHandler resultHandler) { myRuntimeConfiguration = runtimeConfiguration; myTestRoot = root; myResultHandler = resultHandler; myHidePassedConfig = TestConsoleProperties.HIDE_SUCCESSFUL_CONFIG.value(properties); } private void execute() throws SAXException { myResultHandler.startDocument(); TreeMap<String, Integer> counts = new TreeMap<String, Integer>(new Comparator<String>() { @Override public int compare(String o1, String o2) { if (TOTAL_STATUS.equals(o1) && !TOTAL_STATUS.equals(o2)) return -1; if (TOTAL_STATUS.equals(o2) && !TOTAL_STATUS.equals(o1)) return 1; return o1.compareTo(o2); } }); for (AbstractTestProxy node : myTestRoot.getAllTests()) { if (!node.isLeaf()) continue; String status = getStatusString(node); increment(counts, status); increment(counts, TOTAL_STATUS); } Map<String, String> runAttrs = new HashMap<String, String>(); runAttrs.put(ATTR_NAME, myRuntimeConfiguration.getName()); String footerText = ExecutionBundle.message("export.test.results.footer", ApplicationNamesInfo.getInstance().getFullProductName(), new SimpleDateFormat().format(new Date())); runAttrs.put(ATTR_FOORTER_TEXT, footerText); Long duration = myTestRoot.getDuration(); if (duration != null) { runAttrs.put(ATTR_DURATION, String.valueOf(duration)); } startElement(ELEM_RUN, runAttrs); for (Map.Entry<String, Integer> entry : counts.entrySet()) { Map<String, String> a = new HashMap<String, String>(); a.put(ATTR_NAME, entry.getKey()); a.put(ATTR_VALUE, String.valueOf(entry.getValue())); startElement(ELEM_COUNT, a); endElement(ELEM_COUNT); } final Element config = new Element("config"); try { myRuntimeConfiguration.writeExternal(config); config.setAttribute("configId", myRuntimeConfiguration.getType().getId()); config.setAttribute("name", myRuntimeConfiguration.getName()); } catch (WriteExternalException ignore) {} processJDomElement(config); CompositeFilter f = new CompositeFilter(myRuntimeConfiguration.getProject()); for (ConsoleFilterProvider eachProvider : Extensions.getExtensions(ConsoleFilterProvider.FILTER_PROVIDERS)) { Filter[] filters = eachProvider.getDefaultFilters(myRuntimeConfiguration.getProject()); for (Filter filter : filters) { f.addFilter(filter); } } if (myTestRoot instanceof TestProxyRoot) { final String presentation = ((TestProxyRoot)myTestRoot).getPresentation(); if (presentation != null) { final LinkedHashMap<String, String> rootAttrs = new LinkedHashMap<String, String>(); rootAttrs.put("name", presentation); final String comment = ((TestProxyRoot)myTestRoot).getComment(); if (comment != null) { rootAttrs.put("comment", comment); } final String rootLocation = ((TestProxyRoot)myTestRoot).getRootLocation(); if (rootLocation != null) { rootAttrs.put("location", rootLocation); } startElement(ROOT_ELEM, rootAttrs); endElement(ROOT_ELEM); } } if (myTestRoot.shouldSkipRootNodeForExport()) { for (AbstractTestProxy node : myTestRoot.getChildren()) { processNode(node, f); } } else { processNode(myTestRoot, f); } endElement(ELEM_RUN); myResultHandler.endDocument(); } private void processJDomElement(Element config) throws SAXException { final String name = config.getName(); final LinkedHashMap<String, String> attributes = new LinkedHashMap<String, String>(); for (Attribute attribute : config.getAttributes()) { attributes.put(attribute.getName(), attribute.getValue()); } startElement(name, attributes); for (Element child : config.getChildren()) { processJDomElement(child); } endElement(name); } private static void increment(Map<String, Integer> counts, String status) { Integer count = counts.get(status); counts.put(status, count != null ? count + 1 : 1); } private void processNode(AbstractTestProxy node, final Filter filter) throws SAXException { ProgressManager.checkCanceled(); Map<String, String> attrs = new HashMap<String, String>(); attrs.put(ATTR_NAME, node.getName()); attrs.put(ATTR_STATUS, getStatusString(node)); Long duration = node.getDuration(); if (duration != null) { attrs.put(ATTR_DURATION, String.valueOf(duration)); } String locationUrl = node.getLocationUrl(); if (locationUrl != null) { attrs.put(ATTR_LOCATION, locationUrl); } if (node.isConfig()) { attrs.put(ATTR_CONFIG, "true"); } boolean started = false; String elemName = node.isLeaf() ? ELEM_TEST : ELEM_SUITE; if (node.isLeaf()) { started = true; startElement(elemName, attrs); final StringBuilder buffer = new StringBuilder(); final Ref<ConsoleViewContentType> lastType = new Ref<ConsoleViewContentType>(); final Ref<SAXException> error = new Ref<SAXException>(); node.printOn(new Printer() { @Override public void print(String text, ConsoleViewContentType contentType) { if (contentType != lastType.get()) { if (buffer.length() > 0) { try { writeOutput(lastType.get(), buffer, filter); } catch (SAXException e) { error.set(e); } } lastType.set(contentType); } buffer.append(text); } @Override public void onNewAvailable(@NotNull Printable printable) { } @Override public void printHyperlink(String text, HyperlinkInfo info) { } @Override public void mark() { } }); if (!error.isNull()) { throw error.get(); } if (buffer.length() > 0) { writeOutput(lastType.get(), buffer, filter); } } else { for (AbstractTestProxy child : node.getChildren()) { if (myHidePassedConfig && child.isConfig() && child.isPassed()) { //ignore configurations during export continue; } if (!started) { started = true; startElement(elemName, attrs); } processNode(child, filter); } } if (started) { endElement(elemName); } } private void writeOutput(ConsoleViewContentType type, StringBuilder text, Filter filter) throws SAXException { StringBuilder output = new StringBuilder(); StringTokenizer t = new StringTokenizer(text.toString(), "\n"); while (t.hasMoreTokens()) { String line = StringUtil.escapeXml(t.nextToken()) + "\n"; Filter.Result result = null;//filter.applyFilter(line, line.length()); if (result != null && result.hyperlinkInfo instanceof OpenFileHyperlinkInfo) { output.append(line.substring(0, result.highlightStartOffset)); OpenFileDescriptor descriptor = ((OpenFileHyperlinkInfo)result.hyperlinkInfo).getDescriptor(); output.append("<a href=\"javascript://\" onclick=\"Activator.doOpen('file?file="); output.append(descriptor.getFile().getPresentableUrl()); output.append("&line="); output.append(descriptor.getLine()); output.append("')\">"); output.append(line.substring(result.highlightStartOffset, result.highlightEndOffset)); output.append("</a>"); output.append(line.substring(result.highlightEndOffset)); } else { output.append(line); } } Map<String, String> a = new HashMap<String, String>(); a.put(ATTR_OUTPUT_TYPE, getTypeString(type)); startElement(ELEM_OUTPUT, a); writeText(output.toString()); text.delete(0, text.length()); endElement(ELEM_OUTPUT); } private static String getTypeString(ConsoleViewContentType type) { return type == ConsoleViewContentType.ERROR_OUTPUT ? "stderr" : "stdout"; } private static String getStatusString(AbstractTestProxy node) { int magnitude = node.getMagnitude(); // TODO enumeration! switch (magnitude) { case 0: return STATUS_SKIPPED; case 2: case 4: return STATUS_SKIPPED; case 5: return STATUS_IGNORED; case 1: return STATUS_PASSED; case 6: return STATUS_FAILED; case 8: return STATUS_ERROR; default: return node.isPassed() ? STATUS_PASSED : STATUS_FAILED; } } private void startElement(String name, Map<String, String> attributes) throws SAXException { AttributesImpl attrs = new AttributesImpl(); for (Map.Entry<String, String> entry : attributes.entrySet()) { attrs.addAttribute("", entry.getKey(), entry.getKey(), "CDATA", entry.getValue()); } myResultHandler.startElement("", name, name, attrs); } private void endElement(String name) throws SAXException { myResultHandler.endElement("", name, name); } private void writeText(String text) throws SAXException { final char[] chars = text.toCharArray(); myResultHandler.characters(chars, 0, chars.length); } }
platform/testRunner/src/com/intellij/execution/testframework/export/TestResultsXmlFormatter.java
/* * Copyright 2000-2010 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.execution.testframework.export; import com.intellij.execution.ExecutionBundle; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.execution.filters.*; import com.intellij.execution.filters.Filter; import com.intellij.execution.impl.RunManagerImpl; import com.intellij.execution.impl.RunnerAndConfigurationSettingsImpl; import com.intellij.execution.testframework.*; import com.intellij.execution.ui.ConsoleViewContentType; import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.UserDataHolder; import com.intellij.openapi.util.WriteExternalException; import com.intellij.openapi.util.text.StringUtil; import org.jdom.Attribute; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; import java.text.SimpleDateFormat; import java.util.*; public class TestResultsXmlFormatter { private static final String ELEM_RUN = "testrun"; public static final String ELEM_TEST = "test"; public static final String ELEM_SUITE = "suite"; public static final String ATTR_NAME = "name"; public static final String ATTR_DURATION = "duration"; public static final String ATTR_LOCATION = "locationUrl"; public static final String ELEM_COUNT = "count"; public static final String ATTR_VALUE = "value"; public static final String ELEM_OUTPUT = "output"; public static final String ATTR_OUTPUT_TYPE = "type"; public static final String ATTR_STATUS = "status"; public static final String TOTAL_STATUS = "total"; private static final String ATTR_FOORTER_TEXT = "footerText"; public static final String ATTR_CONFIG = "isConfig"; public static final String STATUS_PASSED = "passed"; public static final String STATUS_FAILED = "failed"; public static final String STATUS_ERROR = "error"; public static final String STATUS_IGNORED = "ignored"; public static final String STATUS_SKIPPED = "skipped"; public static final String ROOT_ELEM = "root"; private final RunConfiguration myRuntimeConfiguration; private final ContentHandler myResultHandler; private final AbstractTestProxy myTestRoot; private final boolean myHidePassedConfig; public static void execute(AbstractTestProxy root, RunConfiguration runtimeConfiguration, TestConsoleProperties properties, ContentHandler resultHandler) throws SAXException { new TestResultsXmlFormatter(root, runtimeConfiguration, properties, resultHandler).execute(); } private TestResultsXmlFormatter(AbstractTestProxy root, RunConfiguration runtimeConfiguration, TestConsoleProperties properties, ContentHandler resultHandler) { myRuntimeConfiguration = runtimeConfiguration; myTestRoot = root; myResultHandler = resultHandler; myHidePassedConfig = TestConsoleProperties.HIDE_SUCCESSFUL_CONFIG.value(properties); } private void execute() throws SAXException { myResultHandler.startDocument(); TreeMap<String, Integer> counts = new TreeMap<String, Integer>(new Comparator<String>() { @Override public int compare(String o1, String o2) { if (TOTAL_STATUS.equals(o1) && !TOTAL_STATUS.equals(o2)) return -1; if (TOTAL_STATUS.equals(o2) && !TOTAL_STATUS.equals(o1)) return 1; return o1.compareTo(o2); } }); for (AbstractTestProxy node : myTestRoot.getAllTests()) { if (!node.isLeaf()) continue; String status = getStatusString(node); increment(counts, status); increment(counts, TOTAL_STATUS); } Map<String, String> runAttrs = new HashMap<String, String>(); runAttrs.put(ATTR_NAME, myRuntimeConfiguration.getName()); String footerText = ExecutionBundle.message("export.test.results.footer", ApplicationNamesInfo.getInstance().getFullProductName(), new SimpleDateFormat().format(new Date())); runAttrs.put(ATTR_FOORTER_TEXT, footerText); Long duration = myTestRoot.getDuration(); if (duration != null) { runAttrs.put(ATTR_DURATION, String.valueOf(duration)); } startElement(ELEM_RUN, runAttrs); for (Map.Entry<String, Integer> entry : counts.entrySet()) { Map<String, String> a = new HashMap<String, String>(); a.put(ATTR_NAME, entry.getKey()); a.put(ATTR_VALUE, String.valueOf(entry.getValue())); startElement(ELEM_COUNT, a); endElement(ELEM_COUNT); } final Element config = new Element("config"); try { myRuntimeConfiguration.writeExternal(config); config.setAttribute("configId", myRuntimeConfiguration.getType().getId()); config.setAttribute("name", myRuntimeConfiguration.getName()); } catch (WriteExternalException ignore) {} processJDomElement(config); CompositeFilter f = new CompositeFilter(myRuntimeConfiguration.getProject()); for (ConsoleFilterProvider eachProvider : Extensions.getExtensions(ConsoleFilterProvider.FILTER_PROVIDERS)) { Filter[] filters = eachProvider.getDefaultFilters(myRuntimeConfiguration.getProject()); for (Filter filter : filters) { f.addFilter(filter); } } if (myTestRoot instanceof TestProxyRoot) { final String presentation = ((TestProxyRoot)myTestRoot).getPresentation(); if (presentation != null) { final LinkedHashMap<String, String> rootAttrs = new LinkedHashMap<String, String>(); rootAttrs.put("name", presentation); final String comment = ((TestProxyRoot)myTestRoot).getComment(); if (comment != null) { rootAttrs.put("comment", comment); } final String rootLocation = ((TestProxyRoot)myTestRoot).getRootLocation(); if (rootLocation != null) { rootAttrs.put("location", rootLocation); } startElement(ROOT_ELEM, rootAttrs); endElement(ROOT_ELEM); } } if (myTestRoot.shouldSkipRootNodeForExport()) { for (AbstractTestProxy node : myTestRoot.getChildren()) { processNode(node, f); } } else { processNode(myTestRoot, f); } endElement(ELEM_RUN); myResultHandler.endDocument(); } private void processJDomElement(Element config) throws SAXException { final String name = config.getName(); final LinkedHashMap<String, String> attributes = new LinkedHashMap<String, String>(); for (Attribute attribute : config.getAttributes()) { attributes.put(attribute.getName(), attribute.getValue()); } startElement(name, attributes); for (Element child : config.getChildren()) { processJDomElement(child); } endElement(name); } private static void increment(Map<String, Integer> counts, String status) { Integer count = counts.get(status); counts.put(status, count != null ? count + 1 : 1); } private void processNode(AbstractTestProxy node, final Filter filter) throws SAXException { ProgressManager.checkCanceled(); Map<String, String> attrs = new HashMap<String, String>(); attrs.put(ATTR_NAME, node.getName()); attrs.put(ATTR_STATUS, getStatusString(node)); Long duration = node.getDuration(); if (duration != null) { attrs.put(ATTR_DURATION, String.valueOf(duration)); } String locationUrl = node.getLocationUrl(); if (locationUrl != null) { attrs.put(ATTR_LOCATION, locationUrl); } if (node.isConfig()) { attrs.put(ATTR_CONFIG, "true"); } String elemName = node.isLeaf() ? ELEM_TEST : ELEM_SUITE; startElement(elemName, attrs); if (node.isLeaf()) { final StringBuilder buffer = new StringBuilder(); final Ref<ConsoleViewContentType> lastType = new Ref<ConsoleViewContentType>(); final Ref<SAXException> error = new Ref<SAXException>(); node.printOn(new Printer() { @Override public void print(String text, ConsoleViewContentType contentType) { if (contentType != lastType.get()) { if (buffer.length() > 0) { try { writeOutput(lastType.get(), buffer, filter); } catch (SAXException e) { error.set(e); } } lastType.set(contentType); } buffer.append(text); } @Override public void onNewAvailable(@NotNull Printable printable) { } @Override public void printHyperlink(String text, HyperlinkInfo info) { } @Override public void mark() { } }); if (!error.isNull()) { throw error.get(); } if (buffer.length() > 0) { writeOutput(lastType.get(), buffer, filter); } } else { for (AbstractTestProxy child : node.getChildren()) { if (myHidePassedConfig && child.isConfig() && child.isPassed()) { //ignore configurations during export continue; } processNode(child, filter); } } endElement(elemName); } private void writeOutput(ConsoleViewContentType type, StringBuilder text, Filter filter) throws SAXException { StringBuilder output = new StringBuilder(); StringTokenizer t = new StringTokenizer(text.toString(), "\n"); while (t.hasMoreTokens()) { String line = StringUtil.escapeXml(t.nextToken()) + "\n"; Filter.Result result = null;//filter.applyFilter(line, line.length()); if (result != null && result.hyperlinkInfo instanceof OpenFileHyperlinkInfo) { output.append(line.substring(0, result.highlightStartOffset)); OpenFileDescriptor descriptor = ((OpenFileHyperlinkInfo)result.hyperlinkInfo).getDescriptor(); output.append("<a href=\"javascript://\" onclick=\"Activator.doOpen('file?file="); output.append(descriptor.getFile().getPresentableUrl()); output.append("&line="); output.append(descriptor.getLine()); output.append("')\">"); output.append(line.substring(result.highlightStartOffset, result.highlightEndOffset)); output.append("</a>"); output.append(line.substring(result.highlightEndOffset)); } else { output.append(line); } } Map<String, String> a = new HashMap<String, String>(); a.put(ATTR_OUTPUT_TYPE, getTypeString(type)); startElement(ELEM_OUTPUT, a); writeText(output.toString()); text.delete(0, text.length()); endElement(ELEM_OUTPUT); } private static String getTypeString(ConsoleViewContentType type) { return type == ConsoleViewContentType.ERROR_OUTPUT ? "stderr" : "stdout"; } private static String getStatusString(AbstractTestProxy node) { int magnitude = node.getMagnitude(); // TODO enumeration! switch (magnitude) { case 0: return STATUS_SKIPPED; case 2: case 4: return STATUS_SKIPPED; case 5: return STATUS_IGNORED; case 1: return STATUS_PASSED; case 6: return STATUS_FAILED; case 8: return STATUS_ERROR; default: return node.isPassed() ? STATUS_PASSED : STATUS_FAILED; } } private void startElement(String name, Map<String, String> attributes) throws SAXException { AttributesImpl attrs = new AttributesImpl(); for (Map.Entry<String, String> entry : attributes.entrySet()) { attrs.addAttribute("", entry.getKey(), entry.getKey(), "CDATA", entry.getValue()); } myResultHandler.startElement("", name, name, attrs); } private void endElement(String name) throws SAXException { myResultHandler.endElement("", name, name); } private void writeText(String text) throws SAXException { final char[] chars = text.toCharArray(); myResultHandler.characters(chars, 0, chars.length); } }
export tests: skip empty suites (due to successful configs) on export (IDEA-142269)
platform/testRunner/src/com/intellij/execution/testframework/export/TestResultsXmlFormatter.java
export tests: skip empty suites (due to successful configs) on export (IDEA-142269)
Java
apache-2.0
b75bbcefc3cfe2aedf576428bb9aeb54425d10db
0
allotria/intellij-community,semonte/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,blademainer/intellij-community,retomerz/intellij-community,fnouama/intellij-community,kdwink/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,petteyg/intellij-community,consulo/consulo,Lekanich/intellij-community,wreckJ/intellij-community,jexp/idea2,nicolargo/intellij-community,apixandru/intellij-community,allotria/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,ernestp/consulo,xfournet/intellij-community,apixandru/intellij-community,adedayo/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,xfournet/intellij-community,hurricup/intellij-community,slisson/intellij-community,semonte/intellij-community,signed/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,asedunov/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,robovm/robovm-studio,dslomov/intellij-community,FHannes/intellij-community,slisson/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,izonder/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,holmes/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,asedunov/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,ibinti/intellij-community,supersven/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,clumsy/intellij-community,caot/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,signed/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,Lekanich/intellij-community,holmes/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,ernestp/consulo,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,slisson/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,clumsy/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,clumsy/intellij-community,caot/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,slisson/intellij-community,ibinti/intellij-community,joewalnes/idea-community,hurricup/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,samthor/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,amith01994/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,ryano144/intellij-community,adedayo/intellij-community,blademainer/intellij-community,dslomov/intellij-community,samthor/intellij-community,da1z/intellij-community,hurricup/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,ernestp/consulo,gnuhub/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,xfournet/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,consulo/consulo,dslomov/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,consulo/consulo,signed/intellij-community,lucafavatella/intellij-community,signed/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,kdwink/intellij-community,signed/intellij-community,blademainer/intellij-community,supersven/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,jexp/idea2,muntasirsyed/intellij-community,blademainer/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,semonte/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,jexp/idea2,ahb0327/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,robovm/robovm-studio,fnouama/intellij-community,fitermay/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,izonder/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,slisson/intellij-community,kool79/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,caot/intellij-community,FHannes/intellij-community,samthor/intellij-community,dslomov/intellij-community,diorcety/intellij-community,retomerz/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,allotria/intellij-community,samthor/intellij-community,consulo/consulo,akosyakov/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,caot/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,adedayo/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,supersven/intellij-community,xfournet/intellij-community,caot/intellij-community,jexp/idea2,semonte/intellij-community,TangHao1987/intellij-community,caot/intellij-community,ibinti/intellij-community,ryano144/intellij-community,ryano144/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,kool79/intellij-community,vladmm/intellij-community,petteyg/intellij-community,amith01994/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,caot/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,joewalnes/idea-community,da1z/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,orekyuu/intellij-community,consulo/consulo,Lekanich/intellij-community,holmes/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,izonder/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,izonder/intellij-community,asedunov/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,asedunov/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,supersven/intellij-community,da1z/intellij-community,clumsy/intellij-community,kdwink/intellij-community,asedunov/intellij-community,fnouama/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,Distrotech/intellij-community,kool79/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,jagguli/intellij-community,FHannes/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,samthor/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,diorcety/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,fitermay/intellij-community,FHannes/intellij-community,apixandru/intellij-community,dslomov/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,allotria/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,ernestp/consulo,ryano144/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,diorcety/intellij-community,da1z/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,samthor/intellij-community,blademainer/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,semonte/intellij-community,slisson/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,signed/intellij-community,clumsy/intellij-community,ryano144/intellij-community,holmes/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,ernestp/consulo,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,jagguli/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,semonte/intellij-community,supersven/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,clumsy/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,slisson/intellij-community,fnouama/intellij-community,jexp/idea2,vvv1559/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,caot/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,signed/intellij-community,supersven/intellij-community,suncycheng/intellij-community,ernestp/consulo,ryano144/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,joewalnes/idea-community,adedayo/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,da1z/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,semonte/intellij-community,caot/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,consulo/consulo,ftomassetti/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,vladmm/intellij-community,FHannes/intellij-community,allotria/intellij-community,izonder/intellij-community,allotria/intellij-community,xfournet/intellij-community,joewalnes/idea-community,xfournet/intellij-community,vvv1559/intellij-community,jexp/idea2,asedunov/intellij-community,allotria/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,samthor/intellij-community,joewalnes/idea-community,orekyuu/intellij-community,joewalnes/idea-community,joewalnes/idea-community,fitermay/intellij-community,hurricup/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,amith01994/intellij-community,fitermay/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,caot/intellij-community,pwoodworth/intellij-community,signed/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,FHannes/intellij-community,kdwink/intellij-community,joewalnes/idea-community,allotria/intellij-community,jagguli/intellij-community,kool79/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,diorcety/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,jexp/idea2,mglukhikh/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,joewalnes/idea-community,fitermay/intellij-community,robovm/robovm-studio,petteyg/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,jexp/idea2,ol-loginov/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,FHannes/intellij-community,retomerz/intellij-community,izonder/intellij-community,signed/intellij-community,holmes/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,allotria/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,supersven/intellij-community,petteyg/intellij-community,samthor/intellij-community,petteyg/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community
/* * Copyright (c) 2000-2006 JetBrains s.r.o. All Rights Reserved. */ package com.intellij.psi.impl.source.resolve.reference.impl.providers; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.Nullable; /** * @author peter */ public class AttributeValueSelfReference extends BasicAttributeValueReference { public AttributeValueSelfReference(final PsiElement element) { super(element); } public AttributeValueSelfReference(final PsiElement element, int offset) { super(element, offset); } public AttributeValueSelfReference(final PsiElement element, TextRange range) { super(element, range); } @Nullable public PsiElement resolve() { return myElement; } public Object[] getVariants() { return ArrayUtil.EMPTY_OBJECT_ARRAY; } public boolean isSoft() { return true; } }
xml/impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/AttributeValueSelfReference.java
/* * Copyright (c) 2000-2006 JetBrains s.r.o. All Rights Reserved. */ package com.intellij.psi.impl.source.resolve.reference.impl.providers; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiNamedElement; import com.intellij.openapi.util.TextRange; import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.Nullable; /** * @author peter */ public class AttributeValueSelfReference extends BasicAttributeValueReference { public AttributeValueSelfReference(final PsiElement element) { super(element); } public AttributeValueSelfReference(final PsiElement element, int offset) { super(element, offset); } public AttributeValueSelfReference(final PsiElement element, TextRange range) { super(element, range); } @Nullable public PsiElement resolve() { return myElement; } public Object[] getVariants() { return ArrayUtil.EMPTY_OBJECT_ARRAY; } public boolean isSoft() { return true; } public boolean isReferenceTo(PsiElement element) { return super.isReferenceTo(element) || ( element instanceof PsiNamedElement && // DOM node element.getNode() == null && ((PsiNamedElement)element).getName().equals(getCanonicalText()) ); } }
IDEADEV-33969
xml/impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/AttributeValueSelfReference.java
IDEADEV-33969
Java
apache-2.0
1179e40c7fa9aeadcb6d4a5b3957580b9b89b7d0
0
kieker-monitoring/kieker,leadwire-apm/leadwire-javaagent,leadwire-apm/leadwire-javaagent,HaStr/kieker,HaStr/kieker,kieker-monitoring/kieker,HaStr/kieker,kieker-monitoring/kieker,HaStr/kieker,kieker-monitoring/kieker,HaStr/kieker,kieker-monitoring/kieker
/*************************************************************************** * Copyright 2013 Kieker Project (http://kieker-monitoring.net) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ***************************************************************************/ package kieker.tools.bridge.cli; import java.net.URL; import java.net.URLClassLoader; import java.security.PrivilegedAction; /** * @author Reiner Jung * @author Nils Ehmke * @since 1.8 */ public class PrivilegedClassLoaderAction implements PrivilegedAction<URLClassLoader> { /** * The list of libraries used to create the class loader. */ private final URL[] urls; /** * Creates a new instance of this class using the given parameters. * * @param urls * The list of libraries used to create the class loader. */ public PrivilegedClassLoaderAction(final URL[] urls) { // NOPMD this.urls = urls; } /** * Runs the action. * * @return The class loader. */ public URLClassLoader run() { return new URLClassLoader(this.urls, CLIServerMain.class.getClassLoader()); } }
src/tools/kieker/tools/bridge/cli/PrivilegedClassLoaderAction.java
/*************************************************************************** * Copyright 2013 Kieker Project (http://kieker-monitoring.net) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ***************************************************************************/ package kieker.tools.bridge.cli; import java.net.URL; import java.net.URLClassLoader; import java.security.PrivilegedAction; /** * @author Reiner Jung * @author Nils Ehmke * @since 1.8 */ public class PrivilegedClassLoaderAction implements PrivilegedAction<URLClassLoader> { /** * The list of libraries used to create the class loader. */ private final URL[] urls; /** * Creates a new instance of this class using the given parameters. * * @param urls * The list of libraries used to create the class loader. */ public PrivilegedClassLoaderAction(final URL[] urls) { // NOPMND this.urls = urls; } /** * Runs the action. * * @return The class loader. */ public URLClassLoader run() { return new URLClassLoader(this.urls, CLIServerMain.class.getClassLoader()); } }
Fix typo.
src/tools/kieker/tools/bridge/cli/PrivilegedClassLoaderAction.java
Fix typo.
Java
apache-2.0
64fd62e0a9ad1860a8c28a602533c5f7b432ca76
0
ThiagoGarciaAlves/intellij-community,da1z/intellij-community,xfournet/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,xfournet/intellij-community,da1z/intellij-community,xfournet/intellij-community,da1z/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,apixandru/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,da1z/intellij-community,apixandru/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,apixandru/intellij-community,da1z/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,allotria/intellij-community,da1z/intellij-community,allotria/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,xfournet/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,apixandru/intellij-community,xfournet/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,xfournet/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,allotria/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,da1z/intellij-community,da1z/intellij-community,allotria/intellij-community,xfournet/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.java.propertyBased; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl; import com.intellij.psi.PsiFile; import com.intellij.testFramework.LightProjectDescriptor; import com.intellij.testFramework.SkipSlowTestLocally; import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase; import com.intellij.testFramework.propertyBased.*; import jetCheck.Generator; import jetCheck.PropertyChecker; import org.jetbrains.annotations.NotNull; import java.util.function.Function; /** * @author peter */ @SkipSlowTestLocally public class JavaCodeInsightSanityTest extends LightCodeInsightFixtureTestCase { @Override protected void tearDown() throws Exception { // remove jdk if it was created during highlighting to avoid leaks WriteAction.run(()->JavaAwareProjectJdkTableImpl.getInstanceEx().removeJdk(JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk())); super.tearDown(); } @NotNull @Override protected LightProjectDescriptor getProjectDescriptor() { return JAVA_9; } public void testRandomActivity() { MadTestingUtil.enableAllInspections(getProject(), getTestRootDisposable()); Function<PsiFile, Generator<? extends MadTestingAction>> fileActions = file -> Generator.anyOf(InvokeIntention.randomIntentions(file, new JavaIntentionPolicy()), InvokeCompletion.completions(file, new JavaCompletionPolicy()), Generator.constant(new StripTestDataMarkup(file)), DeleteRange.psiRangeDeletions(file)); PropertyChecker.forAll(actionsOnJavaFiles(fileActions)).shouldHold(FileWithActions::runActions); } @NotNull private Generator<FileWithActions> actionsOnJavaFiles(Function<PsiFile, Generator<? extends MadTestingAction>> fileActions) { return MadTestingUtil.actionsOnFileContents(myFixture, PathManager.getHomePath(), f -> f.getName().endsWith(".java"), fileActions); } public void testReparse() { PropertyChecker.forAll(actionsOnJavaFiles(MadTestingUtil::randomEditsWithReparseChecks)).shouldHold(FileWithActions::runActions); } }
java/java-tests/testSrc/com/intellij/java/propertyBased/JavaCodeInsightSanityTest.java
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.java.propertyBased; import com.intellij.openapi.application.PathManager; import com.intellij.psi.PsiFile; import com.intellij.testFramework.LightProjectDescriptor; import com.intellij.testFramework.SkipSlowTestLocally; import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase; import com.intellij.testFramework.propertyBased.*; import org.jetbrains.annotations.NotNull; import jetCheck.Generator; import jetCheck.PropertyChecker; import java.util.function.Function; /** * @author peter */ @SkipSlowTestLocally public class JavaCodeInsightSanityTest extends LightCodeInsightFixtureTestCase { @NotNull @Override protected LightProjectDescriptor getProjectDescriptor() { return JAVA_9; } public void testRandomActivity() { MadTestingUtil.enableAllInspections(getProject(), getTestRootDisposable()); Function<PsiFile, Generator<? extends MadTestingAction>> fileActions = file -> Generator.anyOf(InvokeIntention.randomIntentions(file, new JavaIntentionPolicy()), InvokeCompletion.completions(file, new JavaCompletionPolicy()), Generator.constant(new StripTestDataMarkup(file)), DeleteRange.psiRangeDeletions(file)); PropertyChecker.forAll(actionsOnJavaFiles(fileActions)).shouldHold(FileWithActions::runActions); } @NotNull private Generator<FileWithActions> actionsOnJavaFiles(Function<PsiFile, Generator<? extends MadTestingAction>> fileActions) { return MadTestingUtil.actionsOnFileContents(myFixture, PathManager.getHomePath(), f -> f.getName().endsWith(".java"), fileActions); } public void testReparse() { PropertyChecker.forAll(actionsOnJavaFiles(MadTestingUtil::randomEditsWithReparseChecks)).shouldHold(FileWithActions::runActions); } }
test fix
java/java-tests/testSrc/com/intellij/java/propertyBased/JavaCodeInsightSanityTest.java
test fix
Java
apache-2.0
aa913502c7a282371887193ea0cdba8883024211
0
da1z/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,fitermay/intellij-community,xfournet/intellij-community,asedunov/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,allotria/intellij-community,apixandru/intellij-community,signed/intellij-community,ibinti/intellij-community,FHannes/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,semonte/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,da1z/intellij-community,fitermay/intellij-community,hurricup/intellij-community,fitermay/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,xfournet/intellij-community,retomerz/intellij-community,da1z/intellij-community,hurricup/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,signed/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,semonte/intellij-community,allotria/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,da1z/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,signed/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,semonte/intellij-community,da1z/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,vvv1559/intellij-community,allotria/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,fitermay/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,asedunov/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,allotria/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,fitermay/intellij-community,hurricup/intellij-community,signed/intellij-community,allotria/intellij-community,fitermay/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,apixandru/intellij-community,xfournet/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,ibinti/intellij-community,retomerz/intellij-community,signed/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,ibinti/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,fitermay/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,signed/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,allotria/intellij-community,hurricup/intellij-community,semonte/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,semonte/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,da1z/intellij-community,FHannes/intellij-community,signed/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,asedunov/intellij-community,xfournet/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,signed/intellij-community,xfournet/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,fitermay/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,ibinti/intellij-community,fitermay/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,FHannes/intellij-community,retomerz/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,signed/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,signed/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,FHannes/intellij-community,apixandru/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,retomerz/intellij-community,retomerz/intellij-community,FHannes/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,retomerz/intellij-community,ibinti/intellij-community
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.impl.search; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.QueryExecutorBase; import com.intellij.openapi.application.ReadActionProcessor; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressIndicatorProvider; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.LocalSearchScope; import com.intellij.psi.search.PsiSearchScopeUtil; import com.intellij.psi.search.SearchScope; import com.intellij.psi.search.searches.AllClassesSearch; import com.intellij.psi.search.searches.ClassInheritorsSearch; import com.intellij.psi.search.searches.DirectClassInheritorsSearch; import com.intellij.psi.util.PsiUtilCore; import com.intellij.util.CommonProcessors; import com.intellij.util.Processor; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.Stack; import org.jetbrains.annotations.NotNull; import java.util.*; public class JavaClassInheritorsSearcher extends QueryExecutorBase<PsiClass, ClassInheritorsSearch.SearchParameters> { @Override public void processQuery(@NotNull ClassInheritorsSearch.SearchParameters parameters, @NotNull Processor<PsiClass> consumer) { final PsiClass baseClass = parameters.getClassToProcess(); assert parameters.isCheckDeep(); assert parameters.isCheckInheritance(); ProgressIndicator progress = ProgressIndicatorProvider.getGlobalProgressIndicator(); if (progress != null) { progress.pushState(); String className = ApplicationManager.getApplication().runReadAction((Computable<String>)baseClass::getName); progress.setText(className != null ? PsiBundle.message("psi.search.inheritors.of.class.progress", className) : PsiBundle.message("psi.search.inheritors.progress")); } try { processInheritors(parameters, consumer); } finally { if (progress != null) { progress.popState(); } } } private static boolean processInheritors(@NotNull final ClassInheritorsSearch.SearchParameters parameters, @NotNull final Processor<PsiClass> consumer) { @NotNull final PsiClass baseClass = parameters.getClassToProcess(); if (baseClass instanceof PsiAnonymousClass || isFinal(baseClass)) return true; final SearchScope searchScope = parameters.getScope(); Project project = PsiUtilCore.getProjectInReadAction(baseClass); if (isJavaLangObject(baseClass)) { return AllClassesSearch.search(searchScope, project, parameters.getNameCondition()).forEach(aClass -> { ProgressManager.checkCanceled(); return isJavaLangObject(aClass) || consumer.process(aClass); }); } Collection<PsiClass> cached = getOrComputeSubClasses(project, parameters); Processor<PsiClass> readActionedConsumer = ReadActionProcessor.wrapInReadAction(consumer); for (final PsiClass subClass : cached) { ProgressManager.checkCanceled(); if (!readActionedConsumer.process(subClass)) { return false; } } return true; } @NotNull private static Collection<PsiClass> getOrComputeSubClasses(@NotNull Project project, @NotNull ClassInheritorsSearch.SearchParameters parameters) { List<PsiClass> computed = null; PsiClass baseClass = parameters.getClassToProcess(); while (true) { Collection<PsiClass> cached = null; List<Pair<ClassInheritorsSearch.SearchParameters, Collection<PsiClass>>> cachedPairs = HighlightingCaches.getInstance(project).ALL_SUB_CLASSES.get(baseClass); if (cachedPairs != null) { for (Pair<ClassInheritorsSearch.SearchParameters, Collection<PsiClass>> pair : cachedPairs) { ClassInheritorsSearch.SearchParameters cachedParams = pair.getFirst(); if (cachedParams.equals(parameters)) { cached = pair.getSecond(); break; } } } if (cached != null) { return cached; } if (computed == null) { computed = new ArrayList<>(); boolean success = getAllSubClasses(project, parameters, new CommonProcessors.CollectProcessor<>(computed)); assert success; } if (cachedPairs != null) { cachedPairs.add(Pair.create(parameters, computed)); break; } List<Pair<ClassInheritorsSearch.SearchParameters, Collection<PsiClass>>> newCachedPairs = ContainerUtil.createConcurrentList(Collections.singletonList(Pair.create(parameters, computed))); if (HighlightingCaches.getInstance(project).ALL_SUB_CLASSES.putIfAbsent(baseClass, newCachedPairs) == null) { break; } } return computed; } private static boolean getAllSubClasses(@NotNull Project project, @NotNull ClassInheritorsSearch.SearchParameters parameters, @NotNull Processor<PsiClass> consumer) { SearchScope searchScope = parameters.getScope(); final Ref<PsiClass> currentBase = Ref.create(null); final Stack<PsiAnchor> stack = new Stack<>(); final Set<PsiAnchor> processed = ContainerUtil.newTroveSet(); boolean checkDeep = searchScope instanceof LocalSearchScope; final Processor<PsiClass> processor = new ReadActionProcessor<PsiClass>() { @Override public boolean processInReadAction(PsiClass candidate) { ProgressManager.checkCanceled(); if (!candidate.isInheritor(currentBase.get(), checkDeep)) { return true; } if (PsiSearchScopeUtil.isInScope(searchScope, candidate)) { if (candidate instanceof PsiAnonymousClass) { return consumer.process(candidate); } final String name = candidate.getName(); if (name != null && parameters.getNameCondition().value(name) && !consumer.process(candidate)) { return false; } } if (!(candidate instanceof PsiAnonymousClass) && !candidate.hasModifierProperty(PsiModifier.FINAL)) { stack.push(PsiAnchor.create(candidate)); } return true; } }; @NotNull PsiClass baseClass = parameters.getClassToProcess(); if (searchScope instanceof LocalSearchScope) { // optimisation: it's considered cheaper to enumerate all scope files and check if there is an inheritor there, // instead of traversing the (potentially huge) class hierarchy and filter out almost everything by scope. VirtualFile[] virtualFiles = ((LocalSearchScope)searchScope).getVirtualFiles(); final boolean[] success = {true}; currentBase.set(baseClass); for (VirtualFile virtualFile : virtualFiles) { PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile); if (psiFile != null) { psiFile.accept(new JavaRecursiveElementVisitor() { @Override public void visitClass(PsiClass aClass) { if (!success[0]) return; if (!processor.process(aClass)) { success[0] = false; return; } super.visitClass(aClass); } @Override public void visitCodeBlock(PsiCodeBlock block) { if (!parameters.isIncludeAnonymous()) return; super.visitCodeBlock(block); } }); } } return success[0]; } ApplicationManager.getApplication().runReadAction(() -> { stack.push(PsiAnchor.create(baseClass)); }); final GlobalSearchScope projectScope = GlobalSearchScope.allScope(project); while (!stack.isEmpty()) { ProgressManager.checkCanceled(); final PsiAnchor anchor = stack.pop(); if (!processed.add(anchor)) continue; PsiClass psiClass = ApplicationManager.getApplication().runReadAction((Computable<PsiClass>)() -> (PsiClass)anchor.retrieve()); if (psiClass == null) continue; currentBase.set(psiClass); if (!DirectClassInheritorsSearch.search(psiClass, projectScope, parameters.isIncludeAnonymous(), false).forEach(processor)) return false; } return true; } static boolean isJavaLangObject(@NotNull final PsiClass baseClass) { return ApplicationManager.getApplication().runReadAction( (Computable<Boolean>)() -> baseClass.isValid() && CommonClassNames.JAVA_LANG_OBJECT.equals(baseClass.getQualifiedName())); } private static boolean isFinal(@NotNull final PsiClass baseClass) { return ApplicationManager.getApplication().runReadAction((Computable<Boolean>)() -> baseClass.hasModifierProperty(PsiModifier.FINAL)); } }
java/java-indexing-impl/src/com/intellij/psi/impl/search/JavaClassInheritorsSearcher.java
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.impl.search; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.QueryExecutorBase; import com.intellij.openapi.application.ReadActionProcessor; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressIndicatorProvider; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.PsiSearchScopeUtil; import com.intellij.psi.search.SearchScope; import com.intellij.psi.search.searches.AllClassesSearch; import com.intellij.psi.search.searches.ClassInheritorsSearch; import com.intellij.psi.search.searches.DirectClassInheritorsSearch; import com.intellij.psi.util.PsiUtilCore; import com.intellij.util.CommonProcessors; import com.intellij.util.Processor; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.Stack; import org.jetbrains.annotations.NotNull; import java.util.*; public class JavaClassInheritorsSearcher extends QueryExecutorBase<PsiClass, ClassInheritorsSearch.SearchParameters> { @Override public void processQuery(@NotNull ClassInheritorsSearch.SearchParameters parameters, @NotNull Processor<PsiClass> consumer) { final PsiClass baseClass = parameters.getClassToProcess(); assert parameters.isCheckDeep(); assert parameters.isCheckInheritance(); ProgressIndicator progress = ProgressIndicatorProvider.getGlobalProgressIndicator(); if (progress != null) { progress.pushState(); String className = ApplicationManager.getApplication().runReadAction((Computable<String>)baseClass::getName); progress.setText(className != null ? PsiBundle.message("psi.search.inheritors.of.class.progress", className) : PsiBundle.message("psi.search.inheritors.progress")); } try { processInheritors(parameters, consumer); } finally { if (progress != null) { progress.popState(); } } } private static boolean processInheritors(@NotNull final ClassInheritorsSearch.SearchParameters parameters, @NotNull final Processor<PsiClass> consumer) { @NotNull final PsiClass baseClass = parameters.getClassToProcess(); if (baseClass instanceof PsiAnonymousClass || isFinal(baseClass)) return true; final SearchScope searchScope = parameters.getScope(); Project project = PsiUtilCore.getProjectInReadAction(baseClass); if (isJavaLangObject(baseClass)) { return AllClassesSearch.search(searchScope, project, parameters.getNameCondition()).forEach(aClass -> { ProgressManager.checkCanceled(); return isJavaLangObject(aClass) || consumer.process(aClass); }); } Collection<PsiClass> cached = getOrComputeSubClasses(project, parameters); Processor<PsiClass> readActionedConsumer = ReadActionProcessor.wrapInReadAction(consumer); for (final PsiClass subClass : cached) { ProgressManager.checkCanceled(); if (!readActionedConsumer.process(subClass)) { return false; } } return true; } @NotNull private static Collection<PsiClass> getOrComputeSubClasses(@NotNull Project project, @NotNull ClassInheritorsSearch.SearchParameters parameters) { List<PsiClass> computed = null; PsiClass baseClass = parameters.getClassToProcess(); while (true) { Collection<PsiClass> cached = null; List<Pair<ClassInheritorsSearch.SearchParameters, Collection<PsiClass>>> cachedPairs = HighlightingCaches.getInstance(project).ALL_SUB_CLASSES.get(baseClass); if (cachedPairs != null) { for (Pair<ClassInheritorsSearch.SearchParameters, Collection<PsiClass>> pair : cachedPairs) { ClassInheritorsSearch.SearchParameters cachedParams = pair.getFirst(); if (cachedParams.equals(parameters)) { cached = pair.getSecond(); break; } } } if (cached != null) { return cached; } if (computed == null) { computed = new ArrayList<>(); boolean success = getAllSubClasses(project, parameters, new CommonProcessors.CollectProcessor<>(computed)); assert success; } if (cachedPairs != null) { cachedPairs.add(Pair.create(parameters, computed)); break; } List<Pair<ClassInheritorsSearch.SearchParameters, Collection<PsiClass>>> newCachedPairs = ContainerUtil.createConcurrentList(Collections.singletonList(Pair.create(parameters, computed))); if (HighlightingCaches.getInstance(project).ALL_SUB_CLASSES.putIfAbsent(baseClass, newCachedPairs) == null) { break; } } return computed; } private static boolean getAllSubClasses(@NotNull Project project, @NotNull ClassInheritorsSearch.SearchParameters parameters, @NotNull Processor<PsiClass> consumer) { SearchScope searchScope = parameters.getScope(); final Ref<PsiClass> currentBase = Ref.create(null); final Stack<PsiAnchor> stack = new Stack<>(); final Set<PsiAnchor> processed = ContainerUtil.newTroveSet(); final Processor<PsiClass> processor = new ReadActionProcessor<PsiClass>() { @Override public boolean processInReadAction(PsiClass candidate) { ProgressManager.checkCanceled(); if (parameters.isCheckInheritance() || !(candidate instanceof PsiAnonymousClass)) { if (!candidate.isInheritor(currentBase.get(), false)) { return true; } } if (PsiSearchScopeUtil.isInScope(searchScope, candidate)) { if (candidate instanceof PsiAnonymousClass) { return consumer.process(candidate); } final String name = candidate.getName(); if (name != null && parameters.getNameCondition().value(name) && !consumer.process(candidate)) { return false; } } if (!(candidate instanceof PsiAnonymousClass) && !candidate.hasModifierProperty(PsiModifier.FINAL)) { stack.push(PsiAnchor.create(candidate)); } return true; } }; ApplicationManager.getApplication().runReadAction(() -> { @NotNull PsiClass baseClass = parameters.getClassToProcess(); stack.push(PsiAnchor.create(baseClass)); }); final GlobalSearchScope projectScope = GlobalSearchScope.allScope(project); while (!stack.isEmpty()) { ProgressManager.checkCanceled(); final PsiAnchor anchor = stack.pop(); if (!processed.add(anchor)) continue; PsiClass psiClass = ApplicationManager.getApplication().runReadAction((Computable<PsiClass>)() -> (PsiClass)anchor.retrieve()); if (psiClass == null) continue; currentBase.set(psiClass); if (!DirectClassInheritorsSearch.search(psiClass, projectScope, parameters.isIncludeAnonymous(), false).forEach(processor)) return false; } return true; } static boolean isJavaLangObject(@NotNull final PsiClass baseClass) { return ApplicationManager.getApplication().runReadAction( (Computable<Boolean>)() -> baseClass.isValid() && CommonClassNames.JAVA_LANG_OBJECT.equals(baseClass.getQualifiedName())); } private static boolean isFinal(@NotNull final PsiClass baseClass) { return ApplicationManager.getApplication().runReadAction((Computable<Boolean>)() -> baseClass.hasModifierProperty(PsiModifier.FINAL)); } }
optimisation: iterate the whole LocalSearchScope instead of iterate all inheritors and filter out by scope
java/java-indexing-impl/src/com/intellij/psi/impl/search/JavaClassInheritorsSearcher.java
optimisation: iterate the whole LocalSearchScope instead of iterate all inheritors and filter out by scope
Java
apache-2.0
3a26ed23a8180e4aac06b8ed3c0ff2caec232ffc
0
jagguli/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,samthor/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,jagguli/intellij-community,fitermay/intellij-community,asedunov/intellij-community,signed/intellij-community,samthor/intellij-community,gnuhub/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,ryano144/intellij-community,petteyg/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,slisson/intellij-community,izonder/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,ernestp/consulo,signed/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,da1z/intellij-community,holmes/intellij-community,signed/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,clumsy/intellij-community,ibinti/intellij-community,da1z/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,holmes/intellij-community,retomerz/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,kool79/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,vladmm/intellij-community,jagguli/intellij-community,petteyg/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,FHannes/intellij-community,slisson/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,consulo/consulo,suncycheng/intellij-community,xfournet/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,supersven/intellij-community,samthor/intellij-community,hurricup/intellij-community,petteyg/intellij-community,semonte/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,FHannes/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,izonder/intellij-community,samthor/intellij-community,izonder/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,robovm/robovm-studio,dslomov/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,ryano144/intellij-community,da1z/intellij-community,ernestp/consulo,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,jagguli/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,diorcety/intellij-community,izonder/intellij-community,petteyg/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,xfournet/intellij-community,petteyg/intellij-community,petteyg/intellij-community,apixandru/intellij-community,holmes/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,consulo/consulo,retomerz/intellij-community,gnuhub/intellij-community,samthor/intellij-community,signed/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,vladmm/intellij-community,apixandru/intellij-community,petteyg/intellij-community,kool79/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,semonte/intellij-community,allotria/intellij-community,semonte/intellij-community,vladmm/intellij-community,allotria/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,caot/intellij-community,izonder/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,signed/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,apixandru/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,vladmm/intellij-community,kdwink/intellij-community,robovm/robovm-studio,amith01994/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,akosyakov/intellij-community,allotria/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,fnouama/intellij-community,amith01994/intellij-community,caot/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,apixandru/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,semonte/intellij-community,kdwink/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,consulo/consulo,akosyakov/intellij-community,ibinti/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,samthor/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,holmes/intellij-community,xfournet/intellij-community,caot/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,hurricup/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,amith01994/intellij-community,asedunov/intellij-community,allotria/intellij-community,adedayo/intellij-community,signed/intellij-community,diorcety/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,allotria/intellij-community,hurricup/intellij-community,asedunov/intellij-community,supersven/intellij-community,ernestp/consulo,fnouama/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,diorcety/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,izonder/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,caot/intellij-community,semonte/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,holmes/intellij-community,signed/intellij-community,signed/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,semonte/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,izonder/intellij-community,semonte/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,clumsy/intellij-community,blademainer/intellij-community,clumsy/intellij-community,jagguli/intellij-community,blademainer/intellij-community,FHannes/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,semonte/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,samthor/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,asedunov/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,ryano144/intellij-community,diorcety/intellij-community,ernestp/consulo,akosyakov/intellij-community,petteyg/intellij-community,da1z/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,semonte/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,ryano144/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,samthor/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,apixandru/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,supersven/intellij-community,robovm/robovm-studio,dslomov/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,amith01994/intellij-community,ernestp/consulo,ibinti/intellij-community,caot/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,da1z/intellij-community,orekyuu/intellij-community,ernestp/consulo,fnouama/intellij-community,kool79/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,hurricup/intellij-community,samthor/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,clumsy/intellij-community,supersven/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,kdwink/intellij-community,kool79/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,blademainer/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,jagguli/intellij-community,izonder/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,ibinti/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,holmes/intellij-community,robovm/robovm-studio,retomerz/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,slisson/intellij-community,caot/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,consulo/consulo,apixandru/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,allotria/intellij-community,robovm/robovm-studio,ibinti/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,fitermay/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,holmes/intellij-community,petteyg/intellij-community,slisson/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,supersven/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,diorcety/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,xfournet/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,jagguli/intellij-community,slisson/intellij-community,Distrotech/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,caot/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,allotria/intellij-community,dslomov/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,caot/intellij-community,hurricup/intellij-community,blademainer/intellij-community,signed/intellij-community,consulo/consulo,ftomassetti/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,retomerz/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,holmes/intellij-community,amith01994/intellij-community,kdwink/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,consulo/consulo,ryano144/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,kdwink/intellij-community,apixandru/intellij-community,caot/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,supersven/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,ibinti/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,slisson/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,allotria/intellij-community,Lekanich/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,vladmm/intellij-community
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.lang.psi.impl.statements.typedef; import com.intellij.lang.ASTNode; import com.intellij.navigation.ItemPresentation; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.impl.*; import com.intellij.psi.impl.source.tree.LeafPsiElement; import com.intellij.psi.impl.source.tree.java.ClassElement; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.ui.RowIcon; import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.VisibilityIcons; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.GroovyFileType; import org.jetbrains.plugins.groovy.GroovyIcons; import org.jetbrains.plugins.groovy.lang.groovydoc.psi.api.GrDocComment; import org.jetbrains.plugins.groovy.lang.groovydoc.psi.impl.GrDocCommentUtil; import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes; import org.jetbrains.plugins.groovy.lang.lexer.TokenSets; import org.jetbrains.plugins.groovy.lang.parser.GroovyElementTypes; import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor; import org.jetbrains.plugins.groovy.lang.psi.GroovyFile; import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrClassInitializer; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrExtendsClause; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrImplementsClause; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinitionBody; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMember; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMembersDeclaration; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement; import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeParameter; import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeParameterList; import org.jetbrains.plugins.groovy.lang.psi.api.types.GrWildcardTypeArgument; import org.jetbrains.plugins.groovy.lang.psi.impl.GrStubElementBase; import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyFileImpl; import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil; import org.jetbrains.plugins.groovy.lang.psi.stubs.GrTypeDefinitionStub; import org.jetbrains.plugins.groovy.lang.psi.util.GrClassImplUtil; import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil; import javax.swing.*; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * @author ilyas */ public abstract class GrTypeDefinitionImpl extends GrStubElementBase<GrTypeDefinitionStub> implements GrTypeDefinition, StubBasedPsiElement<GrTypeDefinitionStub> { private volatile PsiClass[] myInnerClasses; private volatile List<PsiMethod> myMethods; private volatile GrMethod[] myGroovyMethods; private volatile GrMethod[] myConstructors; public GrTypeDefinitionImpl(@NotNull ASTNode node) { super(node); } protected GrTypeDefinitionImpl(GrTypeDefinitionStub stub, IStubElementType nodeType) { super(stub, nodeType); } @Override public PsiElement getParent() { return getDefinitionParent(); } public void accept(GroovyElementVisitor visitor) { visitor.visitTypeDefinition(this); } public int getTextOffset() { return getNameIdentifierGroovy().getTextRange().getStartOffset(); } @Nullable public String getQualifiedName() { final GrTypeDefinitionStub stub = getStub(); if (stub != null) { return stub.getQualifiedName(); } PsiElement parent = getParent(); if (parent instanceof GroovyFile) { String packageName = ((GroovyFile)parent).getPackageName(); return packageName.length() > 0 ? packageName + "." + getName() : getName(); } final PsiClass containingClass = getContainingClass(); if (containingClass != null) { return containingClass.getQualifiedName() + "." + getName(); } return null; } public GrWildcardTypeArgument[] getTypeParametersGroovy() { return findChildrenByClass(GrWildcardTypeArgument.class); } @Nullable public GrTypeDefinitionBody getBody() { return getStubOrPsiChild(GroovyElementTypes.CLASS_BODY); } @NotNull public GrMembersDeclaration[] getMemberDeclarations() { GrTypeDefinitionBody body = getBody(); if (body == null) return GrMembersDeclaration.EMPTY_ARRAY; return body.getMemberDeclarations(); } public ItemPresentation getPresentation() { return new ItemPresentation() { @Nullable public String getPresentableText() { return getName(); } @Nullable public String getLocationString() { PsiFile file = getContainingFile(); if (file instanceof GroovyFile) { GroovyFile groovyFile = (GroovyFile)file; return groovyFile.getPackageName().length() > 0 ? "(" + groovyFile.getPackageName() + ")" : ""; } return ""; } @Nullable public Icon getIcon(boolean open) { return GrTypeDefinitionImpl.this.getIcon(ICON_FLAG_VISIBILITY | ICON_FLAG_READ_STATUS); } @Nullable public TextAttributesKey getTextAttributesKey() { return null; } }; } @Nullable public GrExtendsClause getExtendsClause() { return getStubOrPsiChild(GroovyElementTypes.EXTENDS_CLAUSE); } @Nullable public GrImplementsClause getImplementsClause() { return getStubOrPsiChild(GroovyElementTypes.IMPLEMENTS_CLAUSE); } public String[] getSuperClassNames() { final GrTypeDefinitionStub stub = getStub(); if (stub != null) { return stub.getSuperClassNames(); } return ArrayUtil.mergeArrays(getExtendsNames(), getImplementsNames()); } protected String[] getImplementsNames() { GrImplementsClause implementsClause = getImplementsClause(); GrCodeReferenceElement[] implementsRefs = implementsClause != null ? implementsClause.getReferenceElements() : GrCodeReferenceElement.EMPTY_ARRAY; ArrayList<String> implementsNames = new ArrayList<String>(implementsRefs.length); for (GrCodeReferenceElement ref : implementsRefs) { String name = ref.getReferenceName(); if (name != null) implementsNames.add(name); } return ArrayUtil.toStringArray(implementsNames); } protected String[] getExtendsNames() { GrExtendsClause extendsClause = getExtendsClause(); GrCodeReferenceElement[] extendsRefs = extendsClause != null ? extendsClause.getReferenceElements() : GrCodeReferenceElement.EMPTY_ARRAY; ArrayList<String> extendsNames = new ArrayList<String>(extendsRefs.length); for (GrCodeReferenceElement ref : extendsRefs) { String name = ref.getReferenceName(); if (name != null) extendsNames.add(name); } return ArrayUtil.toStringArray(extendsNames); } @NotNull public PsiElement getNameIdentifierGroovy() { PsiElement result = findChildByType(TokenSets.PROPERTY_NAMES); assert result != null; return result; } public void checkDelete() throws IncorrectOperationException { } public void delete() throws IncorrectOperationException { PsiElement parent = getParent(); if (parent instanceof GroovyFileImpl) { GroovyFileImpl file = (GroovyFileImpl)parent; if (file.getTypeDefinitions().length == 1 && !file.isScript()) { file.delete(); return; } } super.delete(); } public boolean processDeclarations(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, @Nullable PsiElement lastParent, @NotNull PsiElement place) { return GrClassImplUtil.processDeclarations(this, processor, state, lastParent, place); } public String getName() { final GrTypeDefinitionStub stub = getStub(); if (stub != null) { return stub.getName(); } return PsiImplUtil.getName(this); } @Override public boolean isEquivalentTo(PsiElement another) { return GrClassImplUtil.isClassEquivalentTo(this, another); } public boolean isInterface() { return false; } public boolean isAnnotationType() { return false; } public boolean isEnum() { return false; } @Nullable public PsiReferenceList getExtendsList() { return null; } @Nullable public PsiReferenceList getImplementsList() { return null; } @NotNull public PsiClassType[] getExtendsListTypes() { return CachedValuesManager.getManager(getProject()).getCachedValue(this, new CachedValueProvider<PsiClassType[]>() { @Override public Result<PsiClassType[]> compute() { return Result.create(GrClassImplUtil.getExtendsListTypes(GrTypeDefinitionImpl.this), PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT); } }); } @NotNull public PsiClassType[] getImplementsListTypes() { return CachedValuesManager.getManager(getProject()).getCachedValue(this, new CachedValueProvider<PsiClassType[]>() { @Override public Result<PsiClassType[]> compute() { return Result.create(GrClassImplUtil.getImplementsListTypes(GrTypeDefinitionImpl.this), PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT); } }); } @Nullable public PsiClass getSuperClass() { return GrClassImplUtil.getSuperClass(this); } public PsiClass[] getInterfaces() { return CachedValuesManager.getManager(getProject()).getCachedValue(this, new CachedValueProvider<PsiClass[]>() { @Override public Result<PsiClass[]> compute() { return Result.create(GrClassImplUtil.getInterfaces(GrTypeDefinitionImpl.this), PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT); } }); } @NotNull public final PsiClass[] getSupers() { return GrClassImplUtil.getSupers(this); } @NotNull public PsiClassType[] getSuperTypes() { return GrClassImplUtil.getSuperTypes(this); } @NotNull public GrField[] getFields() { GrTypeDefinitionBody body = getBody(); if (body != null) { return body.getFields(); } return GrField.EMPTY_ARRAY; } @NotNull public GrClassInitializer[] getInitializersGroovy() { GrTypeDefinitionBody body = getBody(); if (body != null) { return body.getInitializers(); } return GrClassInitializer.EMPTY_ARRAY; } @NotNull public PsiMethod[] getMethods() { List<PsiMethod> cached = myMethods; if (cached == null) { cached = new ArrayList<PsiMethod>(); GrTypeDefinitionBody body = getBody(); if (body != null) { cached.addAll(body.getMethods()); } myMethods = cached; } List<PsiMethod> result = new ArrayList<PsiMethod>(cached); result.addAll(GrClassImplUtil.getDelegatedMethods(this)); return result.toArray(new PsiMethod[result.size()]); } @NotNull public GrMethod[] getGroovyMethods() { GrMethod[] cached = myGroovyMethods; if (cached == null) { GrTypeDefinitionBody body = getBody(); myGroovyMethods = cached = body != null ? body.getGroovyMethods() : GrMethod.EMPTY_ARRAY; } return cached; } public void subtreeChanged() { myMethods = null; myInnerClasses = null; myConstructors = null; myGroovyMethods = null; super.subtreeChanged(); } @NotNull public PsiMethod[] getConstructors() { GrMethod[] cached = myConstructors; if (cached == null) { List<GrMethod> result = new ArrayList<GrMethod>(); for (final PsiMethod method : getMethods()) { if (method.isConstructor()) { result.add((GrMethod)method); } } myConstructors = cached = result.toArray(new GrMethod[result.size()]); } return cached; } @NotNull public PsiClass[] getInnerClasses() { PsiClass[] inners = myInnerClasses; if (inners == null) { final GrTypeDefinitionBody body = getBody(); myInnerClasses = inners = body != null ? body.getInnerClasses() : PsiClass.EMPTY_ARRAY; } return inners; } @NotNull public PsiClassInitializer[] getInitializers() { return PsiClassInitializer.EMPTY_ARRAY; } @NotNull public PsiField[] getAllFields() { return GrClassImplUtil.getAllFields(this); } @NotNull public PsiMethod[] getAllMethods() { return GrClassImplUtil.getAllMethods(this); } @NotNull public PsiClass[] getAllInnerClasses() { return PsiClassImplUtil.getAllInnerClasses(this); } @Nullable public PsiField findFieldByName(String name, boolean checkBases) { return GrClassImplUtil.findFieldByName(this, name, checkBases); } @Nullable public PsiMethod findMethodBySignature(PsiMethod patternMethod, boolean checkBases) { return GrClassImplUtil.findMethodBySignature(this, patternMethod, checkBases); } @NotNull public PsiMethod[] findMethodsBySignature(PsiMethod patternMethod, boolean checkBases) { return GrClassImplUtil.findMethodsBySignature(this, patternMethod, checkBases); } @NotNull public PsiMethod[] findCodeMethodsBySignature(PsiMethod patternMethod, boolean checkBases) { return GrClassImplUtil.findCodeMethodsBySignature(this, patternMethod, checkBases); } @NotNull public PsiMethod[] findMethodsByName(@NonNls String name, boolean checkBases) { return GrClassImplUtil.findMethodsByName(this, name, checkBases); } @NotNull public PsiMethod[] findCodeMethodsByName(@NonNls String name, boolean checkBases) { return GrClassImplUtil.findCodeMethodsByName(this, name, checkBases); } @NotNull public List<Pair<PsiMethod, PsiSubstitutor>> findMethodsAndTheirSubstitutorsByName(String name, boolean checkBases) { return GrClassImplUtil.findMethodsAndTheirSubstitutorsByName(this, name, checkBases); } @NotNull public List<Pair<PsiMethod, PsiSubstitutor>> getAllMethodsAndTheirSubstitutors() { return GrClassImplUtil.getAllMethodsAndTheirSubstitutors(this); } @Nullable public PsiClass findInnerClassByName(String name, boolean checkBases) { return null; } @Nullable public PsiElement getLBrace() { final GrTypeDefinitionBody body = getBody(); return body == null ? null : body.getLBrace(); } @Nullable public PsiElement getRBrace() { final GrTypeDefinitionBody body = getBody(); return body == null ? null : body.getRBrace(); } public boolean isAnonymous() { return false; } @Nullable public PsiIdentifier getNameIdentifier() { return PsiUtil.getJavaNameIdentifier(this); } @Nullable public PsiElement getScope() { return null; } public boolean isInheritor(@NotNull PsiClass baseClass, boolean checkDeep) { return InheritanceImplUtil.isInheritor(this, baseClass, checkDeep); } public boolean isInheritorDeep(PsiClass baseClass, @Nullable PsiClass classToByPass) { return InheritanceImplUtil.isInheritorDeep(this, baseClass, classToByPass); } @Nullable public PsiClass getContainingClass() { PsiElement parent = getParent(); if (parent instanceof GrTypeDefinitionBody) { final PsiElement pparent = parent.getParent(); if (pparent instanceof PsiClass) { return (PsiClass)pparent; } } return null; } @NotNull public Collection<HierarchicalMethodSignature> getVisibleSignatures() { return PsiSuperMethodImplUtil.getVisibleSignatures(this); } public PsiElement setName(@NonNls @NotNull String name) throws IncorrectOperationException { boolean renameFile = isRenameFileOnClassRenaming(); final String oldName = getName(); PsiImplUtil.setName(name, getNameIdentifierGroovy()); for (PsiMethod method : getMethods()) { if (method.isConstructor() && method.getName().equals(oldName)) method.setName(name); } if (renameFile) { final GroovyFileBase file = (GroovyFileBase)getContainingFile(); final VirtualFile virtualFile = file.getVirtualFile(); final String ext; if (virtualFile != null) { ext = virtualFile.getExtension(); } else { ext = GroovyFileType.GROOVY_FILE_TYPE.getDefaultExtension(); } file.setName(name + "." + ext); } return this; } @Nullable public GrModifierList getModifierList() { return getStubOrPsiChild(GroovyElementTypes.MODIFIERS); } public boolean hasModifierProperty(@NonNls @NotNull String name) { PsiModifierList modifierList = getModifierList(); return modifierList != null && modifierList.hasModifierProperty(name); } @Nullable public GrDocComment getDocComment() { return GrDocCommentUtil.findDocComment(this); } public boolean isDeprecated() { return com.intellij.psi.impl.PsiImplUtil.isDeprecatedByDocTag(this) || com.intellij.psi.impl.PsiImplUtil.isDeprecatedByAnnotation(this); } public boolean hasTypeParameters() { return getTypeParameters().length > 0; } @Nullable public GrTypeParameterList getTypeParameterList() { return getStubOrPsiChild(GroovyElementTypes.TYPE_PARAMETER_LIST); } @NotNull public GrTypeParameter[] getTypeParameters() { final GrTypeParameterList list = getTypeParameterList(); if (list != null) { return list.getTypeParameters(); } return GrTypeParameter.EMPTY_ARRAY; } @Override protected boolean isVisibilitySupported() { return true; } @Nullable public Icon getIcon(int flags) { Icon icon = getIconInner(); final boolean isLocked = (flags & ICON_FLAG_READ_STATUS) != 0 && !isWritable(); RowIcon rowIcon = ElementBase.createLayeredIcon(icon, ElementPresentationUtil.getFlags(this, isLocked)); if ((flags & ICON_FLAG_VISIBILITY) != 0) { VisibilityIcons.setVisibilityIcon(getModifierList(), rowIcon); } return rowIcon; } private Icon getIconInner() { if (isAnnotationType()) return GroovyIcons.ANNOTATION_TYPE; if (isInterface()) return GroovyIcons.INTERFACE; if (isEnum()) return GroovyIcons.ENUM; if (hasModifierProperty(PsiModifier.ABSTRACT)) return GroovyIcons.ABSTRACT_CLASS; return GroovyIcons.CLASS; } private boolean isRenameFileOnClassRenaming() { final PsiFile file = getContainingFile(); if (!(file instanceof GroovyFile)) return false; final GroovyFile groovyFile = (GroovyFile)file; if (groovyFile.isScript()) return false; final String name = getName(); final VirtualFile vFile = groovyFile.getVirtualFile(); return vFile != null && name != null && name.equals(vFile.getNameWithoutExtension()); } @Nullable public PsiElement getOriginalElement() { return PsiImplUtil.getOriginalElement(this, getContainingFile()); } public PsiElement addAfter(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException { if (anchor == null) { return add(element); } final GrTypeDefinitionBody body = getBody(); if (anchor.getParent() == body) { final PsiElement nextChild = anchor.getNextSibling(); if (nextChild == null) { add(element); return element; } ASTNode node = element.getNode(); assert node != null; //body.getNode().addLeaf(GroovyElementTypes.mNLS, "\n", nextChild.getNode()); return body.addBefore(element, nextChild); } else { return super.addAfter(element, anchor); } } public PsiElement addBefore(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException { if (anchor == null) { add(element); return element; } final GrTypeDefinitionBody body = getBody(); if (anchor.getParent() != body) { return super.addBefore(element, anchor); } ASTNode node = element.getNode(); assert node != null; final ASTNode bodyNode = body.getNode(); final ASTNode anchorNode = anchor.getNode(); bodyNode.addChild(node, anchorNode); bodyNode.addLeaf(GroovyTokenTypes.mWS, " ", node); bodyNode.addLeaf(GroovyTokenTypes.mNLS, "\n", anchorNode); return element; } public PsiElement add(@NotNull PsiElement psiElement) throws IncorrectOperationException { final GrTypeDefinitionBody body = getBody(); if (body == null) throw new IncorrectOperationException("Class must have body"); final PsiElement lBrace = body.getLBrace(); if (lBrace == null) throw new IncorrectOperationException("No left brace"); PsiMember member = getAnyMember(psiElement); PsiElement anchor = member != null ? getDefaultAnchor(body, member) : null; if (anchor == null) { anchor = lBrace.getNextSibling(); } if (anchor != null) { ASTNode node = anchor.getNode(); assert node != null; if (GroovyElementTypes.mSEMI.equals(node.getElementType())) { anchor = anchor.getNextSibling(); } psiElement = body.addBefore(psiElement, anchor); } else { body.add(psiElement); } return psiElement; } @Nullable private static PsiMember getAnyMember(@Nullable PsiElement psiElement) { if (psiElement instanceof PsiMember) { return (PsiMember)psiElement; } if (psiElement instanceof GrVariableDeclaration) { final GrMember[] members = ((GrVariableDeclaration)psiElement).getMembers(); if (members.length > 0) { return members[0]; } } return null; } @Nullable private PsiElement getDefaultAnchor(GrTypeDefinitionBody body, PsiMember member) { CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(getProject()); int order = ClassElement.getMemberOrderWeight(member, settings); if (order < 0) return null; PsiElement lastMember = null; for (PsiElement child = body.getFirstChild(); child != null; child = child.getNextSibling()) { int order1 = ClassElement.getMemberOrderWeight(getAnyMember(child), settings); if (order1 < 0) continue; if (order1 > order) { final PsiElement lBrace = body.getLBrace(); if (lastMember != null) { PsiElement nextSibling = lastMember.getNextSibling(); while (nextSibling instanceof LeafPsiElement && (nextSibling.getText().equals(",") || nextSibling.getText().equals(";"))) { nextSibling = nextSibling.getNextSibling(); } return nextSibling == null && lBrace != null ? PsiUtil.skipWhitespaces(lBrace.getNextSibling(), true) : nextSibling; } else if (lBrace != null) { return PsiUtil.skipWhitespaces(lBrace.getNextSibling(), true); } } lastMember = child; } return body.getRBrace(); } public <T extends GrMembersDeclaration> T addMemberDeclaration(@NotNull T decl, PsiElement anchorBefore) throws IncorrectOperationException { if (anchorBefore == null) { return (T)add(decl); } GrTypeDefinitionBody body = getBody(); if (body == null) throw new IncorrectOperationException("Type definition without a body"); // ASTNode anchorNode; // anchorNode = anchorBefore.getNode(); // ASTNode bodyNode = body.getNode(); decl = (T)body.addBefore(decl, anchorBefore); // bodyNode.addLeaf(GroovyTokenTypes.mWS, " ", decl.getNode()); //add whitespaces before and after to hack over incorrect auto reformat // bodyNode.addLeaf(GroovyTokenTypes.mWS, " ", anchorNode); return decl; } }
plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/typedef/GrTypeDefinitionImpl.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.lang.psi.impl.statements.typedef; import com.intellij.lang.ASTNode; import com.intellij.navigation.ItemPresentation; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.impl.*; import com.intellij.psi.impl.source.tree.LeafPsiElement; import com.intellij.psi.impl.source.tree.java.ClassElement; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.ui.RowIcon; import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.VisibilityIcons; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.GroovyFileType; import org.jetbrains.plugins.groovy.GroovyIcons; import org.jetbrains.plugins.groovy.lang.groovydoc.psi.api.GrDocComment; import org.jetbrains.plugins.groovy.lang.groovydoc.psi.impl.GrDocCommentUtil; import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes; import org.jetbrains.plugins.groovy.lang.lexer.TokenSets; import org.jetbrains.plugins.groovy.lang.parser.GroovyElementTypes; import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor; import org.jetbrains.plugins.groovy.lang.psi.GroovyFile; import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrClassInitializer; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrExtendsClause; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrImplementsClause; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinitionBody; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMember; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMembersDeclaration; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement; import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeParameter; import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeParameterList; import org.jetbrains.plugins.groovy.lang.psi.api.types.GrWildcardTypeArgument; import org.jetbrains.plugins.groovy.lang.psi.impl.GrStubElementBase; import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyFileImpl; import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil; import org.jetbrains.plugins.groovy.lang.psi.stubs.GrTypeDefinitionStub; import org.jetbrains.plugins.groovy.lang.psi.util.GrClassImplUtil; import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil; import javax.swing.*; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * @author ilyas */ public abstract class GrTypeDefinitionImpl extends GrStubElementBase<GrTypeDefinitionStub> implements GrTypeDefinition, StubBasedPsiElement<GrTypeDefinitionStub> { private volatile PsiClass[] myInnerClasses; private volatile List<PsiMethod> myMethods; private volatile GrMethod[] myGroovyMethods; private volatile GrMethod[] myConstructors; public GrTypeDefinitionImpl(@NotNull ASTNode node) { super(node); } protected GrTypeDefinitionImpl(GrTypeDefinitionStub stub, IStubElementType nodeType) { super(stub, nodeType); } @Override public PsiElement getParent() { return getDefinitionParent(); } public void accept(GroovyElementVisitor visitor) { visitor.visitTypeDefinition(this); } public int getTextOffset() { return getNameIdentifierGroovy().getTextRange().getStartOffset(); } @Nullable public String getQualifiedName() { final GrTypeDefinitionStub stub = getStub(); if (stub != null) { return stub.getQualifiedName(); } PsiElement parent = getParent(); if (parent instanceof GroovyFile) { String packageName = ((GroovyFile)parent).getPackageName(); return packageName.length() > 0 ? packageName + "." + getName() : getName(); } final PsiClass containingClass = getContainingClass(); if (containingClass != null) { return containingClass.getQualifiedName() + "." + getName(); } return null; } public GrWildcardTypeArgument[] getTypeParametersGroovy() { return findChildrenByClass(GrWildcardTypeArgument.class); } @Nullable public GrTypeDefinitionBody getBody() { return getStubOrPsiChild(GroovyElementTypes.CLASS_BODY); } @NotNull public GrMembersDeclaration[] getMemberDeclarations() { GrTypeDefinitionBody body = getBody(); if (body == null) return GrMembersDeclaration.EMPTY_ARRAY; return body.getMemberDeclarations(); } public ItemPresentation getPresentation() { return new ItemPresentation() { @Nullable public String getPresentableText() { return getName(); } @Nullable public String getLocationString() { PsiFile file = getContainingFile(); if (file instanceof GroovyFile) { GroovyFile groovyFile = (GroovyFile)file; return groovyFile.getPackageName().length() > 0 ? "(" + groovyFile.getPackageName() + ")" : ""; } return ""; } @Nullable public Icon getIcon(boolean open) { return GrTypeDefinitionImpl.this.getIcon(ICON_FLAG_VISIBILITY | ICON_FLAG_READ_STATUS); } @Nullable public TextAttributesKey getTextAttributesKey() { return null; } }; } @Nullable public GrExtendsClause getExtendsClause() { return getStubOrPsiChild(GroovyElementTypes.EXTENDS_CLAUSE); } @Nullable public GrImplementsClause getImplementsClause() { return getStubOrPsiChild(GroovyElementTypes.IMPLEMENTS_CLAUSE); } public String[] getSuperClassNames() { final GrTypeDefinitionStub stub = getStub(); if (stub != null) { return stub.getSuperClassNames(); } return ArrayUtil.mergeArrays(getExtendsNames(), getImplementsNames()); } protected String[] getImplementsNames() { GrImplementsClause implementsClause = getImplementsClause(); GrCodeReferenceElement[] implementsRefs = implementsClause != null ? implementsClause.getReferenceElements() : GrCodeReferenceElement.EMPTY_ARRAY; ArrayList<String> implementsNames = new ArrayList<String>(implementsRefs.length); for (GrCodeReferenceElement ref : implementsRefs) { String name = ref.getReferenceName(); if (name != null) implementsNames.add(name); } return ArrayUtil.toStringArray(implementsNames); } protected String[] getExtendsNames() { GrExtendsClause extendsClause = getExtendsClause(); GrCodeReferenceElement[] extendsRefs = extendsClause != null ? extendsClause.getReferenceElements() : GrCodeReferenceElement.EMPTY_ARRAY; ArrayList<String> extendsNames = new ArrayList<String>(extendsRefs.length); for (GrCodeReferenceElement ref : extendsRefs) { String name = ref.getReferenceName(); if (name != null) extendsNames.add(name); } return ArrayUtil.toStringArray(extendsNames); } @NotNull public PsiElement getNameIdentifierGroovy() { PsiElement result = findChildByType(TokenSets.PROPERTY_NAMES); assert result != null; return result; } public void checkDelete() throws IncorrectOperationException { } public void delete() throws IncorrectOperationException { PsiElement parent = getParent(); if (parent instanceof GroovyFileImpl) { GroovyFileImpl file = (GroovyFileImpl)parent; if (file.getTypeDefinitions().length == 1 && !file.isScript()) { file.delete(); return; } } super.delete(); } public boolean processDeclarations(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, @Nullable PsiElement lastParent, @NotNull PsiElement place) { return GrClassImplUtil.processDeclarations(this, processor, state, lastParent, place); } public String getName() { final GrTypeDefinitionStub stub = getStub(); if (stub != null) { return stub.getName(); } return PsiImplUtil.getName(this); } @Override public boolean isEquivalentTo(PsiElement another) { return GrClassImplUtil.isClassEquivalentTo(this, another); } public boolean isInterface() { return false; } public boolean isAnnotationType() { return false; } public boolean isEnum() { return false; } @Nullable public PsiReferenceList getExtendsList() { return null; } @Nullable public PsiReferenceList getImplementsList() { return null; } @NotNull public PsiClassType[] getExtendsListTypes() { return CachedValuesManager.getManager(getProject()).getCachedValue(this, new CachedValueProvider<PsiClassType[]>() { @Override public Result<PsiClassType[]> compute() { return Result.create(GrClassImplUtil.getExtendsListTypes(GrTypeDefinitionImpl.this), PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT); } }); } @NotNull public PsiClassType[] getImplementsListTypes() { return CachedValuesManager.getManager(getProject()).getCachedValue(this, new CachedValueProvider<PsiClassType[]>() { @Override public Result<PsiClassType[]> compute() { return Result.create(GrClassImplUtil.getImplementsListTypes(GrTypeDefinitionImpl.this), PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT); } }); } @Nullable public PsiClass getSuperClass() { return GrClassImplUtil.getSuperClass(this); } public PsiClass[] getInterfaces() { return GrClassImplUtil.getInterfaces(this); } @NotNull public final PsiClass[] getSupers() { return GrClassImplUtil.getSupers(this); } @NotNull public PsiClassType[] getSuperTypes() { return GrClassImplUtil.getSuperTypes(this); } @NotNull public GrField[] getFields() { GrTypeDefinitionBody body = getBody(); if (body != null) { return body.getFields(); } return GrField.EMPTY_ARRAY; } @NotNull public GrClassInitializer[] getInitializersGroovy() { GrTypeDefinitionBody body = getBody(); if (body != null) { return body.getInitializers(); } return GrClassInitializer.EMPTY_ARRAY; } @NotNull public PsiMethod[] getMethods() { List<PsiMethod> cached = myMethods; if (cached == null) { cached = new ArrayList<PsiMethod>(); GrTypeDefinitionBody body = getBody(); if (body != null) { cached.addAll(body.getMethods()); } myMethods = cached; } List<PsiMethod> result = new ArrayList<PsiMethod>(cached); result.addAll(GrClassImplUtil.getDelegatedMethods(this)); return result.toArray(new PsiMethod[result.size()]); } @NotNull public GrMethod[] getGroovyMethods() { GrMethod[] cached = myGroovyMethods; if (cached == null) { GrTypeDefinitionBody body = getBody(); myGroovyMethods = cached = body != null ? body.getGroovyMethods() : GrMethod.EMPTY_ARRAY; } return cached; } public void subtreeChanged() { myMethods = null; myInnerClasses = null; myConstructors = null; myGroovyMethods = null; super.subtreeChanged(); } @NotNull public PsiMethod[] getConstructors() { GrMethod[] cached = myConstructors; if (cached == null) { List<GrMethod> result = new ArrayList<GrMethod>(); for (final PsiMethod method : getMethods()) { if (method.isConstructor()) { result.add((GrMethod)method); } } myConstructors = cached = result.toArray(new GrMethod[result.size()]); } return cached; } @NotNull public PsiClass[] getInnerClasses() { PsiClass[] inners = myInnerClasses; if (inners == null) { final GrTypeDefinitionBody body = getBody(); myInnerClasses = inners = body != null ? body.getInnerClasses() : PsiClass.EMPTY_ARRAY; } return inners; } @NotNull public PsiClassInitializer[] getInitializers() { return PsiClassInitializer.EMPTY_ARRAY; } @NotNull public PsiField[] getAllFields() { return GrClassImplUtil.getAllFields(this); } @NotNull public PsiMethod[] getAllMethods() { return GrClassImplUtil.getAllMethods(this); } @NotNull public PsiClass[] getAllInnerClasses() { return PsiClassImplUtil.getAllInnerClasses(this); } @Nullable public PsiField findFieldByName(String name, boolean checkBases) { return GrClassImplUtil.findFieldByName(this, name, checkBases); } @Nullable public PsiMethod findMethodBySignature(PsiMethod patternMethod, boolean checkBases) { return GrClassImplUtil.findMethodBySignature(this, patternMethod, checkBases); } @NotNull public PsiMethod[] findMethodsBySignature(PsiMethod patternMethod, boolean checkBases) { return GrClassImplUtil.findMethodsBySignature(this, patternMethod, checkBases); } @NotNull public PsiMethod[] findCodeMethodsBySignature(PsiMethod patternMethod, boolean checkBases) { return GrClassImplUtil.findCodeMethodsBySignature(this, patternMethod, checkBases); } @NotNull public PsiMethod[] findMethodsByName(@NonNls String name, boolean checkBases) { return GrClassImplUtil.findMethodsByName(this, name, checkBases); } @NotNull public PsiMethod[] findCodeMethodsByName(@NonNls String name, boolean checkBases) { return GrClassImplUtil.findCodeMethodsByName(this, name, checkBases); } @NotNull public List<Pair<PsiMethod, PsiSubstitutor>> findMethodsAndTheirSubstitutorsByName(String name, boolean checkBases) { return GrClassImplUtil.findMethodsAndTheirSubstitutorsByName(this, name, checkBases); } @NotNull public List<Pair<PsiMethod, PsiSubstitutor>> getAllMethodsAndTheirSubstitutors() { return GrClassImplUtil.getAllMethodsAndTheirSubstitutors(this); } @Nullable public PsiClass findInnerClassByName(String name, boolean checkBases) { return null; } @Nullable public PsiElement getLBrace() { final GrTypeDefinitionBody body = getBody(); return body == null ? null : body.getLBrace(); } @Nullable public PsiElement getRBrace() { final GrTypeDefinitionBody body = getBody(); return body == null ? null : body.getRBrace(); } public boolean isAnonymous() { return false; } @Nullable public PsiIdentifier getNameIdentifier() { return PsiUtil.getJavaNameIdentifier(this); } @Nullable public PsiElement getScope() { return null; } public boolean isInheritor(@NotNull PsiClass baseClass, boolean checkDeep) { return InheritanceImplUtil.isInheritor(this, baseClass, checkDeep); } public boolean isInheritorDeep(PsiClass baseClass, @Nullable PsiClass classToByPass) { return InheritanceImplUtil.isInheritorDeep(this, baseClass, classToByPass); } @Nullable public PsiClass getContainingClass() { PsiElement parent = getParent(); if (parent instanceof GrTypeDefinitionBody) { final PsiElement pparent = parent.getParent(); if (pparent instanceof PsiClass) { return (PsiClass)pparent; } } return null; } @NotNull public Collection<HierarchicalMethodSignature> getVisibleSignatures() { return PsiSuperMethodImplUtil.getVisibleSignatures(this); } public PsiElement setName(@NonNls @NotNull String name) throws IncorrectOperationException { boolean renameFile = isRenameFileOnClassRenaming(); final String oldName = getName(); PsiImplUtil.setName(name, getNameIdentifierGroovy()); for (PsiMethod method : getMethods()) { if (method.isConstructor() && method.getName().equals(oldName)) method.setName(name); } if (renameFile) { final GroovyFileBase file = (GroovyFileBase)getContainingFile(); final VirtualFile virtualFile = file.getVirtualFile(); final String ext; if (virtualFile != null) { ext = virtualFile.getExtension(); } else { ext = GroovyFileType.GROOVY_FILE_TYPE.getDefaultExtension(); } file.setName(name + "." + ext); } return this; } @Nullable public GrModifierList getModifierList() { return getStubOrPsiChild(GroovyElementTypes.MODIFIERS); } public boolean hasModifierProperty(@NonNls @NotNull String name) { PsiModifierList modifierList = getModifierList(); return modifierList != null && modifierList.hasModifierProperty(name); } @Nullable public GrDocComment getDocComment() { return GrDocCommentUtil.findDocComment(this); } public boolean isDeprecated() { return com.intellij.psi.impl.PsiImplUtil.isDeprecatedByDocTag(this) || com.intellij.psi.impl.PsiImplUtil.isDeprecatedByAnnotation(this); } public boolean hasTypeParameters() { return getTypeParameters().length > 0; } @Nullable public GrTypeParameterList getTypeParameterList() { return getStubOrPsiChild(GroovyElementTypes.TYPE_PARAMETER_LIST); } @NotNull public GrTypeParameter[] getTypeParameters() { final GrTypeParameterList list = getTypeParameterList(); if (list != null) { return list.getTypeParameters(); } return GrTypeParameter.EMPTY_ARRAY; } @Override protected boolean isVisibilitySupported() { return true; } @Nullable public Icon getIcon(int flags) { Icon icon = getIconInner(); final boolean isLocked = (flags & ICON_FLAG_READ_STATUS) != 0 && !isWritable(); RowIcon rowIcon = ElementBase.createLayeredIcon(icon, ElementPresentationUtil.getFlags(this, isLocked)); if ((flags & ICON_FLAG_VISIBILITY) != 0) { VisibilityIcons.setVisibilityIcon(getModifierList(), rowIcon); } return rowIcon; } private Icon getIconInner() { if (isAnnotationType()) return GroovyIcons.ANNOTATION_TYPE; if (isInterface()) return GroovyIcons.INTERFACE; if (isEnum()) return GroovyIcons.ENUM; if (hasModifierProperty(PsiModifier.ABSTRACT)) return GroovyIcons.ABSTRACT_CLASS; return GroovyIcons.CLASS; } private boolean isRenameFileOnClassRenaming() { final PsiFile file = getContainingFile(); if (!(file instanceof GroovyFile)) return false; final GroovyFile groovyFile = (GroovyFile)file; if (groovyFile.isScript()) return false; final String name = getName(); final VirtualFile vFile = groovyFile.getVirtualFile(); return vFile != null && name != null && name.equals(vFile.getNameWithoutExtension()); } @Nullable public PsiElement getOriginalElement() { return PsiImplUtil.getOriginalElement(this, getContainingFile()); } public PsiElement addAfter(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException { if (anchor == null) { return add(element); } final GrTypeDefinitionBody body = getBody(); if (anchor.getParent() == body) { final PsiElement nextChild = anchor.getNextSibling(); if (nextChild == null) { add(element); return element; } ASTNode node = element.getNode(); assert node != null; //body.getNode().addLeaf(GroovyElementTypes.mNLS, "\n", nextChild.getNode()); return body.addBefore(element, nextChild); } else { return super.addAfter(element, anchor); } } public PsiElement addBefore(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException { if (anchor == null) { add(element); return element; } final GrTypeDefinitionBody body = getBody(); if (anchor.getParent() != body) { return super.addBefore(element, anchor); } ASTNode node = element.getNode(); assert node != null; final ASTNode bodyNode = body.getNode(); final ASTNode anchorNode = anchor.getNode(); bodyNode.addChild(node, anchorNode); bodyNode.addLeaf(GroovyTokenTypes.mWS, " ", node); bodyNode.addLeaf(GroovyTokenTypes.mNLS, "\n", anchorNode); return element; } public PsiElement add(@NotNull PsiElement psiElement) throws IncorrectOperationException { final GrTypeDefinitionBody body = getBody(); if (body == null) throw new IncorrectOperationException("Class must have body"); final PsiElement lBrace = body.getLBrace(); if (lBrace == null) throw new IncorrectOperationException("No left brace"); PsiMember member = getAnyMember(psiElement); PsiElement anchor = member != null ? getDefaultAnchor(body, member) : null; if (anchor == null) { anchor = lBrace.getNextSibling(); } if (anchor != null) { ASTNode node = anchor.getNode(); assert node != null; if (GroovyElementTypes.mSEMI.equals(node.getElementType())) { anchor = anchor.getNextSibling(); } psiElement = body.addBefore(psiElement, anchor); } else { body.add(psiElement); } return psiElement; } @Nullable private static PsiMember getAnyMember(@Nullable PsiElement psiElement) { if (psiElement instanceof PsiMember) { return (PsiMember)psiElement; } if (psiElement instanceof GrVariableDeclaration) { final GrMember[] members = ((GrVariableDeclaration)psiElement).getMembers(); if (members.length > 0) { return members[0]; } } return null; } @Nullable private PsiElement getDefaultAnchor(GrTypeDefinitionBody body, PsiMember member) { CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(getProject()); int order = ClassElement.getMemberOrderWeight(member, settings); if (order < 0) return null; PsiElement lastMember = null; for (PsiElement child = body.getFirstChild(); child != null; child = child.getNextSibling()) { int order1 = ClassElement.getMemberOrderWeight(getAnyMember(child), settings); if (order1 < 0) continue; if (order1 > order) { final PsiElement lBrace = body.getLBrace(); if (lastMember != null) { PsiElement nextSibling = lastMember.getNextSibling(); while (nextSibling instanceof LeafPsiElement && (nextSibling.getText().equals(",") || nextSibling.getText().equals(";"))) { nextSibling = nextSibling.getNextSibling(); } return nextSibling == null && lBrace != null ? PsiUtil.skipWhitespaces(lBrace.getNextSibling(), true) : nextSibling; } else if (lBrace != null) { return PsiUtil.skipWhitespaces(lBrace.getNextSibling(), true); } } lastMember = child; } return body.getRBrace(); } public <T extends GrMembersDeclaration> T addMemberDeclaration(@NotNull T decl, PsiElement anchorBefore) throws IncorrectOperationException { if (anchorBefore == null) { return (T)add(decl); } GrTypeDefinitionBody body = getBody(); if (body == null) throw new IncorrectOperationException("Type definition without a body"); // ASTNode anchorNode; // anchorNode = anchorBefore.getNode(); // ASTNode bodyNode = body.getNode(); decl = (T)body.addBefore(decl, anchorBefore); // bodyNode.addLeaf(GroovyTokenTypes.mWS, " ", decl.getNode()); //add whitespaces before and after to hack over incorrect auto reformat // bodyNode.addLeaf(GroovyTokenTypes.mWS, " ", anchorNode); return decl; } }
cache groovy class interfaces
plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/typedef/GrTypeDefinitionImpl.java
cache groovy class interfaces
Java
apache-2.0
83689e2a40a3e5069c7fb02a78e3eff8ab3a9ada
0
allotria/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,xfournet/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,allotria/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,xfournet/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,allotria/intellij-community
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInsight.editorActions; import com.intellij.application.options.editor.WebEditorOptions; import com.intellij.codeInsight.completion.XmlTagInsertHandler; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.codeInsight.lookup.impl.LookupImpl; import com.intellij.codeInspection.htmlInspections.RenameTagBeginOrEndIntentionAction; import com.intellij.lang.Language; import com.intellij.lang.html.HTMLLanguage; import com.intellij.lang.injection.InjectedLanguageManager; import com.intellij.lang.xhtml.XHTMLLanguage; import com.intellij.lang.xml.XMLLanguage; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandEvent; import com.intellij.openapi.command.CommandListener; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.undo.UndoManager; import com.intellij.openapi.components.NamedComponent; import com.intellij.openapi.diagnostic.Attachment; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.event.DocumentListener; import com.intellij.openapi.editor.event.EditorFactoryAdapter; import com.intellij.openapi.editor.event.EditorFactoryEvent; import com.intellij.openapi.editor.ex.DocumentEx; import com.intellij.openapi.editor.impl.EditorImpl; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Couple; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.core.impl.PomModelImpl; import com.intellij.psi.*; import com.intellij.psi.impl.PsiDocumentManagerBase; import com.intellij.psi.impl.source.tree.TreeUtil; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; import com.intellij.psi.templateLanguages.TemplateLanguage; import com.intellij.psi.xml.XmlTokenType; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import com.intellij.xml.util.HtmlUtil; import com.intellij.xml.util.XmlUtil; import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Set; /** * @author Dennis.Ushakov */ public class XmlTagNameSynchronizer implements NamedComponent, CommandListener { private static final Logger LOG = Logger.getInstance(XmlTagNameSynchronizer.class); private static final Set<Language> SUPPORTED_LANGUAGES = ContainerUtil.set(HTMLLanguage.INSTANCE, XMLLanguage.INSTANCE, XHTMLLanguage.INSTANCE); private static final Key<TagNameSynchronizer> SYNCHRONIZER_KEY = Key.create("tag_name_synchronizer"); private final FileDocumentManager myFileDocumentManager; public XmlTagNameSynchronizer(EditorFactory editorFactory, FileDocumentManager manager, CommandProcessor processor) { myFileDocumentManager = manager; editorFactory.addEditorFactoryListener(new EditorFactoryAdapter() { @Override public void editorCreated(@NotNull EditorFactoryEvent event) { installSynchronizer(event.getEditor()); } }, ApplicationManager.getApplication()); processor.addCommandListener(this); } private void installSynchronizer(final Editor editor) { final Project project = editor.getProject(); if (project == null) return; final Document document = editor.getDocument(); final VirtualFile file = myFileDocumentManager.getFile(document); final Language language = findXmlLikeLanguage(project, file); if (language != null) new TagNameSynchronizer(editor, project, language); } private static Language findXmlLikeLanguage(Project project, VirtualFile file) { final PsiFile psiFile = file != null && file.isValid() ? PsiManager.getInstance(project).findFile(file) : null; if (psiFile != null) { for (Language language : psiFile.getViewProvider().getLanguages()) { if ((ContainerUtil.find(SUPPORTED_LANGUAGES, language::isKindOf) != null || HtmlUtil.supportsXmlTypedHandlers(psiFile)) && !(language instanceof TemplateLanguage)) { return language; } } } return null; } @NotNull @Override public String getComponentName() { return "XmlTagNameSynchronizer"; } @NotNull private static TagNameSynchronizer[] findSynchronizers(final Document document) { if (!WebEditorOptions.getInstance().isSyncTagEditing() || document == null) return TagNameSynchronizer.EMPTY; final Editor[] editors = EditorFactory.getInstance().getEditors(document); return ContainerUtil.mapNotNull(editors, editor -> editor.getUserData(SYNCHRONIZER_KEY), TagNameSynchronizer.EMPTY); } @Override public void beforeCommandFinished(CommandEvent event) { final TagNameSynchronizer[] synchronizers = findSynchronizers(event.getDocument()); for (TagNameSynchronizer synchronizer : synchronizers) { synchronizer.beforeCommandFinished(); } } private static class TagNameSynchronizer implements DocumentListener { public static final TagNameSynchronizer[] EMPTY = new TagNameSynchronizer[0]; private final PsiDocumentManagerBase myDocumentManager; private final Language myLanguage; private enum State {INITIAL, TRACKING, APPLYING} private final Editor myEditor; private State myState = State.INITIAL; private final List<Couple<RangeMarker>> myMarkers = new SmartList<>(); public TagNameSynchronizer(Editor editor, Project project, Language language) { myEditor = editor; myLanguage = language; final Disposable disposable = ((EditorImpl)editor).getDisposable(); final Document document = editor.getDocument(); document.addDocumentListener(this, disposable); editor.putUserData(SYNCHRONIZER_KEY, this); myDocumentManager = (PsiDocumentManagerBase)PsiDocumentManager.getInstance(project); } @Override public void beforeDocumentChange(DocumentEvent event) { if (!WebEditorOptions.getInstance().isSyncTagEditing()) return; final Document document = event.getDocument(); if (myState == State.APPLYING || UndoManager.getInstance(myEditor.getProject()).isUndoInProgress() || !PomModelImpl.isAllowPsiModification() || ((DocumentEx)document).isInBulkUpdate()) { return; } final int offset = event.getOffset(); final int oldLength = event.getOldLength(); final CharSequence fragment = event.getNewFragment(); final int newLength = event.getNewLength(); if (document.getUserData(XmlTagInsertHandler.ENFORCING_TAG) == Boolean.TRUE) { // xml completion inserts extra space after tag name to ensure correct parsing // we need to ignore it return; } for (int i = 0; i < newLength; i++) { if (!XmlUtil.isValidTagNameChar(fragment.charAt(i))) { clearMarkers(); return; } } if (myState == State.INITIAL) { final PsiFile file = myDocumentManager.getPsiFile(document); if (file == null || myDocumentManager.getSynchronizer().isInSynchronization(document)) return; final SmartList<RangeMarker> leaders = new SmartList<>(); for (Caret caret : myEditor.getCaretModel().getAllCarets()) { final RangeMarker leader = createTagNameMarker(caret); if (leader == null) { for (RangeMarker marker : leaders) { marker.dispose(); } return; } leader.setGreedyToLeft(true); leader.setGreedyToRight(true); leaders.add(leader); } if (leaders.isEmpty()) return; if (myDocumentManager.isUncommited(document)) { myDocumentManager.commitDocument(document); } for (RangeMarker leader : leaders) { final RangeMarker support = findSupport(leader, file, document); if (support == null) { clearMarkers(); return; } support.setGreedyToLeft(true); support.setGreedyToRight(true); myMarkers.add(Couple.of(leader, support)); } if (!fitsInMarker(offset, oldLength)) { clearMarkers(); return; } myState = State.TRACKING; } if (myMarkers.isEmpty()) return; boolean fitsInMarker = fitsInMarker(offset, oldLength); if (!fitsInMarker || myMarkers.size() != myEditor.getCaretModel().getCaretCount()) { clearMarkers(); beforeDocumentChange(event); } } public boolean fitsInMarker(int offset, int oldLength) { boolean fitsInMarker = false; for (Couple<RangeMarker> leaderAndSupport : myMarkers) { final RangeMarker leader = leaderAndSupport.first; if (!leader.isValid()) { fitsInMarker = false; break; } fitsInMarker |= offset >= leader.getStartOffset() && offset + oldLength <= leader.getEndOffset(); } return fitsInMarker; } public void clearMarkers() { for (Couple<RangeMarker> leaderAndSupport : myMarkers) { leaderAndSupport.first.dispose(); leaderAndSupport.second.dispose(); } myMarkers.clear(); myState = State.INITIAL; } private RangeMarker createTagNameMarker(Caret caret) { final int offset = caret.getOffset(); final Document document = myEditor.getDocument(); final CharSequence sequence = document.getCharsSequence(); int start = -1; int end = -1; boolean seenColon = false; for (int i = offset - 1; i >= Math.max(0, offset - 50); i--) { try { final char c = sequence.charAt(i); if (c == '<' || (c == '/' && i > 0 && sequence.charAt(i - 1) == '<')) { start = i + 1; break; } if (!XmlUtil.isValidTagNameChar(c)) break; seenColon |= c == ':'; } catch (IndexOutOfBoundsException e) { LOG.error("incorrect offset:" + i + ", initial: " + offset, new Attachment("document.txt", sequence.toString())); return null; } } if (start < 0) return null; for (int i = offset; i < Math.min(document.getTextLength(), offset + 50); i++) { final char c = sequence.charAt(i); if (!XmlUtil.isValidTagNameChar(c) || (seenColon && c == ':')) { end = i; break; } seenColon |= c == ':'; } if (end < 0 || start > end) return null; return document.createRangeMarker(start, end, true); } public void beforeCommandFinished() { if (myMarkers.isEmpty()) return; myState = State.APPLYING; final Document document = myEditor.getDocument(); final Runnable apply = () -> { for (Couple<RangeMarker> couple : myMarkers) { final RangeMarker leader = couple.first; final RangeMarker support = couple.second; final String name = document.getText(new TextRange(leader.getStartOffset(), leader.getEndOffset())); if (document.getTextLength() >= support.getEndOffset() && !name.equals(document.getText(new TextRange(support.getStartOffset(), support.getEndOffset())))) { document.replaceString(support.getStartOffset(), support.getEndOffset(), name); } } }; ApplicationManager.getApplication().runWriteAction(() -> { final LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myEditor); if (lookup != null) { lookup.performGuardedChange(apply); } else { apply.run(); } }); myState = State.TRACKING; } private RangeMarker findSupport(RangeMarker leader, PsiFile file, Document document) { final int offset = leader.getStartOffset(); PsiElement element = InjectedLanguageUtil.findElementAtNoCommit(file, offset); PsiElement support = findSupportElement(element); if (support == null && file.getViewProvider() instanceof MultiplePsiFilesPerDocumentFileViewProvider) { element = file.getViewProvider().findElementAt(offset, myLanguage); support = findSupportElement(element); } if (support == null) return findSupportForTagList(leader, element, document); final TextRange range = support.getTextRange(); TextRange realRange = InjectedLanguageManager.getInstance(file.getProject()).injectedToHost(element.getContainingFile(), range); return document.createRangeMarker(realRange.getStartOffset(), realRange.getEndOffset(), true); } private static RangeMarker findSupportForTagList(RangeMarker leader, PsiElement element, Document document) { if (leader.getStartOffset() != leader.getEndOffset() || element == null) return null; PsiElement support = null; if ("<>".equals(element.getText())) { PsiElement last = element.getParent().getLastChild(); if ("</>".equals(last.getText())) { support = last; } } if ("</>".equals(element.getText())) { PsiElement first = element.getParent().getFirstChild(); if ("<>".equals(first.getText())) { support = first; } } if (support != null) { TextRange range = support.getTextRange(); return document.createRangeMarker(range.getEndOffset() - 1, range.getEndOffset() - 1, true); } return null; } private static PsiElement findSupportElement(PsiElement element) { if (element == null || TreeUtil.findSibling(element.getNode(), XmlTokenType.XML_TAG_END) == null) return null; PsiElement support = RenameTagBeginOrEndIntentionAction.findOtherSide(element, false); support = support == null || element == support ? RenameTagBeginOrEndIntentionAction.findOtherSide(element, true) : support; return support != null && StringUtil.equals(element.getText(), support.getText()) ? support : null; } } }
xml/impl/src/com/intellij/codeInsight/editorActions/XmlTagNameSynchronizer.java
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInsight.editorActions; import com.intellij.application.options.editor.WebEditorOptions; import com.intellij.codeInsight.completion.XmlTagInsertHandler; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.codeInsight.lookup.impl.LookupImpl; import com.intellij.codeInspection.htmlInspections.RenameTagBeginOrEndIntentionAction; import com.intellij.lang.Language; import com.intellij.lang.html.HTMLLanguage; import com.intellij.lang.injection.InjectedLanguageManager; import com.intellij.lang.xhtml.XHTMLLanguage; import com.intellij.lang.xml.XMLLanguage; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandEvent; import com.intellij.openapi.command.CommandListener; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.undo.UndoManager; import com.intellij.openapi.components.NamedComponent; import com.intellij.openapi.diagnostic.Attachment; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.event.DocumentListener; import com.intellij.openapi.editor.event.EditorFactoryAdapter; import com.intellij.openapi.editor.event.EditorFactoryEvent; import com.intellij.openapi.editor.ex.DocumentEx; import com.intellij.openapi.editor.impl.EditorImpl; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Couple; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.core.impl.PomModelImpl; import com.intellij.psi.*; import com.intellij.psi.impl.PsiDocumentManagerBase; import com.intellij.psi.impl.source.tree.TreeUtil; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; import com.intellij.psi.templateLanguages.TemplateLanguage; import com.intellij.psi.xml.XmlTokenType; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import com.intellij.xml.util.HtmlUtil; import com.intellij.xml.util.XmlUtil; import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Set; /** * @author Dennis.Ushakov */ public class XmlTagNameSynchronizer implements NamedComponent, CommandListener { private static final Logger LOG = Logger.getInstance(XmlTagNameSynchronizer.class); private static final Set<Language> SUPPORTED_LANGUAGES = ContainerUtil.set(HTMLLanguage.INSTANCE, XMLLanguage.INSTANCE, XHTMLLanguage.INSTANCE); private static final Key<TagNameSynchronizer> SYNCHRONIZER_KEY = Key.create("tag_name_synchronizer"); private final FileDocumentManager myFileDocumentManager; public XmlTagNameSynchronizer(EditorFactory editorFactory, FileDocumentManager manager, CommandProcessor processor) { myFileDocumentManager = manager; editorFactory.addEditorFactoryListener(new EditorFactoryAdapter() { @Override public void editorCreated(@NotNull EditorFactoryEvent event) { installSynchronizer(event.getEditor()); } }, ApplicationManager.getApplication()); processor.addCommandListener(this); } private void installSynchronizer(final Editor editor) { final Project project = editor.getProject(); if (project == null) return; final Document document = editor.getDocument(); final VirtualFile file = myFileDocumentManager.getFile(document); final Language language = findXmlLikeLanguage(project, file); if (language != null) new TagNameSynchronizer(editor, project, language); } private static Language findXmlLikeLanguage(Project project, VirtualFile file) { final PsiFile psiFile = file != null && file.isValid() ? PsiManager.getInstance(project).findFile(file) : null; if (psiFile != null) { for (Language language : psiFile.getViewProvider().getLanguages()) { if ((ContainerUtil.find(SUPPORTED_LANGUAGES, language::isKindOf) != null || HtmlUtil.supportsXmlTypedHandlers(psiFile)) && !(language instanceof TemplateLanguage)) { return language; } } } return null; } @NotNull @Override public String getComponentName() { return "XmlTagNameSynchronizer"; } @NotNull private static TagNameSynchronizer[] findSynchronizers(final Document document) { if (!WebEditorOptions.getInstance().isSyncTagEditing() || document == null) return TagNameSynchronizer.EMPTY; final Editor[] editors = EditorFactory.getInstance().getEditors(document); return ContainerUtil.mapNotNull(editors, editor -> editor.getUserData(SYNCHRONIZER_KEY), TagNameSynchronizer.EMPTY); } @Override public void beforeCommandFinished(CommandEvent event) { final TagNameSynchronizer[] synchronizers = findSynchronizers(event.getDocument()); for (TagNameSynchronizer synchronizer : synchronizers) { synchronizer.beforeCommandFinished(); } } private static class TagNameSynchronizer implements DocumentListener { public static final TagNameSynchronizer[] EMPTY = new TagNameSynchronizer[0]; private final PsiDocumentManagerBase myDocumentManager; private final Language myLanguage; private enum State {INITIAL, TRACKING, APPLYING} private final Editor myEditor; private State myState = State.INITIAL; private final List<Couple<RangeMarker>> myMarkers = new SmartList<>(); public TagNameSynchronizer(Editor editor, Project project, Language language) { myEditor = editor; myLanguage = language; final Disposable disposable = ((EditorImpl)editor).getDisposable(); final Document document = editor.getDocument(); document.addDocumentListener(this, disposable); editor.putUserData(SYNCHRONIZER_KEY, this); myDocumentManager = (PsiDocumentManagerBase)PsiDocumentManager.getInstance(project); } @Override public void beforeDocumentChange(DocumentEvent event) { if (!WebEditorOptions.getInstance().isSyncTagEditing()) return; final Document document = event.getDocument(); if (myState == State.APPLYING || UndoManager.getInstance(myEditor.getProject()).isUndoInProgress() || !PomModelImpl.isAllowPsiModification() || ((DocumentEx)document).isInBulkUpdate()) { return; } final int offset = event.getOffset(); final int oldLength = event.getOldLength(); final CharSequence fragment = event.getNewFragment(); final int newLength = event.getNewLength(); if (document.getUserData(XmlTagInsertHandler.ENFORCING_TAG) == Boolean.TRUE) { // xml completion inserts extra space after tag name to ensure correct parsing // we need to ignore it return; } for (int i = 0; i < newLength; i++) { if (!XmlUtil.isValidTagNameChar(fragment.charAt(i))) { clearMarkers(); return; } } if (myState == State.INITIAL) { final PsiFile file = myDocumentManager.getPsiFile(document); if (file == null || myDocumentManager.getSynchronizer().isInSynchronization(document)) return; final SmartList<RangeMarker> leaders = new SmartList<>(); for (Caret caret : myEditor.getCaretModel().getAllCarets()) { final RangeMarker leader = createTagNameMarker(caret); if (leader == null) { for (RangeMarker marker : leaders) { marker.dispose(); } return; } leader.setGreedyToLeft(true); leader.setGreedyToRight(true); leaders.add(leader); } if (leaders.isEmpty()) return; if (myDocumentManager.isUncommited(document)) { myDocumentManager.commitDocument(document); } for (RangeMarker leader : leaders) { final RangeMarker support = findSupport(leader, file, document); if (support == null) { clearMarkers(); return; } support.setGreedyToLeft(true); support.setGreedyToRight(true); myMarkers.add(Couple.of(leader, support)); } if (!fitsInMarker(offset, oldLength)) { clearMarkers(); return; } myState = State.TRACKING; } if (myMarkers.isEmpty()) return; boolean fitsInMarker = fitsInMarker(offset, oldLength); if (!fitsInMarker || myMarkers.size() != myEditor.getCaretModel().getCaretCount()) { clearMarkers(); beforeDocumentChange(event); } } public boolean fitsInMarker(int offset, int oldLength) { boolean fitsInMarker = false; for (Couple<RangeMarker> leaderAndSupport : myMarkers) { final RangeMarker leader = leaderAndSupport.first; if (!leader.isValid()) { fitsInMarker = false; break; } fitsInMarker |= offset >= leader.getStartOffset() && offset + oldLength <= leader.getEndOffset(); } return fitsInMarker; } public void clearMarkers() { for (Couple<RangeMarker> leaderAndSupport : myMarkers) { leaderAndSupport.first.dispose(); leaderAndSupport.second.dispose(); } myMarkers.clear(); myState = State.INITIAL; } private RangeMarker createTagNameMarker(Caret caret) { final int offset = caret.getOffset(); final Document document = myEditor.getDocument(); final CharSequence sequence = document.getCharsSequence(); int start = -1; int end = -1; boolean seenColon = false; for (int i = offset - 1; i >= Math.max(0, offset - 50); i--) { try { final char c = sequence.charAt(i); if (c == '<' || (c == '/' && i > 0 && sequence.charAt(i - 1) == '<')) { start = i + 1; break; } if (!XmlUtil.isValidTagNameChar(c)) break; seenColon |= c == ':'; } catch (IndexOutOfBoundsException e) { LOG.error("incorrect offset:" + i + ", initial: " + offset, new Attachment("document.txt", sequence.toString())); return null; } } if (start < 0) return null; for (int i = offset; i < Math.min(document.getTextLength(), offset + 50); i++) { final char c = sequence.charAt(i); if (!XmlUtil.isValidTagNameChar(c) || (seenColon && c == ':')) { end = i; break; } seenColon |= c == ':'; } if (end < 0 || start >= end) return null; return document.createRangeMarker(start, end, true); } public void beforeCommandFinished() { if (myMarkers.isEmpty()) return; myState = State.APPLYING; final Document document = myEditor.getDocument(); final Runnable apply = () -> { for (Couple<RangeMarker> couple : myMarkers) { final RangeMarker leader = couple.first; final RangeMarker support = couple.second; final String name = document.getText(new TextRange(leader.getStartOffset(), leader.getEndOffset())); if (document.getTextLength() >= support.getEndOffset() && !name.equals(document.getText(new TextRange(support.getStartOffset(), support.getEndOffset())))) { document.replaceString(support.getStartOffset(), support.getEndOffset(), name); } } }; ApplicationManager.getApplication().runWriteAction(() -> { final LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myEditor); if (lookup != null) { lookup.performGuardedChange(apply); } else { apply.run(); } }); myState = State.TRACKING; } private RangeMarker findSupport(RangeMarker leader, PsiFile file, Document document) { final int offset = leader.getStartOffset(); PsiElement element = InjectedLanguageUtil.findElementAtNoCommit(file, offset); PsiElement support = findSupportElement(element); if (support == null && file.getViewProvider() instanceof MultiplePsiFilesPerDocumentFileViewProvider) { element = file.getViewProvider().findElementAt(offset, myLanguage); support = findSupportElement(element); } if (support == null) return null; final TextRange range = support.getTextRange(); TextRange realRange = InjectedLanguageManager.getInstance(file.getProject()).injectedToHost(element.getContainingFile(), range); return document.createRangeMarker(realRange.getStartOffset(), realRange.getEndOffset(), true); } private static PsiElement findSupportElement(PsiElement element) { if (element == null || TreeUtil.findSibling(element.getNode(), XmlTokenType.XML_TAG_END) == null) return null; PsiElement support = RenameTagBeginOrEndIntentionAction.findOtherSide(element, false); support = support == null || element == support ? RenameTagBeginOrEndIntentionAction.findOtherSide(element, true) : support; return support != null && StringUtil.equals(element.getText(), support.getText()) ? support : null; } } }
jsx inner fragments support: sync editing
xml/impl/src/com/intellij/codeInsight/editorActions/XmlTagNameSynchronizer.java
jsx inner fragments support: sync editing
Java
apache-2.0
error: pathspec 'src/test/java/TestRoaringBitmap.java' did not match any file(s) known to git
79f8b7b89044f42481322cdae861b2f5c8ed7a0e
1
okrische/RoaringBitmap,okrische/RoaringBitmap,okrische/RoaringBitmap,RoaringBitmap/RoaringBitmap,lemire/RoaringBitmap,lemire/RoaringBitmap,RoaringBitmap/RoaringBitmap,lemire/RoaringBitmap,gssiyankai/RoaringBitmap,RoaringBitmap/RoaringBitmap,lemire/RoaringBitmap,gssiyankai/RoaringBitmap,RoaringBitmap/RoaringBitmap,gssiyankai/RoaringBitmap
import java.util.Arrays; import java.util.BitSet; import java.util.HashSet; import java.util.Vector; import junit.framework.Assert; import me.lemire.roaringbitmap.ArrayContainer; import me.lemire.roaringbitmap.BitmapContainer; import me.lemire.roaringbitmap.ContainerFactory; import me.lemire.roaringbitmap.RoaringBitmap; import me.lemire.roaringbitmap.Util; import org.junit.Test; /** * */ @SuppressWarnings({ "static-method", "deprecation" }) public class TestRoaringBitmap { @Test public void ANDNOTtest() { RoaringBitmap rr = new RoaringBitmap(); for (int k = 4000; k < 4256; ++k) rr.add(k); for (int k = 65536; k < 65536 + 4000; ++k) rr.add(k); for (int k = 3 * 65536; k < 3 * 65536 + 9000; ++k) rr.add(k); for (int k = 4 * 65535; k < 4 * 65535 + 7000; ++k) rr.add(k); for (int k = 6 * 65535; k < 6 * 65535 + 10000; ++k) rr.add(k); for (int k = 8 * 65535; k < 8 * 65535 + 1000; ++k) rr.add(k); for (int k = 9 * 65535; k < 9 * 65535 + 30000; ++k) rr.add(k); RoaringBitmap rr2 = new RoaringBitmap(); for (int k = 4000; k < 4256; ++k) { rr2.add(k); } for (int k = 65536; k < 65536 + 4000; ++k) { rr2.add(k); } for (int k = 3 * 65536 + 2000; k < 3 * 65536 + 6000; ++k) { rr2.add(k); } for (int k = 6 * 65535; k < 6 * 65535 + 1000; ++k) { rr2.add(k); } for (int k = 7 * 65535; k < 7 * 65535 + 1000; ++k) { rr2.add(k); } for (int k = 10 * 65535; k < 10 * 65535 + 5000; ++k) { rr2.add(k); } RoaringBitmap correct = RoaringBitmap.andNot(rr, rr2); rr.andNot(rr2); Assert.assertTrue(correct.equals(rr)); } @Test public void andnottest4() { RoaringBitmap rb = new RoaringBitmap(); RoaringBitmap rb2 = new RoaringBitmap(); for (int i = 0; i < 200000; i += 4) rb2.add(i); for (int i = 200000; i < 400000; i += 14) rb2.add(i); rb2.getCardinality(); // check or against an empty bitmap RoaringBitmap andNotresult = RoaringBitmap.andNot( rb, rb2); RoaringBitmap off = RoaringBitmap.andNot(rb2, rb); Assert.assertEquals(rb, andNotresult); Assert.assertEquals(rb2, off); } @Test public void andtest() { RoaringBitmap rr = new RoaringBitmap(); for (int k = 0; k < 4000; ++k) { rr.add(k); } rr.add(100000); rr.add(110000); RoaringBitmap rr2 = new RoaringBitmap(); rr2.add(13); RoaringBitmap rrand = RoaringBitmap.and(rr, rr2); int[] array = rrand.toArray(); Assert.assertEquals(array[0], 13); } @Test public void ANDtest() { RoaringBitmap rr = new RoaringBitmap(); for (int k = 4000; k < 4256; ++k) rr.add(k); for (int k = 65536; k < 65536 + 4000; ++k) rr.add(k); for (int k = 3 * 65536; k < 3 * 65536 + 9000; ++k) rr.add(k); for (int k = 4 * 65535; k < 4 * 65535 + 7000; ++k) rr.add(k); for (int k = 6 * 65535; k < 6 * 65535 + 10000; ++k) rr.add(k); for (int k = 8 * 65535; k < 8 * 65535 + 1000; ++k) rr.add(k); for (int k = 9 * 65535; k < 9 * 65535 + 30000; ++k) rr.add(k); RoaringBitmap rr2 = new RoaringBitmap(); for (int k = 4000; k < 4256; ++k) { rr2.add(k); } for (int k = 65536; k < 65536 + 4000; ++k) { rr2.add(k); } for (int k = 3 * 65536 + 2000; k < 3 * 65536 + 6000; ++k) { rr2.add(k); } for (int k = 6 * 65535; k < 6 * 65535 + 1000; ++k) { rr2.add(k); } for (int k = 7 * 65535; k < 7 * 65535 + 1000; ++k) { rr2.add(k); } for (int k = 10 * 65535; k < 10 * 65535 + 5000; ++k) { rr2.add(k); } RoaringBitmap correct = RoaringBitmap.and(rr, rr2); rr.and(rr2); Assert.assertTrue(correct.equals(rr)); } @Test public void andtest2() { RoaringBitmap rr = new RoaringBitmap(); for (int k = 0; k < 4000; ++k) { rr.add(k); } rr.add(100000); rr.add(110000); RoaringBitmap rr2 = new RoaringBitmap(); rr2.add(13); RoaringBitmap rrand = RoaringBitmap.and(rr, rr2); int[] array = rrand.toArray(); Assert.assertEquals(array[0], 13); } @Test public void andtest3() { int[] arrayand = new int[11256]; int pos = 0; RoaringBitmap rr = new RoaringBitmap(); for (int k = 4000; k < 4256; ++k) rr.add(k); for (int k = 65536; k < 65536 + 4000; ++k) rr.add(k); for (int k = 3 * 65536; k < 3 * 65536 + 1000; ++k) rr.add(k); for (int k = 3 * 65536 + 1000; k < 3 * 65536 + 7000; ++k) rr.add(k); for (int k = 3 * 65536 + 7000; k < 3 * 65536 + 9000; ++k) rr.add(k); for (int k = 4 * 65536; k < 4 * 65536 + 7000; ++k) rr.add(k); for (int k = 6 * 65536; k < 6 * 65536 + 10000; ++k) rr.add(k); for (int k = 8 * 65536; k < 8 * 65536 + 1000; ++k) rr.add(k); for (int k = 9 * 65536; k < 9 * 65536 + 30000; ++k) rr.add(k); RoaringBitmap rr2 = new RoaringBitmap(); for (int k = 4000; k < 4256; ++k) { rr2.add(k); arrayand[pos++] = k; } for (int k = 65536; k < 65536 + 4000; ++k) { rr2.add(k); arrayand[pos++] = k; } for (int k = 3 * 65536 + 1000; k < 3 * 65536 + 7000; ++k) { rr2.add(k); arrayand[pos++] = k; } for (int k = 6 * 65536; k < 6 * 65536 + 1000; ++k) { rr2.add(k); arrayand[pos++] = k; } for (int k = 7 * 65536; k < 7 * 65536 + 1000; ++k) { rr2.add(k); } for (int k = 10 * 65536; k < 10 * 65536 + 5000; ++k) { rr2.add(k); } RoaringBitmap rrand = RoaringBitmap.and(rr, rr2); int[] arrayres = rrand.toArray(); for (int i = 0; i < arrayres.length; i++) if (arrayres[i] != arrayand[i]) System.out.println(arrayres[i]); Assert.assertTrue(Arrays.equals(arrayand, arrayres)); } @Test public void andtest4() { RoaringBitmap rb = new RoaringBitmap(); RoaringBitmap rb2 = new RoaringBitmap(); for (int i = 0; i < 200000; i += 4) rb2.add(i); for (int i = 200000; i < 400000; i += 14) rb2.add(i); // check or against an empty bitmap RoaringBitmap andresult = RoaringBitmap .and(rb, rb2); RoaringBitmap off = RoaringBitmap.and(rb2, rb); Assert.assertTrue(andresult.equals(off)); Assert.assertEquals(0, andresult.getCardinality()); for (int i = 500000; i < 600000; i += 14) rb.add(i); for (int i = 200000; i < 400000; i += 3) rb2.add(i); // check or against an empty bitmap RoaringBitmap andresult2 = RoaringBitmap.and(rb, rb2); Assert.assertEquals(0, andresult.getCardinality()); Assert.assertEquals(0, andresult2.getCardinality()); for (int i = 0; i < 200000; i += 4) rb.add(i); for (int i = 200000; i < 400000; i += 14) rb.add(i); Assert.assertEquals(0, andresult.getCardinality()); } @Test public void ArrayContainerCardinalityTest() { ArrayContainer ac = new ArrayContainer(); for (short k = 0; k < 100; ++k) { ac.add(k); Assert.assertEquals(ac.getCardinality(), k + 1); } for (short k = 0; k < 100; ++k) { ac.add(k); Assert.assertEquals(ac.getCardinality(), 100); } } @Test public void arraytest() { ArrayContainer rr = new ArrayContainer(); rr.add((short) 110); rr.add((short) 114); rr.add((short) 115); short[] array = new short[3]; int pos = 0; for (short i : rr) array[pos++] = i; Assert.assertEquals(array[0], (short) 110); Assert.assertEquals(array[1], (short) 114); Assert.assertEquals(array[2], (short) 115); } @Test public void basictest() { RoaringBitmap rr = new RoaringBitmap(); int[] a = new int[4002]; int pos = 0; for (int k = 0; k < 4000; ++k) { rr.add(k); a[pos++] = k; } rr.add(100000); a[pos++] = 100000; rr.add(110000); a[pos++] = 110000; int[] array = rr.toArray(); pos = 0; for (int i = 0; i < array.length; i++) if (array[i] != a[i]) System.out.println("rr : " + array[i] + " a : " + a[i]); Assert.assertTrue(Arrays.equals(array, a)); } @Test public void BitmapContainerCardinalityTest() { BitmapContainer ac = new BitmapContainer(); for (short k = 0; k < 100; ++k) { ac.add(k); Assert.assertEquals(ac.getCardinality(), k + 1); } for (short k = 0; k < 100; ++k) { ac.add(k); Assert.assertEquals(ac.getCardinality(), 100); } } @Test public void bitmaptest() { BitmapContainer rr = new BitmapContainer(); rr.add((short) 110); rr.add((short) 114); rr.add((short) 115); short[] array = new short[3]; int pos = 0; for (short i : rr) array[pos++] = i; Assert.assertEquals(array[0], (short) 110); Assert.assertEquals(array[1], (short) 114); Assert.assertEquals(array[2], (short) 115); } @Test public void cardinalityTest() { final int N = 1024; for (int gap = 7; gap < 100000; gap *= 10) { for (int offset = 2; offset <= 1024; offset *= 2) { RoaringBitmap rb = new RoaringBitmap(); // check the add of new values for (int k = 0; k < N; k++) { rb.add(k * gap); Assert.assertEquals( rb.getCardinality(), k + 1); } Assert.assertEquals(rb.getCardinality(), N); // check the add of existing values for (int k = 0; k < N; k++) { rb.add(k * gap); Assert.assertEquals( rb.getCardinality(), N); } RoaringBitmap rb2 = new RoaringBitmap(); for (int k = 0; k < N; k++) { rb2.add(k * gap * offset); Assert.assertEquals( rb2.getCardinality(), k + 1); } Assert.assertEquals(rb2.getCardinality(), N); for (int k = 0; k < N; k++) { rb2.add(k * gap * offset); Assert.assertEquals( rb2.getCardinality(), N); } Assert.assertEquals( RoaringBitmap.and(rb, rb2) .getCardinality(), N / offset); Assert.assertEquals( RoaringBitmap.or(rb, rb2) .getCardinality(), 2 * N - N / offset); Assert.assertEquals( RoaringBitmap.xor(rb, rb2) .getCardinality(), 2 * N - 2 * N / offset); } } } @Test public void clearTest() { RoaringBitmap rb = new RoaringBitmap(); for (int i = 0; i < 200000; i += 7) // dense rb.add(i); for (int i = 200000; i < 400000; i += 177) // sparse rb.add(i); RoaringBitmap rb2 = new RoaringBitmap(); RoaringBitmap rb3 = new RoaringBitmap(); for (int i = 0; i < 200000; i += 4) rb2.add(i); for (int i = 200000; i < 400000; i += 14) rb2.add(i); rb.clear(); Assert.assertEquals(0, rb.getCardinality()); Assert.assertTrue(0 != rb2.getCardinality()); rb.add(4); rb3.add(4); RoaringBitmap andresult = RoaringBitmap .and(rb, rb2); RoaringBitmap orresult = RoaringBitmap.or(rb, rb2); Assert.assertEquals(1, andresult.getCardinality()); Assert.assertEquals(rb2.getCardinality(), orresult.getCardinality()); for (int i = 0; i < 200000; i += 4) { rb.add(i); rb3.add(i); } for (int i = 200000; i < 400000; i += 114) { rb.add(i); rb3.add(i); } int[] arrayrr = rb.toArray(); int[] arrayrr3 = rb3.toArray(); Assert.assertTrue(Arrays.equals(arrayrr, arrayrr3)); } @Test public void ContainerFactory() { BitmapContainer bc1, bc2, bc3; ArrayContainer ac1, ac2, ac3; bc1 = new BitmapContainer(); bc2 = new BitmapContainer(); bc3 = new BitmapContainer(); ac1 = new ArrayContainer(); ac2 = new ArrayContainer(); ac3 = new ArrayContainer(); for (short i = 0; i < 5000; i++) bc1.add((short) (i * 70)); for (short i = 0; i < 5000; i++) bc2.add((short) (i * 70)); for (short i = 0; i < 5000; i++) bc3.add((short) (i * 70)); for (short i = 0; i < 4000; i++) ac1.add((short) (i * 50)); for (short i = 0; i < 4000; i++) ac2.add((short) (i * 50)); for (short i = 0; i < 4000; i++) ac3.add((short) (i * 50)); BitmapContainer rbc; rbc = ContainerFactory.transformToBitmapContainer(ac1.clone()); Assert.assertTrue(validate(rbc, ac1)); rbc = ContainerFactory.transformToBitmapContainer(ac2.clone()); Assert.assertTrue(validate(rbc, ac2)); rbc = ContainerFactory.transformToBitmapContainer(ac3.clone()); Assert.assertTrue(validate(rbc, ac3)); } @Test public void ortest() { RoaringBitmap rr = new RoaringBitmap(); for (int k = 0; k < 4000; ++k) { rr.add(k); } rr.add(100000); rr.add(110000); RoaringBitmap rr2 = new RoaringBitmap(); for (int k = 0; k < 4000; ++k) { rr2.add(k); } RoaringBitmap rror = RoaringBitmap.or(rr, rr2); int[] array = rror.toArray(); int[] arrayrr = rr.toArray(); Assert.assertTrue(Arrays.equals(array, arrayrr)); } @Test public void ORtest() { RoaringBitmap rr = new RoaringBitmap(); for (int k = 4000; k < 4256; ++k) rr.add(k); for (int k = 65536; k < 65536 + 4000; ++k) rr.add(k); for (int k = 3 * 65536; k < 3 * 65536 + 9000; ++k) rr.add(k); for (int k = 4 * 65535; k < 4 * 65535 + 7000; ++k) rr.add(k); for (int k = 6 * 65535; k < 6 * 65535 + 10000; ++k) rr.add(k); for (int k = 8 * 65535; k < 8 * 65535 + 1000; ++k) rr.add(k); for (int k = 9 * 65535; k < 9 * 65535 + 30000; ++k) rr.add(k); RoaringBitmap rr2 = new RoaringBitmap(); for (int k = 4000; k < 4256; ++k) { rr2.add(k); } for (int k = 65536; k < 65536 + 4000; ++k) { rr2.add(k); } for (int k = 3 * 65536 + 2000; k < 3 * 65536 + 6000; ++k) { rr2.add(k); } for (int k = 6 * 65535; k < 6 * 65535 + 1000; ++k) { rr2.add(k); } for (int k = 7 * 65535; k < 7 * 65535 + 1000; ++k) { rr2.add(k); } for (int k = 10 * 65535; k < 10 * 65535 + 5000; ++k) { rr2.add(k); } RoaringBitmap correct = RoaringBitmap.or(rr, rr2); rr.or(rr2); Assert.assertTrue(correct.equals(rr)); } @Test public void ortest2() { int[] arrayrr = new int[4000 + 4000 + 2]; int pos = 0; RoaringBitmap rr = new RoaringBitmap(); for (int k = 0; k < 4000; ++k) { rr.add(k); arrayrr[pos++] = k; } rr.add(100000); rr.add(110000); RoaringBitmap rr2 = new RoaringBitmap(); for (int k = 4000; k < 8000; ++k) { rr2.add(k); arrayrr[pos++] = k; } arrayrr[pos++] = 100000; arrayrr[pos++] = 110000; RoaringBitmap rror = RoaringBitmap.or(rr, rr2); int[] arrayor = rror.toArray(); Assert.assertTrue(Arrays.equals(arrayor, arrayrr)); } @Test public void ortest3() { HashSet<Integer> V1 = new HashSet<Integer>(); HashSet<Integer> V2 = new HashSet<Integer>(); RoaringBitmap rr = new RoaringBitmap(); RoaringBitmap rr2 = new RoaringBitmap(); // For the first 65536: rr2 has a bitmap container, and rr has // an array container. // We will check the union between a BitmapCintainer and an // arrayContainer for (int k = 0; k < 4000; ++k) { rr2.add(k); V1.add(new Integer(k)); } for (int k = 3500; k < 4500; ++k) { rr.add(k); V1.add(new Integer(k)); } for (int k = 4000; k < 65000; ++k) { rr2.add(k); V1.add(new Integer(k)); } // In the second node of each roaring bitmap, we have two bitmap // containers. // So, we will check the union between two BitmapContainers for (int k = 65536; k < 65536 + 10000; ++k) { rr.add(k); V1.add(new Integer(k)); } for (int k = 65536; k < 65536 + 14000; ++k) { rr2.add(k); V1.add(new Integer(k)); } // In the 3rd node of each Roaring Bitmap, we have an // ArrayContainer, so, we will try the union between two // ArrayContainers. for (int k = 4 * 65535; k < 4 * 65535 + 1000; ++k) { rr.add(k); V1.add(new Integer(k)); } for (int k = 4 * 65535; k < 4 * 65535 + 800; ++k) { rr2.add(k); V1.add(new Integer(k)); } // For the rest, we will check if the union will take them in // the result for (int k = 6 * 65535; k < 6 * 65535 + 1000; ++k) { rr.add(k); V1.add(new Integer(k)); } for (int k = 7 * 65535; k < 7 * 65535 + 2000; ++k) { rr2.add(k); V1.add(new Integer(k)); } RoaringBitmap rror = RoaringBitmap.or(rr, rr2); boolean valide = true; // Si tous les elements de rror sont dans V1 et que tous les // elements de // V1 sont dans rror(V2) // alors V1 == rror Object[] tab = V1.toArray(); Vector<Integer> vector = new Vector<Integer>(); for (int i = 0; i < tab.length; i++) vector.add((Integer) tab[i]); for (int i : rror.toArray()) { if (!vector.contains(new Integer(i))) { valide = false; } V2.add(new Integer(i)); } for (int i = 0; i < V1.size(); i++) if (!V2.contains(vector.elementAt(i))) { valide = false; } Assert.assertEquals(valide, true); } @Test public void ortest4() { RoaringBitmap rb = new RoaringBitmap(); RoaringBitmap rb2 = new RoaringBitmap(); for (int i = 0; i < 200000; i += 4) rb2.add(i); for (int i = 200000; i < 400000; i += 14) rb2.add(i); int rb2card = rb2.getCardinality(); // check or against an empty bitmap RoaringBitmap orresult = RoaringBitmap.or(rb, rb2); RoaringBitmap off = RoaringBitmap.or(rb2, rb); Assert.assertTrue(orresult.equals(off)); Assert.assertEquals(rb2card, orresult.getCardinality()); for (int i = 500000; i < 600000; i += 14) rb.add(i); for (int i = 200000; i < 400000; i += 3) rb2.add(i); // check or against an empty bitmap RoaringBitmap orresult2 = RoaringBitmap.or(rb, rb2); Assert.assertEquals(rb2card, orresult.getCardinality()); Assert.assertEquals(rb2.getCardinality() + rb.getCardinality(), orresult2.getCardinality()); } @Test public void randomTest() { final int N = 65536 * 16; for (int gap = 1; gap <= 65536; gap *= 2) { BitSet bs1 = new BitSet(); RoaringBitmap rb1 = new RoaringBitmap(); for (int x = 0; x <= N; ++x) { bs1.set(x); rb1.add(x); } for (int offset = 1; offset <= gap; offset *= 2) { BitSet bs2 = new BitSet(); RoaringBitmap rb2 = new RoaringBitmap(); for (int x = 0; x <= N; ++x) { bs2.set(x + offset); rb2.add(x + offset); } BitSet clonebs1; // testing AND clonebs1 = (BitSet) bs1.clone(); clonebs1.and(bs2); if (!equals(clonebs1, RoaringBitmap.and(rb1, rb2))) throw new RuntimeException("bug"); // testing OR clonebs1 = (BitSet) bs1.clone(); clonebs1.or(bs2); if (!equals(clonebs1, RoaringBitmap.or(rb1, rb2))) throw new RuntimeException("bug"); // testing XOR clonebs1 = (BitSet) bs1.clone(); clonebs1.xor(bs2); if (!equals(clonebs1, RoaringBitmap.xor(rb1, rb2))) throw new RuntimeException("bug"); // testing NOTAND clonebs1 = (BitSet) bs1.clone(); clonebs1.andNot(bs2); if (!equals(clonebs1, RoaringBitmap.andNot(rb1, rb2))) { throw new RuntimeException("bug"); } clonebs1 = (BitSet) bs2.clone(); clonebs1.andNot(bs1); if (!equals(clonebs1, RoaringBitmap.andNot(rb2, rb1))) { throw new RuntimeException("bug"); } } } } @Test public void removeSpeedyArrayTest() { RoaringBitmap rb = new RoaringBitmap(); for (int i = 0; i < 10000; i++) rb.add(i); for (int i = 10000; i > 0; i++) { rb.highlowcontainer.remove(Util.highbits(i)); Assert.assertEquals(rb.contains(i), false); } } @Test public void simplecardinalityTest() { final int N = 512; final int gap = 70; RoaringBitmap rb = new RoaringBitmap(); for (int k = 0; k < N; k++) { rb.add(k * gap); Assert.assertEquals(rb.getCardinality(), k + 1); } Assert.assertEquals(rb.getCardinality(), N); for (int k = 0; k < N; k++) { rb.add(k * gap); Assert.assertEquals(rb.getCardinality(), N); } } @Test public void XORtest() { RoaringBitmap rr = new RoaringBitmap(); for (int k = 4000; k < 4256; ++k) rr.add(k); for (int k = 65536; k < 65536 + 4000; ++k) rr.add(k); for (int k = 3 * 65536; k < 3 * 65536 + 9000; ++k) rr.add(k); for (int k = 4 * 65535; k < 4 * 65535 + 7000; ++k) rr.add(k); for (int k = 6 * 65535; k < 6 * 65535 + 10000; ++k) rr.add(k); for (int k = 8 * 65535; k < 8 * 65535 + 1000; ++k) rr.add(k); for (int k = 9 * 65535; k < 9 * 65535 + 30000; ++k) rr.add(k); RoaringBitmap rr2 = new RoaringBitmap(); for (int k = 4000; k < 4256; ++k) { rr2.add(k); } for (int k = 65536; k < 65536 + 4000; ++k) { rr2.add(k); } for (int k = 3 * 65536 + 2000; k < 3 * 65536 + 6000; ++k) { rr2.add(k); } for (int k = 6 * 65535; k < 6 * 65535 + 1000; ++k) { rr2.add(k); } for (int k = 7 * 65535; k < 7 * 65535 + 1000; ++k) { rr2.add(k); } for (int k = 10 * 65535; k < 10 * 65535 + 5000; ++k) { rr2.add(k); } RoaringBitmap correct = RoaringBitmap.xor(rr, rr2); rr.xor(rr2); Assert.assertTrue(correct.equals(rr)); } @Test public void xortest1() { HashSet<Integer> V1 = new HashSet<Integer>(); HashSet<Integer> V2 = new HashSet<Integer>(); RoaringBitmap rr = new RoaringBitmap(); RoaringBitmap rr2 = new RoaringBitmap(); // For the first 65536: rr2 has a bitmap container, and rr has // an array container. // We will check the union between a BitmapCintainer and an // arrayContainer for (int k = 0; k < 4000; ++k) { rr2.add(k); if (k < 3500) V1.add(new Integer(k)); } for (int k = 3500; k < 4500; ++k) { rr.add(k); } for (int k = 4000; k < 65000; ++k) { rr2.add(k); if (k >= 4500) V1.add(new Integer(k)); } // In the second node of each roaring bitmap, we have two bitmap // containers. // So, we will check the union between two BitmapContainers for (int k = 65536; k < 65536 + 30000; ++k) { rr.add(k); } for (int k = 65536; k < 65536 + 50000; ++k) { rr2.add(k); if (k >= 65536 + 30000) V1.add(new Integer(k)); } // In the 3rd node of each Roaring Bitmap, we have an // ArrayContainer. So, we will try the union between two // ArrayContainers. for (int k = 4 * 65535; k < 4 * 65535 + 1000; ++k) { rr.add(k); if (k >= 4 * 65535 + 800) V1.add(new Integer(k)); } for (int k = 4 * 65535; k < 4 * 65535 + 800; ++k) { rr2.add(k); } // For the rest, we will check if the union will take them in // the result for (int k = 6 * 65535; k < 6 * 65535 + 1000; ++k) { rr.add(k); V1.add(new Integer(k)); } for (int k = 7 * 65535; k < 7 * 65535 + 2000; ++k) { rr2.add(k); V1.add(new Integer(k)); } RoaringBitmap rrxor = RoaringBitmap.xor(rr, rr2); boolean valide = true; // Si tous les elements de rror sont dans V1 et que tous les // elements de // V1 sont dans rror(V2) // alors V1 == rror Object[] tab = V1.toArray(); Vector<Integer> vector = new Vector<Integer>(); for (int i = 0; i < tab.length; i++) vector.add((Integer) tab[i]); for (int i : rrxor.toArray()) { if (!vector.contains(new Integer(i))) { valide = false; } V2.add(new Integer(i)); } for (int i = 0; i < V1.size(); i++) if (!V2.contains(vector.elementAt(i))) { valide = false; } Assert.assertEquals(valide, true); } @Test public void xortest4() { RoaringBitmap rb = new RoaringBitmap(); RoaringBitmap rb2 = new RoaringBitmap(); for (int i = 0; i < 200000; i += 4) rb2.add(i); for (int i = 200000; i < 400000; i += 14) rb2.add(i); int rb2card = rb2.getCardinality(); // check or against an empty bitmap RoaringBitmap xorresult = RoaringBitmap .xor(rb, rb2); RoaringBitmap off = RoaringBitmap.or(rb2, rb); Assert.assertTrue(xorresult.equals(off)); Assert.assertEquals(rb2card, xorresult.getCardinality()); for (int i = 500000; i < 600000; i += 14) rb.add(i); for (int i = 200000; i < 400000; i += 3) rb2.add(i); // check or against an empty bitmap RoaringBitmap xorresult2 = RoaringBitmap.xor(rb, rb2); Assert.assertEquals(rb2card, xorresult.getCardinality()); Assert.assertEquals(rb2.getCardinality() + rb.getCardinality(), xorresult2.getCardinality()); } boolean validate(BitmapContainer bc, ArrayContainer ac) { // Checking the cardinalities of each container if (bc.getCardinality() != ac.getCardinality()) { System.out.println("cardinality differs"); return false; } // Checking that the two containers contain the same values int counter = 0; int i = bc.nextSetBit(0); while (i >= 0) { ++counter; if (!ac.contains((short) i)) { System.out.println("content differs"); System.out.println(bc); System.out.println(ac); return false; } i = bc.nextSetBit(i + 1); } // checking the cardinality of the BitmapContainer if (counter != bc.getCardinality()) return false; return true; } public static boolean equals(BitSet bs, RoaringBitmap rr) { int[] a = new int[bs.cardinality()]; int pos = 0; for (int x = bs.nextSetBit(0); x >= 0; x = bs.nextSetBit(x + 1)) a[pos++] = x; return Arrays.equals(rr.toArray(), a); } }
src/test/java/TestRoaringBitmap.java
Test file was renamed
src/test/java/TestRoaringBitmap.java
Test file was renamed
Java
apache-2.0
error: pathspec 'chapter_001/src/main/java/ru/job4j/package-info.java' did not match any file(s) known to git
14f99f358ebe9c377885f602d98c2ebe1997d0d5
1
NatashaPanchina/npanchina
/** * //TODO add comments. * *@author Natasha Panchina(panchinanata25@gmail.com) *@version $Id$ *@since 0.1 */ package ru.job4j;
chapter_001/src/main/java/ru/job4j/package-info.java
junit
chapter_001/src/main/java/ru/job4j/package-info.java
junit
Java
apache-2.0
error: pathspec 'src/main/java/enmasse/broker/forwarder/Forwarder.java' did not match any file(s) known to git
e6c95aac632a85ca77dc982e51a289ae55351da0
1
jenmalloy/enmasse,EnMasseProject/enmasse,EnMasseProject/enmasse,jenmalloy/enmasse,jenmalloy/enmasse,EnMasseProject/enmasse,jenmalloy/enmasse,jenmalloy/enmasse,EnMasseProject/enmasse,EnMasseProject/enmasse,EnMasseProject/enmasse,jenmalloy/enmasse,jenmalloy/enmasse,EnMasseProject/enmasse
/* * Copyright 2016 Red Hat Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package enmasse.broker.forwarder; import enmasse.discovery.Host; import io.vertx.core.Vertx; import io.vertx.proton.ProtonClient; import io.vertx.proton.ProtonConnection; import io.vertx.proton.ProtonDelivery; import io.vertx.proton.ProtonLinkOptions; import io.vertx.proton.ProtonReceiver; import io.vertx.proton.ProtonSender; import org.apache.qpid.proton.amqp.Symbol; import org.apache.qpid.proton.amqp.messaging.Accepted; import org.apache.qpid.proton.amqp.messaging.MessageAnnotations; import org.apache.qpid.proton.amqp.messaging.Source; import org.apache.qpid.proton.amqp.messaging.Target; import org.apache.qpid.proton.amqp.messaging.TerminusDurability; import org.apache.qpid.proton.message.Message; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.Optional; /** * A forwarder forwards AMQP messages from one host to another, using durable subscriptions, flow control and linked acknowledgement. */ public class Forwarder { private static final Logger log = LoggerFactory.getLogger(Forwarder.class.getName()); private final Vertx vertx; private final ProtonClient client; private final String address; private final Host from; private final Host to; private final long connectionRetryInterval; private volatile Optional<ProtonConnection> senderConnection = Optional.empty(); private volatile Optional<ProtonConnection> receiverConnection = Optional.empty(); private static Symbol replicated = Symbol.getSymbol("replicated"); private static Symbol topic = Symbol.getSymbol("topic"); public Forwarder(Vertx vertx, Host from, Host to, String address, long connectionRetryInterval) { this.vertx = vertx; this.client = ProtonClient.create(vertx); this.from = from; this.to = to; this.address = address; this.connectionRetryInterval = connectionRetryInterval; } public void start() { startSender(); } private void startReceiver(ProtonSender sender, String containerId) { log.info("Starting receiver"); client.connect(from.getHostname(), from.getAmqpPort(), event -> { if (event.succeeded()) { ProtonConnection connection = event.result(); connection.setContainer(containerId); connection.open(); receiverConnection = Optional.of(connection); Source source = new Source(); source.setAddress(address); source.setCapabilities(topic); source.setDurable(TerminusDurability.UNSETTLED_STATE); ProtonReceiver receiver = connection.createReceiver(address, new ProtonLinkOptions().setLinkName(containerId)); receiver.setAutoAccept(false); receiver.openHandler(handler -> { log.info(this + ": receiver opened to " + connection.getRemoteContainer()); }); receiver.closeHandler(result -> { if (result.succeeded()) { log.info(this + ": receiver closed"); closeReceiver(); } else { log.warn(this + ": receiver closed with error: " + result.cause().getMessage()); closeReceiver(); vertx.setTimer(connectionRetryInterval, timerId -> startReceiver(sender, containerId)); } }); receiver.setPrefetch(0); receiver.flow(sender.getCredit()); receiver.setSource(source); receiver.handler(((delivery, message) -> handleMessage(sender, receiver, delivery, message))); receiver.open(); } else { log.info(this + ": connection failed, retrying: " + event.cause().getMessage()); vertx.setTimer(connectionRetryInterval, timerId -> startReceiver(sender, containerId)); } }); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(from.getHostname()).append(":").append(from.getAmqpPort()); builder.append(" -> "); builder.append(to.getHostname()).append(":").append(to.getAmqpPort()); return builder.toString(); } private void startSender() { log.info(this + ": starting sender"); client.connect(to.getHostname(), to.getAmqpPort(), event -> { if (event.succeeded()) { ProtonConnection connection = event.result(); connection.open(); senderConnection = Optional.of(connection); ProtonSender sender = connection.createSender(address); sender.openHandler(handler -> { log.info(this + ": sender opened to " + connection.getRemoteContainer()); startReceiver(sender, connection.getRemoteContainer()); }); sender.closeHandler(result -> { if (result.succeeded()) { log.info(this + ": sender closed"); closeReceiver(); } else { closeReceiver(); log.warn(this + ": sender closed with error: " + result.cause().getMessage()); vertx.setTimer(connectionRetryInterval, timerId -> startSender()); } }); Target target = new Target(); target.setAddress(address); target.setCapabilities(topic); sender.setTarget(target); sender.open(); } else { closeReceiver(); log.info(this + ": connection failed: " + event.cause().getMessage()); vertx.setTimer(connectionRetryInterval, timerId -> startSender()); } }); } private void closeReceiver() { receiverConnection.ifPresent(ProtonConnection::close); } private void handleMessage(ProtonSender protonSender, ProtonReceiver protonReceiver, ProtonDelivery protonDelivery, Message message) { if (log.isDebugEnabled()) { log.debug(this + ": forwarding message"); } if (message.getAddress().equals(address) && !isMessageReplicated(message)) { forwardMessage(protonSender, protonReceiver, protonDelivery, message); } } private void forwardMessage(ProtonSender protonSender, ProtonReceiver protonReceiver, ProtonDelivery sourceDelivery, Message message) { MessageAnnotations annotations = message.getMessageAnnotations(); if (annotations == null) { annotations = new MessageAnnotations(Collections.singletonMap(replicated, true)); } else { annotations.getValue().put(replicated, true); } message.setMessageAnnotations(annotations); protonSender.send(message, protonDelivery -> { sourceDelivery.disposition(protonDelivery.getRemoteState(), protonDelivery.remotelySettled()); protonReceiver.flow(protonSender.getCredit() - protonReceiver.getCredit()); }); } public void stop() { receiverConnection.ifPresent(ProtonConnection::close); senderConnection.ifPresent(ProtonConnection::close); } private static boolean isMessageReplicated(Message message) { MessageAnnotations annotations = message.getMessageAnnotations(); return annotations != null && annotations.getValue().containsKey(replicated); } }
src/main/java/enmasse/broker/forwarder/Forwarder.java
Readd forwarder
src/main/java/enmasse/broker/forwarder/Forwarder.java
Readd forwarder
Java
apache-2.0
error: pathspec 'src/main/java/madcrawler/crawling/PageDownloader.java' did not match any file(s) known to git
3fafc529721369b5b76626c12c0aed027d5fd03c
1
tireks/mad-crawler
package madcrawler.crawling; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import java.io.IOException; import java.net.URL; public class PageDownloader { public Document fetchPage(URL url) throws IOException { return Jsoup.parse(url, 1000); } }
src/main/java/madcrawler/crawling/PageDownloader.java
Page Downloader Based on Jsoup
src/main/java/madcrawler/crawling/PageDownloader.java
Page Downloader
Java
apache-2.0
error: pathspec 'src/com/tenkiv/tekdaqc/android/content/CalibrationPoint.java' did not match any file(s) known to git
ddfe5454e279ff37c45b962c1d93e5abacb72319
1
Tenkiv/Tekdaqc-Android-Library
/** * Copyright 2013 Tenkiv, LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tenkiv.tekdaqc.android.content; import android.content.ContentValues; import com.tenkiv.tekdaqc.ATekdaqc.ANALOG_SCALE; import com.tenkiv.tekdaqc.peripherals.analog.AAnalogInput.Gain; import com.tenkiv.tekdaqc.peripherals.analog.AAnalogInput.Rate; import com.tenkiv.tekdaqc.peripherals.analog.ADS1256_AnalogInput.BUFFER_STATE; /** * POJO Class for a single calibration data point. * * @author Jared Woolston (jwoolston@tenkiv.com) * @since v1.0.0.0 */ public class CalibrationPoint { private long mID; private String mSerial; private long mTime; private double mTemperature; private Gain mGain; private Rate mRate; private BUFFER_STATE mBuffer; private ANALOG_SCALE mScale; private int mSelfGainCal; private int mSystemGainCal; private int mGainCalDifference; public CalibrationPoint(String serial, long time, double temp, Gain gain, Rate rate, BUFFER_STATE buffer, ANALOG_SCALE scale, int selfGain, int systemGain, int gainDiff) { this(-1, serial, time, temp, gain, rate, buffer, scale, selfGain, systemGain, gainDiff); } public CalibrationPoint(long id, String serial, long time, double temp, Gain gain, Rate rate, BUFFER_STATE buffer, ANALOG_SCALE scale, int selfGain, int systemGain, int gainDiff) { mID = id; mSerial = serial; mTime = time; mTemperature = temp; mGain = gain; mRate = rate; mBuffer = buffer; mScale = scale; mSelfGainCal = selfGain; mSystemGainCal = systemGain; mGainCalDifference = gainDiff; } public ContentValues toContentValues() { final ContentValues values = new ContentValues(); values.put(TekdaqcDataProviderContract.COLUMN_SERIAL, mSerial); values.put(TekdaqcDataProviderContract.COLUMN_TIME, System.currentTimeMillis()); values.put(TekdaqcDataProviderContract.COLUMN_GAIN, Integer.valueOf(mGain.gain)); values.put(TekdaqcDataProviderContract.COLUMN_RATE, Float.valueOf(mRate.rate)); values.put(TekdaqcDataProviderContract.COLUMN_BUFFER, mBuffer.name()); values.put(TekdaqcDataProviderContract.COLUMN_SCALE, mScale.scale); // We are writing the goal here to be as exact as possible values.put(TekdaqcDataProviderContract.COLUMN_TEMPERATURE, mTemperature); values.put(TekdaqcDataProviderContract.COLUMN_SELF_GAIN_CAL, mSelfGainCal); values.put(TekdaqcDataProviderContract.COLUMN_SYSTEM_GAIN_CAL, mSystemGainCal); values.put(TekdaqcDataProviderContract.COLUMN_GAIN_CAL_DIFF, mGainCalDifference); return values; } public long getID() { return mID; } public void setID(long id) { mID = id; } public String getSerial() { return mSerial; } public void setSerial(String serial) { mSerial = serial; } public long getTime() { return mTime; } public void setTime(long time) { mTime = time; } public Gain getGain() { return mGain; } public void setGain(Gain gain) { mGain = gain; } public Rate getRate() { return mRate; } public void setRate(Rate rate) { mRate = rate; } public BUFFER_STATE getBuffer() { return mBuffer; } public void setBuffer(BUFFER_STATE buffer) { mBuffer = buffer; } public ANALOG_SCALE getAnalogScale() { return mScale; } public void setAnalogScale(ANALOG_SCALE scale) { mScale = scale; } public int getSelfGainCal() { return mSelfGainCal; } public void setSelfGainCal(int cal) { mSelfGainCal = cal; } public int getSystemGainCal() { return mSystemGainCal; } public void setSystemGainCal(int cal) { mSystemGainCal = cal; } public int getGainCalDifference() { return mGainCalDifference; } public void setGainCalDifference(int difference) { mGainCalDifference = difference; } }
src/com/tenkiv/tekdaqc/android/content/CalibrationPoint.java
Adds a CalibrationPoint class which helps encapsulate submitting data to the content provider. Signed-off-by: Jared Woolston <7908093a172bd408f98ae7c3b27e2f9c385c52db@tenkiv.com>
src/com/tenkiv/tekdaqc/android/content/CalibrationPoint.java
Adds a CalibrationPoint class which helps encapsulate submitting data to the content provider.
Java
apache-2.0
error: pathspec 'app/src/main/java/com/gedder/gedderalarm/GedderAlarmManager.java' did not match any file(s) known to git
5ffefb015cf65d0b90aaf5307e51ee00ab814de7
1
GedderAlarm/GedderAlarm
/* * USER: mslm * DATE: 3/27/17 */ package com.gedder.gedderalarm; import android.annotation.TargetApi; import android.app.AlarmManager; import android.app.PendingIntent; import android.os.Build; import android.os.Handler; import static android.content.Context.ALARM_SERVICE; /** * A reimplementation of AlarmManager (because we can't extend it), to manage Gedder Alarms. */ public final class GedderAlarmManager { private static final String TAG = GedderAlarmManager.class.getSimpleName(); private static AlarmManager sAlarmManager = (AlarmManager) GedderAlarmApplication.getAppContext().getSystemService(ALARM_SERVICE); private GedderAlarmManager() {} public void cancel(PendingIntent operation) { sAlarmManager.cancel(operation); } @TargetApi(24) public void cancel(AlarmManager.OnAlarmListener listener) { if (Build.VERSION.SDK_INT >= 24) sAlarmManager.cancel(listener); } @TargetApi(21) public AlarmManager.AlarmClockInfo getNextAlarmClock() { if (Build.VERSION.SDK_INT >= 21) return sAlarmManager.getNextAlarmClock(); return null; } public void set(int type, long triggerAtMillis, PendingIntent operation) { sAlarmManager.set(type, triggerAtMillis, operation); } @TargetApi(24) public void set(int type, long triggerAtMillis, String tag, AlarmManager.OnAlarmListener listener, Handler targetHandler) { if (Build.VERSION.SDK_INT >= 24) sAlarmManager.set(type, triggerAtMillis, tag, listener, targetHandler); } @TargetApi(21) public void setAlarmClock(AlarmManager.AlarmClockInfo info, PendingIntent operation) { if (Build.VERSION.SDK_INT >= 21) sAlarmManager.setAlarmClock(info, operation); } @TargetApi(23) public void setAndAllowWhileIdle(int type, long triggerAtMillis, PendingIntent operation) { if (Build.VERSION.SDK_INT >= 23) sAlarmManager.setAndAllowWhileIdle(type, triggerAtMillis, operation); } public void setExact(int type, long triggerAtMillis, PendingIntent operation) { sAlarmManager.setExact(type, triggerAtMillis, operation); } @TargetApi(24) public void setExact(int type, long triggerAtMillis, String tag, AlarmManager.OnAlarmListener listener, Handler targetHandler) { if (Build.VERSION.SDK_INT >= 24) sAlarmManager.setExact(type, triggerAtMillis, tag, listener, targetHandler); } @TargetApi(23) public void setExactAndAllowWhileIdle(int type, long triggerAtMillis, PendingIntent operation) { if (Build.VERSION.SDK_INT >= 23) sAlarmManager.setAndAllowWhileIdle(type, triggerAtMillis, operation); } public void setInexactRepeating(int type, long triggerAtMillis, long intervalMillis, PendingIntent operation) { sAlarmManager.setInexactRepeating(type, triggerAtMillis, intervalMillis, operation); } public void setRepeating(int type, long triggerAtMillis, long intervalMillis, PendingIntent operation) { sAlarmManager.setRepeating(type, triggerAtMillis, intervalMillis, operation); } public void setTime(long millis) { sAlarmManager.setTime(millis); } public void setTimeZone(String timeZone) { sAlarmManager.setTimeZone(timeZone); } public void setWindow(int type, long windowStartMillis, long windowLengthMillis, PendingIntent operation) { sAlarmManager.setWindow(type, windowStartMillis, windowLengthMillis, operation); } @TargetApi(24) public void setWindow(int type, long windowStartMillis, long windowLengthMillis, String tag, AlarmManager.OnAlarmListener listener, Handler targetHandler) { if (Build.VERSION.SDK_INT >= 24) sAlarmManager.setWindow( type, windowStartMillis, windowLengthMillis, tag, listener, targetHandler); } }
app/src/main/java/com/gedder/gedderalarm/GedderAlarmManager.java
Copy and paste AlarmManager default implementation into GedderAlarmManager.
app/src/main/java/com/gedder/gedderalarm/GedderAlarmManager.java
Copy and paste AlarmManager default implementation into GedderAlarmManager.
Java
apache-2.0
error: pathspec 'src/test/java/com/github/sbugat/ec2tools/service/StartStopServiceTest.java' did not match any file(s) known to git
b8a8b84979fc2ba77e32861a8f3b2e35e8386b9d
1
Sylvain-Bugat/aws-ec2-start-stop-tools,Sylvain-Bugat/aws-ec2-start-stop-tools
package com.github.sbugat.ec2tools.service; import java.util.ArrayList; import org.assertj.core.api.Assertions; import org.assertj.core.util.Lists; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import com.github.sbugat.GenericMockitoTest; import com.github.sbugat.ec2tools.service.aws.AmazonEC2Service; import com.github.sbugat.ec2tools.service.configuration.ConfigurationService; import com.github.sbugat.ec2tools.service.options.ProgramOptions; /** * Start stop core service test. * * @author Sylvain Bugat */ @RunWith(MockitoJUnitRunner.class) public class StartStopServiceTest extends GenericMockitoTest { private static final String SECTION_1 = "Section 1"; private static final String SECTION_2 = "Section 2"; @Mock private AmazonEC2Service amazonEC2Service; @Mock private ConfigurationService configurationService; @InjectMocks private StartStopService startStopService; @Test public void testProcessAllSectionsEmpty() { final ProgramOptions programOptions = new ProgramOptions(true, false, false, false, new ArrayList<String>()); Assertions.assertThat(startStopService.processAllSections(programOptions)).isFalse(); } @Test public void testProcessAllSectionsUnknownSection() { final ProgramOptions programOptions = new ProgramOptions(true, false, false, false, Lists.newArrayList(SECTION_1)); Mockito.doReturn(null).when(configurationService).getConfiguredSections(SECTION_1); Assertions.assertThat(startStopService.processAllSections(programOptions)).isTrue(); Mockito.verify(configurationService).getConfiguredSections(SECTION_1); } @Test public void testProcessAllSectionsEmptySection() { final ProgramOptions programOptions = new ProgramOptions(true, false, false, false, Lists.newArrayList(SECTION_1)); Assertions.assertThat(startStopService.processAllSections(programOptions)).isFalse(); Mockito.verify(configurationService).getConfiguredSections(SECTION_1); } }
src/test/java/com/github/sbugat/ec2tools/service/StartStopServiceTest.java
Add StartStopServiceTest
src/test/java/com/github/sbugat/ec2tools/service/StartStopServiceTest.java
Add StartStopServiceTest
Java
apache-2.0
error: pathspec 'awtt-server/src/test/java/li/moskito/awtt/common/CustomContentTypeTest.java' did not match any file(s) known to git
035a708dd4c2f0019756e5cc2f83475843f80fff
1
moskitoli/awtt
package li.moskito.awtt.common; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; public class CustomContentTypeTest { private CustomContentType subject; @Before public void setUp() throws Exception { this.subject = new CustomContentType("test/plain"); } @Test public void testGetMIMEType() throws Exception { assertEquals("text/plain", this.subject); } }
awtt-server/src/test/java/li/moskito/awtt/common/CustomContentTypeTest.java
added test
awtt-server/src/test/java/li/moskito/awtt/common/CustomContentTypeTest.java
added test
Java
apache-2.0
error: pathspec 'src/java/org/apache/commons/collections/map/AbstractSimpleMapDecorator.java' did not match any file(s) known to git
ee70aa120d63a394872a54d63a94fe3eeda72587
1
MuShiiii/commons-collections,apache/commons-collections,mohanaraosv/commons-collections,apache/commons-collections,sandrineBeauche/commons-collections,gonmarques/commons-collections,jankill/commons-collections,sandrineBeauche/commons-collections,MuShiiii/commons-collections,mohanaraosv/commons-collections,sandrineBeauche/commons-collections,jankill/commons-collections,mohanaraosv/commons-collections,gonmarques/commons-collections,MuShiiii/commons-collections,jankill/commons-collections,apache/commons-collections
/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.collections.KeyValue; import org.apache.commons.collections.collection.AbstractCollectionDecorator; import org.apache.commons.collections.iterators.AbstractIteratorDecorator; import org.apache.commons.collections.set.AbstractSetDecorator; /** * An abstract base class that simplifies the task of creating map decorators. * <p> * The Map API is very difficult to decorate correctly, and involves implementing * lots of different classes. This class exists to provide a simpler API. * <p> * Special hook methods are provided that are called when events occur on the map. * By overriding these methods, the input and output can be validated or manipulated. * <p> * This class provides full implementations of the keySet, values and entrySet, * which means that your subclass decorator should not need any inner classes. * * @since Commons Collections 3.1 * @version $Revision: 1.1 $ $Date: 2004/05/21 21:42:04 $ * * @author Stephen Colebourne */ public class AbstractSimpleMapDecorator extends AbstractMapDecorator { /** * Constructor only used in deserialization, do not use otherwise. */ protected AbstractSimpleMapDecorator() { super(); } /** * Constructor that wraps (not copies). * * @param map the map to decorate, must not be null * @throws IllegalArgumentException if map is null */ protected AbstractSimpleMapDecorator(Map map) { super(map); } //----------------------------------------------------------------------- /** * Hook method called when a key is being retrieved from the map using * <code>put</code>, <code>keySet.iterator</code> or <code>entry.getKey</code>. * <p> * An implementation may validate the key and throw an exception * or it may transform the key into another object. * <p> * This implementation returns the input key. * * @param key the key to check * @throws UnsupportedOperationException if the map get is not supported * @throws IllegalArgumentException if the specified key is invalid * @throws ClassCastException if the class of the specified key is invalid * @throws NullPointerException if the specified key is null and nulls are invalid */ protected Object checkGetKey(Object key) { return key; } /** * Hook method called when a value is being retrieved from the map using * <code>get</code>, <code>values.iterator</code> or <code>entry.getValue</code>. * <p> * An implementation may validate the value and throw an exception * or it may transform the value into another object. * <p> * This implementation returns the input value. * * @param value the value to check * @throws UnsupportedOperationException if the map get is not supported * @throws IllegalArgumentException if the specified value is invalid * @throws ClassCastException if the class of the specified value is invalid * @throws NullPointerException if the specified value is null and nulls are invalid */ protected Object checkGetValue(Object value) { return value; } /** * Hook method called when a key is being added to the map using * <code>put</code> or <code>putAll</code>. * <p> * An implementation may validate the key and throw an exception * or it may transform the key into another object. * The key may already exist in the map. * <p> * This implementation returns the input key. * * @param key the key to check * @throws UnsupportedOperationException if the map may not be changed by put/putAll * @throws IllegalArgumentException if the specified key is invalid * @throws ClassCastException if the class of the specified key is invalid * @throws NullPointerException if the specified key is null and nulls are invalid */ protected Object checkPutKey(Object key) { return key; } /** * Hook method called when a new value is being added to the map using * <code>put</code> or <code>putAll</code>. * <p> * An implementation may validate the value and throw an exception * or it may transform the value into another object. * <p> * This implementation returns the input value. * * @param value the value to check * @throws UnsupportedOperationException if the map may not be changed by put/putAll * @throws IllegalArgumentException if the specified value is invalid * @throws ClassCastException if the class of the specified value is invalid * @throws NullPointerException if the specified value is null and nulls are invalid */ protected Object checkPutValue(Object value) { return value; } /** * Hook method called when a value is being set using <code>setValue</code>. * <p> * An implementation may validate the value and throw an exception * or it may transform the value into another object. * <p> * This implementation returns the input value. * * @param value the value to check * @throws UnsupportedOperationException if the map may not be changed by setValue * @throws IllegalArgumentException if the specified value is invalid * @throws ClassCastException if the class of the specified value is invalid * @throws NullPointerException if the specified value is null and nulls are invalid */ protected Object checkSetValue(Object value) { return value; } /** * Hook method called when the map is being queried using a key via the * contains and equals methods. * <p> * An implementation may validate the key and throw an exception * or it may transform the key into another object. * <p> * This implementation returns the input key. * * @param key the key to check * @throws UnsupportedOperationException if the method is not supported * @throws IllegalArgumentException if the specified key is invalid * @throws ClassCastException if the class of the specified key is invalid * @throws NullPointerException if the specified key is null and nulls are invalid */ protected Object checkQueryKey(Object key) { return key; } /** * Hook method called when the map is being queried using a value via the * contains and equals methods. * <p> * An implementation may validate the value and throw an exception * or it may transform the value into another object. * <p> * This implementation returns the input value. * * @param value the value to check * @throws UnsupportedOperationException if the method is not supported * @throws IllegalArgumentException if the specified value is invalid * @throws ClassCastException if the class of the specified value is invalid * @throws NullPointerException if the specified value is null and nulls are invalid */ protected Object checkQueryValue(Object value) { return value; } /** * Hook method called when the map is being queried using a key via the * remove methods. * <p> * An implementation may validate the key and throw an exception * or it may transform the key into another object. * <p> * This implementation returns the input key. * * @param key the key to check * @throws UnsupportedOperationException if the method is not supported * @throws IllegalArgumentException if the specified key is invalid * @throws ClassCastException if the class of the specified key is invalid * @throws NullPointerException if the specified key is null and nulls are invalid */ protected Object checkRemoveKey(Object key) { return key; } /** * Hook method called when the map is being queried using a value via the * remove methods. * <p> * An implementation may validate the value and throw an exception * or it may transform the value into another object. * <p> * This implementation returns the input value. * * @param value the value to check * @throws UnsupportedOperationException if the method is not supported * @throws IllegalArgumentException if the specified value is invalid * @throws ClassCastException if the class of the specified value is invalid * @throws NullPointerException if the specified value is null and nulls are invalid */ protected Object checkRemoveValue(Object value) { return value; } /** * Hook method called to determine if the keySet view should be decorated. * <p> * An implementation should return false if the there is no decoration of the keySet * view as this optimises the implementation. * <p> * This implementation returns <code>true</code>. * * @param value the value to check */ protected boolean requiresKeySetDecorator() { return true; } /** * Hook method called to determine if the values view should be decorated. * <p> * An implementation should return false if the there is no decoration of the values * view as this optimises the implementation. * <p> * This implementation returns <code>true</code>. * * @param value the value to check */ protected boolean requiresValuesDecorator() { return true; } /** * Hook method called to determine if the entrySet view should be decorated. * <p> * An implementation should return false if the there is no decoration of the entrySet * view as this optimises the implementation. * <p> * This implementation returns <code>true</code>. * * @param value the value to check */ protected boolean requiresEntrySetDecorator() { return true; } /** * Checks each element in the specified map, creating a new map. * <p> * This method is used by <code>putAll</code> to check all the elements * before adding them to the map. * <p> * This implementation builds a <code>LinkedMap</code> to preserve the order * of the input map. * * @param map the map to transform * @throws the transformed object */ protected Map checkMap(Map map) { Map result = new LinkedMap(map.size()); for (Iterator it = map.entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry) it.next(); result.put(checkPutKey(entry.getKey()), checkPutValue(entry.getValue())); } return result; } //----------------------------------------------------------------------- public Object get(Object key) { return checkGetValue(getMap().get(key)); } public boolean containsKey(Object key) { key = checkQueryKey(key); return getMap().containsKey(key); } public boolean containsValue(Object value) { value = checkQueryValue(value); return getMap().containsValue(value); } public Object put(Object key, Object value) { key = checkPutKey(key); value = checkPutValue(value); return checkGetKey(getMap().put(key, value)); } public void putAll(Map mapToCopy) { if (mapToCopy.size() == 0) { return; } else { mapToCopy = checkMap(mapToCopy); getMap().putAll(mapToCopy); } } public Object remove(Object key) { key = checkRemoveKey(key); return checkGetKey(getMap().remove(key)); } public Set keySet() { if (requiresKeySetDecorator()) { return new KeySet(map.keySet(), this); } else { return map.keySet(); } } public Collection values() { if (requiresValuesDecorator()) { return new Values(map.values(), this); } else { return map.values(); } } public Set entrySet() { if (requiresEntrySetDecorator()) { return new EntrySet(map.entrySet(), this); } else { return map.entrySet(); } } //----------------------------------------------------------------------- /** * Implementation of an entry set that checks the returned keys. */ static class KeySet extends AbstractSetDecorator { /** The parent map */ private final AbstractSimpleMapDecorator parent; protected KeySet(Set set, AbstractSimpleMapDecorator parent) { super(set); this.parent = parent; } public Iterator iterator() { return new KeySetIterator(collection.iterator(), parent); } public boolean contains(Object key) { key = parent.checkQueryKey(key); return collection.contains(key); } public boolean containsAll(Collection coll) { List list = new ArrayList(coll); for (int i = 0; i < list.size(); i++) { list.set(i, parent.checkQueryKey(list.get(i))); } return collection.containsAll(list); } public boolean remove(Object key) { key = parent.checkRemoveKey(key); return collection.remove(key); } public boolean removeAll(Collection coll) { List list = new ArrayList(coll); for (int i = 0; i < list.size(); i++) { list.set(i, parent.checkRemoveKey(list.get(i))); } return collection.removeAll(list); } public boolean retainAll(Collection coll) { List list = new ArrayList(coll); for (int i = 0; i < list.size(); i++) { list.set(i, parent.checkRemoveKey(list.get(i))); } return collection.retainAll(list); } public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof Set == false) { return false; } Set other = (Set) object; Set set = new HashSet(other.size()); for (Iterator it = other.iterator(); it.hasNext();) { set.add(parent.checkQueryKey(it.next())); } return collection.equals(set); } public Object[] toArray() { Object[] array = collection.toArray(); for (int i = 0; i < array.length; i++) { array[i] = parent.checkGetKey(array[i]); } return array; } public Object[] toArray(Object array[]) { Object[] result = array; if (array.length > 0) { // we must create a new array to handle multi-threaded situations // where another thread could access data before we decorate it result = (Object[]) Array.newInstance(array.getClass().getComponentType(), 0); } result = collection.toArray(result); for (int i = 0; i < result.length; i++) { result[i] = parent.checkGetKey(result[i]); } // check to see if result should be returned straight if (result.length > array.length) { return result; } // copy back into input array to fulfil the method contract System.arraycopy(result, 0, array, 0, result.length); if (array.length > result.length) { array[result.length] = null; } return array; } } //----------------------------------------------------------------------- /** * Implementation of a key set iterator that checks the returned keys. */ static class KeySetIterator extends AbstractIteratorDecorator { /** The parent map */ private final AbstractSimpleMapDecorator parent; protected KeySetIterator(Iterator iterator, AbstractSimpleMapDecorator parent) { super(iterator); this.parent = parent; } public Object next() { return parent.checkGetKey(iterator.next()); } } //----------------------------------------------------------------------- /** * Implementation of a values collection that checks the returned values. */ static class Values extends AbstractCollectionDecorator { /** The parent map */ private final AbstractSimpleMapDecorator parent; protected Values(Collection coll, AbstractSimpleMapDecorator parent) { super(coll); this.parent = parent; } public Iterator iterator() { return new ValuesIterator(collection.iterator(), parent); } public boolean contains(Object key) { key = parent.checkQueryValue(key); return collection.contains(key); } public boolean containsAll(Collection coll) { List list = new ArrayList(coll); for (int i = 0; i < list.size(); i++) { list.set(i, parent.checkQueryValue(list.get(i))); } return collection.containsAll(list); } public boolean remove(Object key) { key = parent.checkRemoveValue(key); return collection.remove(key); } public boolean removeAll(Collection coll) { List list = new ArrayList(coll); for (int i = 0; i < list.size(); i++) { list.set(i, parent.checkRemoveValue(list.get(i))); } return collection.removeAll(list); } public boolean retainAll(Collection coll) { List list = new ArrayList(coll); for (int i = 0; i < list.size(); i++) { list.set(i, parent.checkRemoveValue(list.get(i))); } return collection.retainAll(list); } public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof Collection == false) { return false; } Collection other = (Collection) object; Collection coll = new ArrayList(other.size()); for (Iterator it = other.iterator(); it.hasNext();) { coll.add(parent.checkQueryValue(it.next())); } return collection.equals(coll); } public Object[] toArray() { Object[] array = collection.toArray(); for (int i = 0; i < array.length; i++) { array[i] = parent.checkGetValue(array[i]); } return array; } public Object[] toArray(Object array[]) { Object[] result = array; if (array.length > 0) { // we must create a new array to handle multi-threaded situations // where another thread could access data before we decorate it result = (Object[]) Array.newInstance(array.getClass().getComponentType(), 0); } result = collection.toArray(result); for (int i = 0; i < result.length; i++) { result[i] = parent.checkGetValue(result[i]); } // check to see if result should be returned straight if (result.length > array.length) { return result; } // copy back into input array to fulfil the method contract System.arraycopy(result, 0, array, 0, result.length); if (array.length > result.length) { array[result.length] = null; } return array; } } //----------------------------------------------------------------------- /** * Implementation of an value iterator that checks the returned values. */ static class ValuesIterator extends AbstractIteratorDecorator { /** The parent map */ private final AbstractSimpleMapDecorator parent; protected ValuesIterator(Iterator iterator, AbstractSimpleMapDecorator parent) { super(iterator); this.parent = parent; } public Object next() { return parent.checkGetValue(iterator.next()); } } //----------------------------------------------------------------------- /** * Implementation of an entry set that calls hook methods from the map entry. */ static class EntrySet extends AbstractSetDecorator { /** The parent map */ private final AbstractSimpleMapDecorator parent; protected EntrySet(Set set, AbstractSimpleMapDecorator parent) { super(set); this.parent = parent; } public Iterator iterator() { return new EntrySetIterator(collection.iterator(), parent); } public Object[] toArray() { Object[] array = collection.toArray(); for (int i = 0; i < array.length; i++) { array[i] = new MapEntry((Map.Entry) array[i], parent); } return array; } public Object[] toArray(Object array[]) { Object[] result = array; if (array.length > 0) { // we must create a new array to handle multi-threaded situations // where another thread could access data before we decorate it result = (Object[]) Array.newInstance(array.getClass().getComponentType(), 0); } result = collection.toArray(result); for (int i = 0; i < result.length; i++) { result[i] = new MapEntry((Map.Entry) result[i], parent); } // check to see if result should be returned straight if (result.length > array.length) { return result; } // copy back into input array to fulfil the method contract System.arraycopy(result, 0, array, 0, result.length); if (array.length > result.length) { array[result.length] = null; } return array; } } //----------------------------------------------------------------------- /** * Implementation of an entry set iterator that sets up a special map entry. */ static class EntrySetIterator extends AbstractIteratorDecorator { /** The parent map */ private final AbstractSimpleMapDecorator parent; protected EntrySetIterator(Iterator iterator, AbstractSimpleMapDecorator parent) { super(iterator); this.parent = parent; } public Object next() { Map.Entry entry = (Map.Entry) iterator.next(); return new MapEntry(entry, parent); } } //----------------------------------------------------------------------- /** * Implementation of a map entry that calls the hook methods. */ static class MapEntry implements Map.Entry, KeyValue { /** The <code>Map.Entry</code> to decorate */ protected final Map.Entry entry; /** The parent map */ private final AbstractSimpleMapDecorator parent; protected MapEntry(Map.Entry entry, AbstractSimpleMapDecorator parent) { super(); this.entry = entry; this.parent = parent; } public Object getKey() { return parent.checkGetKey(entry.getKey()); } public Object getValue() { return parent.checkGetValue(entry.getValue()); } public Object setValue(Object value) { value = parent.checkSetValue(value); return entry.setValue(value); } public boolean equals(Object object) { if (object == this) { return true; } return entry.equals(object); } public int hashCode() { return entry.hashCode(); } public String toString() { return entry.toString(); } } }
src/java/org/apache/commons/collections/map/AbstractSimpleMapDecorator.java
Initial version of AbstractSimpleMapDecorator git-svn-id: b713d2d75405ee089de821fbacfe0f8fc04e1abf@131731 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/commons/collections/map/AbstractSimpleMapDecorator.java
Initial version of AbstractSimpleMapDecorator
Java
apache-2.0
error: pathspec 'modules/quality-check/src/main/java/net/sf/qualitycheck/ConditionalCheck.java' did not match any file(s) known to git
a3477e186ce4cbbec94384c643bf9ae7867cfb99
1
before/quality-check
/******************************************************************************* * Copyright 2012 André Rouél * Copyright 2012 Dominik Seichter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package net.sf.qualitycheck; import java.lang.annotation.Annotation; import java.util.Collection; import java.util.Map; import java.util.regex.Pattern; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import net.sf.qualitycheck.exception.IllegalEmptyArgumentException; import net.sf.qualitycheck.exception.IllegalInstanceOfArgumentException; import net.sf.qualitycheck.exception.IllegalNaNArgumentException; import net.sf.qualitycheck.exception.IllegalNegativeArgumentException; import net.sf.qualitycheck.exception.IllegalNotEqualException; import net.sf.qualitycheck.exception.IllegalNullArgumentException; import net.sf.qualitycheck.exception.IllegalNullElementsException; import net.sf.qualitycheck.exception.IllegalNumberArgumentException; import net.sf.qualitycheck.exception.IllegalNumberRangeException; import net.sf.qualitycheck.exception.IllegalPatternArgumentException; import net.sf.qualitycheck.exception.IllegalPositionIndexException; import net.sf.qualitycheck.exception.IllegalRangeException; import net.sf.qualitycheck.exception.IllegalStateOfArgumentException; import net.sf.qualitycheck.exception.RuntimeInstantiationException; /** * This class adds conditional methods to test your arguments to be valid. The checks are the same as offered in * {@code Check}, but all have an additional condition. The check is only executed if the condition is true. * * @author Dominik Seichter */ public final class ConditionalCheck { /** * Ensures that a passed object is equal to another object. The comparison is made using a call to * {@code expected.equals(check) }. * * The condition must evaluate to {@code true} so that the check is executed. * * @param condition * condition must be true so that the check is performed. * @param expected * Expected value * @param check * Object to be checked * @return {@code check} The checked object */ @ArgumentsChecked @Throws(IllegalNullArgumentException.class) public static <T extends Object> T equals(final boolean condition, @Nonnull final T expected, @Nonnull final T check) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar if (condition) { return Check.equals(expected, check); } return check; } /** * Ensures that a passed object is equal to another object. The comparison is made using a call to * {@code expected.equals(check) }. * * @param expected * Expected value * @param check * Object to be checked * @param message * an error message describing why the objects must equal (will be passed to * {@code IllegalNotEqualException}) * @return {@code check} The checked object */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNotEqualException.class }) public static <T extends Object> T equals(final boolean condition, @Nonnull final T expected, @Nonnull final T check, final String message) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar if (condition) { return Check.equals(expected, check); } return check; } /** * Ensures that a passed class has an annotation of a specific type * * @param clazz * the class that must have a required annotation * @param annotation * the type of annotation that is required on the class * @return the annotation which is present on the checked class */ @ArgumentsChecked @Throws(IllegalNullArgumentException.class) public static Annotation hasAnnotation(final boolean condition, @Nonnull final Class<?> clazz, @Nonnull final Class<? extends Annotation> annotation) { Check.notNull(clazz, "clazz"); Check.notNull(annotation, "annotation"); if (condition) { return Check.hasAnnotation(clazz, annotation); } return clazz.getAnnotation(annotation); } /** * Ensures that a passed argument is a member of a specific type. * * @param type * class that the given object is a member of * @param obj * the object reference that should be a member of a specific {@code type} * @throws IllegalInstanceOfArgumentException * if the given argument {@code obj} is not a member of {@code type} */ @ArgumentsChecked @Throws(IllegalNullArgumentException.class) @SuppressWarnings("unchecked") public static <T> T instanceOf(final boolean condition, @Nonnull final Class<?> type, @Nonnull final Object obj) { if (condition) { return Check.instanceOf(type, obj); } return (T) obj; } /** * Ensures that a passed argument is a member of a specific type. * * @param type * class that the given object is a member of * @param obj * the object reference that should be a member of a specific {@code type} * @param name * name of object reference (in source code) * @throws IllegalInstanceOfArgumentException * if the given argument {@code obj} is not a member of {@code type} */ @ArgumentsChecked @Throws(IllegalNullArgumentException.class) @SuppressWarnings("unchecked") public static <T> T instanceOf(final boolean condition, @Nonnull final Class<?> type, @Nonnull final Object obj, @Nullable final String name) { if (condition) { return Check.instanceOf(type, obj, name); } return (T) obj; } /** * Ensures that a String argument is a number. * * @param value * value which must be a number * @throws IllegalNumberArgumentException * if the given argument {@code value} is no number */ @ArgumentsChecked public static void isNumber(final boolean condition, @Nonnull final String value) { if (condition) { Check.isNumber(value); } } /** * Ensures that a String argument is a number. This overload supports all subclasses of {@code Number}. The number * is first converted to a BigInteger * * @param value * value which must be a number * @param type * requested return value type, must be a subclass of {@code Number}, i.e. one of {@code BigDecimal, * BigInteger, Byte, Double, Float, Integer, Long, Short} * @return the given string argument converted to a number of the requested type * @throws IllegalNumberArgumentException * if the given argument {@code value} is no number */ @ArgumentsChecked @Throws(IllegalNullArgumentException.class) public static <T extends Number> void isNumber(final boolean condition, @Nonnull final String value, @Nonnull final Class<T> type) { if (condition) { Check.isNumber(value, type); } } /** * Ensures that a string argument is a number according to {@code Integer.parseInt} * * @param value * value which must be a number * @param name * name of object reference (in source code) * @return the given string argument converted to an int * @throws IllegalNumberArgumentException * if the given argument {@code value} is no number */ @ArgumentsChecked @Throws(IllegalNullArgumentException.class) public static void isNumber(final boolean condition, @Nonnull final String value, @Nullable final String name) { if (condition) { Check.isNumber(value, name); } } /** * Ensures that a String argument is a number. This overload supports all subclasses of {@code Number}. The number * is first converted to a {@code BigDecimal} or {@code BigInteger}. Floating point types are only supported if the * {@code type} is one of {@code Float, Double, BigDecimal}. * * This method does also check against the ranges of the given datatypes. * * @param value * value which must be a number and in the range of the given datatype. * @param name * (optional) name of object reference (in source code). * @param type * requested return value type, must be a subclass of {@code Number}, i.e. one of {@code BigDecimal, * BigInteger, Byte, Double, Float, Integer, Long, Short} * @return the given string argument converted to a number of the requested type * @throws IllegalNumberArgumentException * if the given argument {@code value} is no number */ @ArgumentsChecked @Throws(value = { IllegalNullArgumentException.class, IllegalNumberRangeException.class }) public static <T extends Number> void isNumber(final boolean condition, @Nonnull final String value, @Nullable final String name, @Nonnull final Class<T> type) { if (condition) { Check.isNumber(value, name, type); } } /** * Ensures that a readable sequence of {@code char} values is numeric. Numeric arguments consist only of the * characters 0-9 and may start with 0 (compared to number arguments, which must be valid numbers - think of a bank * account number). * * <p> * We recommend to use the overloaded method {@link Check#isNumeric(CharSequence, String)} and pass as second * argument the name of the parameter to enhance the exception message. * * @param value * a readable sequence of {@code char} values which must be a number * @return the given string argument * @throws IllegalNumberArgumentException * if the given argument {@code value} is no number */ @ArgumentsChecked @Throws(IllegalNullArgumentException.class) public static <T extends CharSequence> void isNumeric(final boolean condition, @Nonnull final T value) { if (condition) { Check.isNumeric(value); } } /** * Ensures that a readable sequence of {@code char} values is numeric. Numeric arguments consist only of the * characters 0-9 and may start with 0 (compared to number arguments, which must be valid numbers - think of a bank * account number). * * @param value * a readable sequence of {@code char} values which must be a number * @param name * name of object reference (in source code) * @return the given string argument * @throws IllegalNumberArgumentException * if the given argument {@code value} is no number */ @ArgumentsChecked @Throws(IllegalNullArgumentException.class) public static <T extends CharSequence> void isNumeric(final boolean condition, @Nonnull final T value, @Nullable final String name) { if (condition) { Check.isNumeric(value, name); } } /** * Ensures that a readable sequence of {@code char} values matches a specified pattern. If the given character * sequence does not match against the passed pattern, an {@link IllegalPatternArgumentException} will be thrown. * * <p> * We recommend to use the overloaded method {@link Check#matchesPattern(Pattern, CharSequence, String)} and pass as * second argument the name of the parameter to enhance the exception message. * * @param pattern * pattern, that the {@code chars} must correspond to * @param chars * a readable sequence of {@code char} values which should match the given pattern * @return the passed {@code chars} that matches the given pattern * @throws IllegalNullArgumentException * if the given argument {@code chars} is {@code null} * @throws IllegalPatternArgumentException * if the given {@code chars} that does not match the {@code pattern} */ @ArgumentsChecked @Throws(IllegalNullArgumentException.class) public static <T extends CharSequence> T matchesPattern(final boolean condition, @Nonnull final Pattern pattern, @Nonnull final T chars) { if (condition) { Check.matchesPattern(pattern, chars); } return chars; } /** * Ensures that a readable sequence of {@code char} values matches a specified pattern. If the given character * sequence does not match against the passed pattern, an {@link IllegalPatternArgumentException} will be thrown. * * @param pattern * pattern, that the {@code chars} must correspond to * @param chars * a readable sequence of {@code char} values which should match the given pattern * @param name * name of object reference (in source code) * @return the passed {@code chars} that matches the given pattern * @throws IllegalNullArgumentException * if the given argument {@code chars} is {@code null} * @throws IllegalPatternArgumentException * if the given {@code chars} that does not match the {@code pattern} */ @ArgumentsChecked @Throws(IllegalNullArgumentException.class) public static <T extends CharSequence> T matchesPattern(final boolean condition, @Nonnull final Pattern pattern, @Nonnull final T chars, @Nullable final String name) { if (condition) { Check.matchesPattern(pattern, chars, name); } return chars; } /** * Ensures that an iterable reference is neither {@code null} nor contains any elements that are {@code null}. * * <p> * We recommend to use the overloaded method {@link Check#noNullElements(Iterable, String)} and pass as second * argument the name of the parameter to enhance the exception message. * * @param iterable * the iterable reference which should not contain {@code null} * @return the passed reference which contains no elements that are {@code null} * @throws IllegalNullElementsException * if the given argument {@code iterable} contains elements that are {@code null} */ @ArgumentsChecked @Throws(IllegalNullArgumentException.class) public static <T extends Iterable<?>> T noNullElements(final boolean condition, @Nonnull final T iterable) { if (condition) { Check.noNullElements(iterable); } return iterable; } /** * Ensures that an iterable reference is neither {@code null} nor contains any elements that are {@code null}. * * @param iterable * the iterable reference which should not contain {@code null} * @param name * name of object reference (in source code) * @return the passed reference which contains no elements that are {@code null} * @throws IllegalNullElementsException * if the given argument {@code iterable} contains elements that are {@code null} */ @ArgumentsChecked @Throws(IllegalNullArgumentException.class) public static <T extends Iterable<?>> T noNullElements(final boolean condition, @Nonnull final T iterable, final String name) { if (condition) { Check.noNullElements(iterable, name); } return iterable; } /** * Ensures that an array does not contain {@code null}. * * <p> * We recommend to use the overloaded method {@link Check#noNullElements(Object[], String)} and pass as second * argument the name of the parameter to enhance the exception message. * * @param array * reference to an array * @return the passed reference which contains no elements that are {@code null} * @throws IllegalNullElementsException * if the given argument {@code array} contains {@code null} */ @ArgumentsChecked @Throws(IllegalNullArgumentException.class) public static <T> T[] noNullElements(final boolean condition, @Nonnull final T[] array) { if (condition) { Check.noNullElements(array); } return array; } /** * Ensures that an array does not contain {@code null}. * * @param array * reference to an array * @param name * name of object reference (in source code) * @return the passed reference which contains no elements that are {@code null} * @throws IllegalNullElementsException * if the given argument {@code array} contains {@code null} */ @ArgumentsChecked @Throws(IllegalNullArgumentException.class) public static <T> T[] noNullElements(final boolean condition, @Nonnull final T[] array, @Nullable final String name) { if (condition) { Check.noNullElements(array, name); } return array; } /** * Ensures that a passed parameter of the calling method is not empty, using the passed expression to evaluate the * emptiness. * * <p> * We recommend to use the overloaded method {@link Check#notEmpty(boolean, String)} and pass as second argument the * name of the parameter to enhance the exception message. * * @param expression * the result of the expression to verify the emptiness of a reference ({@code true} means empty, * {@code false} means not empty) * * @throws IllegalNullArgumentException * if the given argument {@code reference} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code reference} is empty */ @ArgumentsChecked @Throws(IllegalEmptyArgumentException.class) public static void notEmpty(final boolean condition, final boolean expression) { if (condition) { Check.notEmpty(expression); } } /** * Ensures that a passed parameter of the calling method is not empty, using the passed expression to evaluate the * emptiness. * * @param expression * the result of the expression to verify the emptiness of a reference ({@code true} means empty, * {@code false} means not empty) * @param name * name of object reference (in source code) * * @throws IllegalEmptyArgumentException * if the given argument {@code reference} is empty */ @ArgumentsChecked @Throws(IllegalEmptyArgumentException.class) public static void notEmpty(final boolean condition, final boolean expression, @Nullable final String name) { if (condition) { Check.notEmpty(expression, name); } } /** * Ensures that a passed string as a parameter of the calling method is not empty. * * <p> * We recommend to use the overloaded method {@link Check#notEmpty(CharSequence, String)} and pass as second * argument the name of the parameter to enhance the exception message. * * @param chars * a readable sequence of {@code char} values which should not be empty * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code reference} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code reference} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T extends CharSequence> T notEmpty(final boolean condition, @Nonnull final T chars) { if (condition) { Check.notEmpty(chars); } return chars; } /** * Ensures that a passed collection as a parameter of the calling method is not empty. * * <p> * We recommend to use the overloaded method {@link Check#notEmpty(Collection, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param collection * a collection which should not be empty * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code collection} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code collection} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T extends Collection<?>> T notEmpty(final boolean condition, @Nonnull final T collection) { if (condition) { Check.notEmpty(collection); } return collection; } /** * Ensures that a passed map as a parameter of the calling method is not empty. * * <p> * We recommend to use the overloaded method {@link Check#notEmpty(Collection, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param map * a map which should not be empty * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code map} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code map} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T extends Map<?, ?>> T notEmpty(final boolean condition, @Nonnull final T map) { if (condition) { Check.notEmpty(map); } return map; } /** * Ensures that an object reference passed as a parameter to the calling method is not empty. The passed boolean * value is the result of checking whether the reference is empty or not. * * <p> * The following example describes how to use it. * * <pre> * &#064;ArgumentsChecked * public setText(String text) { * Check.notEmpty(text, text.isEmpty(), &quot;text&quot;); * this.text = text; * } * </pre> * * @param reference * an object reference which should not be empty * @param expression * the result of the expression to verify the emptiness of a reference ({@code true} means empty, * {@code false} means not empty) * @param name * name of object reference (in source code) * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code reference} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code reference} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T> T notEmpty(final boolean condition, @Nonnull final T reference, final boolean expression, @Nullable final String name) { if (condition) { Check.notEmpty(reference, expression, name); } return reference; } /** * Ensures that a passed string as a parameter of the calling method is not empty. * * <p> * The following example describes how to use it. * * <pre> * &#064;ArgumentsChecked * public setText(String text) { * this.text = Check.notEmpty(text, &quot;text&quot;); * } * </pre> * * @param chars * a readable sequence of {@code char} values which should not be empty * @param name * name of object reference (in source code) * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code string} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code string} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T extends CharSequence> T notEmpty(final boolean condition, @Nonnull final T chars, @Nullable final String name) { if (condition) { Check.notEmpty(chars, name); } return chars; } /** * Ensures that a passed map as a parameter of the calling method is not empty. * * <p> * We recommend to use the overloaded method {@link Check#notEmpty(Collection, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param map * a map which should not be empty * @param name * name of object reference (in source code) * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code map} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code map} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T extends Map<?, ?>> T notEmpty(final boolean condition, @Nonnull final T map, @Nullable final String name) { if (condition) { Check.notEmpty(map, name); } return map; } /** * Ensures that a passed collection as a parameter of the calling method is not empty. * * <p> * The following example describes how to use it. * * <pre> * &#064;ArgumentsChecked * public setCollection(Collection&lt;String&gt; collection) { * this.collection = Check.notEmpty(collection, &quot;collection&quot;); * } * </pre> * * @param collection * a collection which should not be empty * @param name * name of object reference (in source code) * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code collection} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code collection} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T extends Collection<?>> T notEmpty(final boolean condition, @Nonnull final T collection, @Nullable final String name) { if (condition) { Check.notEmpty(collection, name); } return collection; } /** * Ensures that a passed map as a parameter of the calling method is not empty. * * <p> * We recommend to use the overloaded method {@link Check#notEmpty(Object[], String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param array * a map which should not be empty * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code array} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code array} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T> T[] notEmpty(final boolean condition, @Nonnull final T[] array) { if (condition) { Check.notEmpty(array); } return array; } /** * Ensures that a passed map as a parameter of the calling method is not empty. * * @param array * a map which should not be empty * @param name * name of object reference (in source code) * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code array} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code array} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T> T[] notEmpty(final boolean condition, @Nonnull final T[] array, @Nullable final String name) { if (condition) { Check.notEmpty(array, name); } return array; } /** * Ensures that a double argument is not NaN (not a number). * * <p> * We recommend to use the overloaded method {@link Check#notNaN(double, String)} and pass as second argument the * name of the parameter to enhance the exception message. * * @see java.lang.Double#NaN * * @param value * value which should not be NaN * @return the given double value * @throws IllegalNaNArgumentException * if the given argument {@code value} is NaN */ @Throws({ IllegalNaNArgumentException.class }) public static double notNaN(final boolean condition, final double value) { if (condition) { Check.notNaN(value); } return value; } /** * Ensures that a double argument is not NaN (not a number). * * @see java.lang.Double#NaN * * @param value * value which should not be NaN * @param name * name of object reference (in source code) * @return the given double value * @throws IllegalNaNArgumentException * if the given argument {@code value} is NaN */ @Throws({ IllegalNaNArgumentException.class }) public static double notNaN(final boolean condition, final double value, @Nullable final String name) { if (condition) { Check.notNaN(value, name); } return value; } /** * Ensures that a double argument is not NaN (not a number). * * <p> * We recommend to use the overloaded method {@link Check#notNaN(float, String)} and pass as second argument the * name of the parameter to enhance the exception message. * * @see java.lang.Float#NaN * * @param value * value which should not be NaN * @return the given double value * @throws IllegalNaNArgumentException * if the given argument {@code value} is NaN */ @Throws({ IllegalNaNArgumentException.class }) public static float notNaN(final boolean condition, final float value) { if (condition) { Check.notNaN(value); } return value; } /** * Ensures that a double argument is not NaN (not a number). * * @see java.lang.Float#NaN * * @param value * value which should not be NaN * @param name * name of object reference (in source code) * @return the given float value * @throws IllegalNaNArgumentException * if the given argument {@code value} is NaN */ @Throws({ IllegalNaNArgumentException.class }) public static float notNaN(final boolean condition, final float value, @Nullable final String name) { if (condition) { Check.notNaN(value, name); } return value; } /** * Ensures that an integer reference passed as a parameter to the calling method is not smaller than {@code 0}. * * <p> * We recommend to use the overloaded method {@link Check#notNegative(int, String)} and pass as second argument the * name of the parameter to enhance the exception message. * * @param value * a number * @param name * name of object reference (in source code) * @return the non-null reference that was validated * @throws IllegalNegativeArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalNullArgumentException.class) public static int notNegative(final boolean condition, @Nonnull final int value) { if (condition) { Check.notNegative(value); } return value; } /** * Ensures that an integer reference passed as a parameter to the calling method is not smaller than {@code 0}. * * @param value * a number * @param name * name of object reference (in source code) * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalNegativeArgumentException.class) public static int notNegative(final boolean condition, @Nonnull final int value, @Nullable final String name) { if (condition) { Check.notNegative(value, name); } return value; } /** * Ensures that an object reference passed as a parameter to the calling method is not {@code null}. * * <p> * We recommend to use the overloaded method {@link Check#notNull(Object, String)} and pass as second argument the * name of the parameter to enhance the exception message. * * @param reference * an object reference * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is {@code null} */ @Throws(IllegalNullArgumentException.class) public static <T> T notNull(final boolean condition, @Nonnull final T reference) { if (condition) { Check.notNull(reference); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not {@code null}. * * @param reference * an object reference * @param name * name of object reference (in source code) * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is {@code null} */ @Throws(IllegalNullArgumentException.class) public static <T> T notNull(final boolean condition, @Nonnull final T reference, @Nullable final String name) { if (condition) { Check.notNull(reference, name); } return reference; } /** * Ensures that a given position index is valid within the size of an array, list or string ... * * @param index * index of an array, list or string * @param size * size of an array list or string * @return the index * * @throws IllegalPositionIndexException * if the index is not a valid position index within an array, list or string of size <em>size</em> * */ @Throws(IllegalPositionIndexException.class) public static int positionIndex(final boolean condition, final int index, final int size) { if (condition) { Check.positionIndex(index, size); } return index; } /** * Ensures that the given arguments are a valid range. * * A range (<em>start</em>, <em>end</em>, <em>size</em>) is valid if the following conditions are {@code true}: * <ul> * <li>start <= size</li> * <li>end <= size</li> * <li>start <= end</li> * <li>size >= 0</li> * <li>start >= 0</li> * <li>end >= 0</li> * </ul> * * @param start * the start value of the range (must be a positive integer or 0) * @param end * the end value of the range (must be a positive integer or 0) * @param size * the size value of the range (must be a positive integer or 0) * * @throws IllegalRangeException * if the given arguments do not form a valid range */ @Throws(IllegalRangeException.class) public static void range(final boolean condition, @Nonnegative final int start, @Nonnegative final int end, @Nonnegative final int size) { if (condition) { Check.range(start, end, size); } } /** * Ensures that a given state is {@code true}. * * <p> * We recommend to use the overloaded method {@link Check#stateIsTrue(boolean, String)} and pass as second argument * the name of the parameter to enhance the exception message. A better way is to create specific exceptions (with a * good wording) for your case and to use the overloaded method {@link Check#stateIsTrue(boolean, Class)} and pass * as second argument your exception. * * @param expression * an expression that must be true to indicate a valid state * * @throws IllegalStateOfArgumentException * if the given arguments caused an invalid state */ @Throws(IllegalStateOfArgumentException.class) public static void stateIsTrue(final boolean condition, final boolean expression) { if (condition) { Check.stateIsTrue(expression); } } /** * Ensures that a given state is {@code true} and allows to specify the class of exception which is thrown in case * the state is not {@code true}. * * @param expression * an expression that must be {@code true} to indicate a valid state * @param clazz * an subclass of {@link RuntimeException} which will be thrown if the given state is not valid * @throws clazz * a new instance of {@code clazz} if the given arguments caused an invalid state * @throws RuntimeInstantiationException * <strong>Attention</strong>: Be aware, that a {@code RuntimeInstantiationException} can be thrown when * the given {@code clazz} cannot be instantiated */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, RuntimeInstantiationException.class }) public static void stateIsTrue(final boolean condition, final boolean expression, final Class<? extends RuntimeException> clazz) { if (condition) { Check.stateIsTrue(expression, clazz); } } /** * Ensures that a given state is {@code true}. * * @param expression * an expression that must be {@code true} to indicate a valid state * @param description * will be used in the error message to describe why the arguments caused an invalid state * @throws IllegalStateOfArgumentException * if the given arguments caused an invalid state */ @Throws(IllegalStateOfArgumentException.class) public static void stateIsTrue(final boolean condition, final boolean expression, @Nonnull final String description) { if (condition) { Check.stateIsTrue(expression, description); } } /** * Ensures that a given state is {@code true} * * @param expression * an expression that must be {@code true} to indicate a valid state * @param descriptionTemplate * format string template that explains why the state is invalid * @param descriptionTemplateArgs * format string template arguments to explain why the state is invalid * @throws IllegalStateOfArgumentException * if the given arguments caused an invalid state */ @Throws(IllegalStateOfArgumentException.class) public static void stateIsTrue(final boolean condition, final boolean expression, @Nonnull final String descriptionTemplate, final Object... descriptionTemplateArgs) { if (condition) { Check.stateIsTrue(expression, descriptionTemplate, descriptionTemplateArgs); } } /** * <strong>Attention:</strong> This class is not intended to create objects from it. */ private ConditionalCheck() { // This class is not intended to create objects from it. } }
modules/quality-check/src/main/java/net/sf/qualitycheck/ConditionalCheck.java
Initial implementation of the class ConditionalCheck. JavaDoc is still missing, as well as tests.
modules/quality-check/src/main/java/net/sf/qualitycheck/ConditionalCheck.java
Initial implementation of the class ConditionalCheck. JavaDoc is still missing, as well as tests.
Java
apache-2.0
error: pathspec 'src/main/java/com/harms/stash/plugin/jenkins/job/settings/servlet/JenkinsStashBaseServlet.java' did not match any file(s) known to git
563599b87d1826147583fa04bb7de75d65e26ecd
1
umbrew/stash-pullrequest-jenkins,umbrew/stash-pullrequest-jenkins
package com.harms.stash.plugin.jenkins.job.settings.servlet; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.atlassian.sal.api.auth.LoginUriProvider; import com.atlassian.sal.api.user.UserManager; import com.atlassian.sal.api.user.UserProfile; public class JenkinsStashBaseServlet extends HttpServlet { private static final long serialVersionUID = 49L; protected final LoginUriProvider loginUriProvider; protected final UserManager userManager; public JenkinsStashBaseServlet(LoginUriProvider loginUriProvider, UserManager userManager) { this.loginUriProvider = loginUriProvider; this.userManager = userManager; } protected void redirectToLogin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { URI uri; try { final String contentType = request.getContentType(); if (contentType != null && contentType.contains("application/x-www-form-urlencoded")) { uri = new URI(request.getHeader("referer")); response.setStatus(HttpServletResponse.SC_OK); response.setContentType("application/json"); response.getWriter().print("{ "+ "\"redirect\" : \""+loginUriProvider.getLoginUri(uri).toASCIIString()+ "\"}"); response.getWriter().flush(); } else { uri = new URI(request.getRequestURI()); response.sendRedirect(loginUriProvider.getLoginUri(uri).toASCIIString()); } } catch (URISyntaxException e) { throw new ServletException(e.getMessage()); } } @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { UserProfile user = userManager.getRemoteUser(req); if (user == null) { redirectToLogin(req, resp); return; } super.service(req, resp); } }
src/main/java/com/harms/stash/plugin/jenkins/job/settings/servlet/JenkinsStashBaseServlet.java
Added missing file
src/main/java/com/harms/stash/plugin/jenkins/job/settings/servlet/JenkinsStashBaseServlet.java
Added missing file
Java
apache-2.0
error: pathspec 'iserve-importer-sawsdl/src/main/java/uk/ac/open/kmi/iserve/importer/sawsdl/SawsdlTransformer.java' did not match any file(s) known to git
a64158f1b05abdda767324944187e1591d8440a8
1
kmi/iserve,kmi/iserve,kmi/iserve,kmi/iserve
/* * Copyright (c) 2013. Knowledge Media Institute - The Open University * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.ac.open.kmi.iserve.importer.sawsdl; import com.ebmwebsourcing.easybox.api.*; import com.ebmwebsourcing.easysawsdl10.api.SawsdlHelper; import com.ebmwebsourcing.easyschema10.api.SchemaXmlObject; import com.ebmwebsourcing.easyschema10.api.element.Element; import com.ebmwebsourcing.easyschema10.api.type.Type; import com.ebmwebsourcing.easywsdl11.api.element.*; import com.ebmwebsourcing.easywsdl11.api.type.TBindingOperationMessage; import com.ebmwebsourcing.easywsdl11.api.type.TDocumented; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.InputSource; import uk.ac.open.kmi.iserve.commons.io.URIUtil; import uk.ac.open.kmi.iserve.commons.model.AnnotableResource; import uk.ac.open.kmi.iserve.commons.model.MessageContent; import uk.ac.open.kmi.iserve.commons.model.MessagePart; import uk.ac.open.kmi.iserve.commons.model.Resource; import uk.ac.open.kmi.iserve.sal.exception.ImporterException; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.TransformerFactory; import javax.xml.xpath.XPathFactory; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.security.CodeSource; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; /** * SawsdlTransformer * New transformer based on EasyWSDL * <p/> * <p/> * Author: Carlos Pedrinaci (KMi - The Open University) * Date: 03/07/2013 * Time: 13:42 */ public class SawsdlTransformer { private static final Logger log = LoggerFactory.getLogger(SawsdlTransformer.class); private final XmlContextFactory xmlContextFactory; private final XmlContext xmlContext; private final XmlObjectReader reader; public SawsdlTransformer() throws ImporterException { // create factory: can be static xmlContextFactory = new XmlContextFactory(); // create context: can be static xmlContext = xmlContextFactory.newContext(); // create generic reader: cannot be static!!! not thread safe!!! reader = xmlContext.createReader(); // Set the parsing properties // System.setProperty("javax.xml.xpath.XPathFactory", // "net.sf.saxon.xpath.XPathFactoryImpl"); // // System.setProperty("javax.xml.transform.TransformerFactory", // "net.sf.saxon.TransformerFactoryImpl"); // // System.setProperty("javax.xml.parsers.DocumentBuilderFactory", // "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"); // // System.setProperty("javax.xml.parsers.SAXParserFactory", // "com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl"); log.debug(this.getJaxpImplementationInfo("DocumentBuilderFactory", DocumentBuilderFactory.newInstance().getClass())); log.debug(this.getJaxpImplementationInfo("XPathFactory", XPathFactory.newInstance().getClass())); log.debug(this.getJaxpImplementationInfo("TransformerFactory", TransformerFactory.newInstance().getClass())); log.debug(this.getJaxpImplementationInfo("SAXParserFactory", SAXParserFactory.newInstance().getClass())); } private String getJaxpImplementationInfo(String componentName, Class componentClass) { CodeSource source = componentClass.getProtectionDomain().getCodeSource(); return MessageFormat.format( "{0} implementation: {1} loaded from: {2}", componentName, componentClass.getCanonicalName(), source == null ? "Java Runtime" : source.getLocation()); } public List<uk.ac.open.kmi.iserve.commons.model.Service> transform(InputStream originalDescription, String baseUri) throws ImporterException { List<uk.ac.open.kmi.iserve.commons.model.Service> msmServices = new ArrayList<uk.ac.open.kmi.iserve.commons.model.Service>(); if (originalDescription == null) return msmServices; Definitions definitions; try { InputSource is = new InputSource(originalDescription); definitions = reader.readDocument(originalDescription, Definitions.class); if (definitions == null) return msmServices; uk.ac.open.kmi.iserve.commons.model.Service msmSvc; Service[] wsdlServices = definitions.getServices(); for (Service wsdlSvc : wsdlServices) { msmSvc = transform(wsdlSvc); if (msmSvc != null) msmServices.add(msmSvc); } return msmServices; } catch (XmlObjectReadException e) { log.error("Problems reading XML Object exception while parsing service", e); throw new ImporterException("Problems reading XML Object exception while parsing service", e); } } private uk.ac.open.kmi.iserve.commons.model.Service transform(Service wsdlSvc) { uk.ac.open.kmi.iserve.commons.model.Service msmSvc = null; if (wsdlSvc == null) return msmSvc; QName qname = wsdlSvc.inferQName(); try { // Use WSDL 2.0 naming http://www.w3.org/TR/wsdl20/#wsdl-iri-references StringBuilder builder = new StringBuilder(). append(qname.getNamespaceURI()).append("#"). append("wsdl.service").append("(").append(qname.getLocalPart()).append(")"); URI svcUri = new URI(builder.toString()); msmSvc = new uk.ac.open.kmi.iserve.commons.model.Service(svcUri); msmSvc.setSource(svcUri); msmSvc.setWsdlGrounding(svcUri); msmSvc.setLabel(qname.getLocalPart()); // Add documentation addComment(wsdlSvc, msmSvc); addModelReferences(wsdlSvc, msmSvc); // Process Operations URI baseUri; uk.ac.open.kmi.iserve.commons.model.Operation msmOp; Port[] ports = wsdlSvc.getPorts(); for (Port port : ports) { if (port.hasBinding()) { BindingOperation[] operations = port.findBinding().getOperations(); for (BindingOperation operation : operations) { msmOp = transform(operation, URIUtil.getNameSpace(svcUri), port.getName()); msmSvc.addOperation(msmOp); } } } } catch (URISyntaxException e) { log.error("Syntax exception while generating service URI", e); } return msmSvc; } private uk.ac.open.kmi.iserve.commons.model.Operation transform(BindingOperation wsdlOp, String namespace, String portName) { uk.ac.open.kmi.iserve.commons.model.Operation msmOp = null; if (wsdlOp == null) return msmOp; StringBuilder builder = new StringBuilder(namespace).append("#"). append("wsdl.interfaceOperation"). append("(").append(portName).append("/").append(wsdlOp.getName()).append(")"); URI opUri = null; try { opUri = new URI(builder.toString()); msmOp = new uk.ac.open.kmi.iserve.commons.model.Operation(opUri); msmOp.setSource(opUri); msmOp.setWsdlGrounding(opUri); msmOp.setLabel(wsdlOp.getName()); // Add documentation addComment(wsdlOp, msmOp); // Add model references addModelReferences(wsdlOp, msmOp); // Process Inputs, Outputs and Faults BindingOperationInput input = wsdlOp.getInput(); MessageContent mcIn = transform(input, namespace, portName, wsdlOp.getName()); msmOp.addInput(mcIn); addModelReferences(input, mcIn); // addSchemaMappings(input, mcIn); BindingOperationOutput output = wsdlOp.getOutput(); MessageContent mcOut = transform(output, namespace, portName, wsdlOp.getName()); msmOp.addOutput(mcOut); addModelReferences(output, mcOut); // addSchemaMappings(output, mcOut); // TODO: Process faults } catch (URISyntaxException e) { log.error("Syntax exception while generating operation URI", e); } return msmOp; } private MessageContent transform(TBindingOperationMessage message, String namespace, String portName, String opName) { MessageContent mc = null; if (message == null) return mc; String direction = (message instanceof BindingOperationInput) ? "In" : "Out"; StringBuilder builder = new StringBuilder(namespace).append("#"). append("wsdl.interfaceMessageReference"). append("(").append(portName).append("/").append(opName).append("/").append(direction).append(")"); URI mcUri = null; try { mcUri = new URI(builder.toString()); mc = new MessageContent(mcUri); mc.setSource(mcUri); mc.setWsdlGrounding(mcUri); mc.setLabel(message.getName()); addComment(message, mc); // Process parts // List<Part> parts = message.getParts(); // for (Part part : parts) { // mc.addMandatoryPart(transform(part)); // } } catch (URISyntaxException e) { log.error("Syntax exception while generating message URI", e); } return mc; } private void addComment(TDocumented element, Resource resource) { Documentation doc = element.getDocumentation(); if (doc != null && doc.getContent() != null && !doc.getContent().isEmpty()) resource.setComment(doc.getContent()); } private MessagePart transform(Part part) { return null; //To change body of created methods use File | Settings | File Templates. } private void addModelReferences(XmlObject object, AnnotableResource annotableResource) { URI[] modelRefs = SawsdlHelper.getModelReference(object); for (URI modelRef : modelRefs) { annotableResource.addModelReference(new Resource(modelRef)); } } private void addSchemaMappings(SchemaXmlObject object, MessagePart message) { // Handle liftingSchemaMappings (only on elements or types) if (object == null) return; URI[] liftList = null; URI[] lowerList = null; if (object instanceof Type) { liftList = SawsdlHelper.getLiftingSchemaMapping((Type) object); lowerList = SawsdlHelper.getLoweringSchemaMapping((Type) object); } else if (object instanceof Element) { liftList = SawsdlHelper.getLiftingSchemaMapping((Element) object); lowerList = SawsdlHelper.getLoweringSchemaMapping((Element) object); } for (URI liftUri : liftList) { message.addLiftingSchemaMapping(liftUri); } for (URI lowerUri : lowerList) { message.addLiftingSchemaMapping(lowerUri); } } }
iserve-importer-sawsdl/src/main/java/uk/ac/open/kmi/iserve/importer/sawsdl/SawsdlTransformer.java
Added the new SAWSDL importer. Still a few things to smooth when obtaining SAWSDL annotations using EasyWSDL. Developers contacted.
iserve-importer-sawsdl/src/main/java/uk/ac/open/kmi/iserve/importer/sawsdl/SawsdlTransformer.java
Added the new SAWSDL importer. Still a few things to smooth when obtaining SAWSDL annotations using EasyWSDL. Developers contacted.
Java
apache-2.0
error: pathspec 'openregistry-webapp/src/main/java/org/openregistry/core/web/resources/NetIdManagementResource.java' did not match any file(s) known to git
ecc40d72fa4fbedf6baf74104cd3cf1961fe6441
1
Jasig/openregistry,Unicon/openregistry,Unicon/openregistry,Unicon/openregistry,Jasig/openregistry,Unicon/openregistry,sheliu/openregistry,msidd/openregistry,sheliu/openregistry,Rutgers-IDM/openregistry,Rutgers-IDM/openregistry,Unicon/openregistry,msidd/openregistry,Jasig/openregistry,sheliu/openregistry,Rutgers-IDM/openregistry,Jasig/openregistry,Jasig/openregistry,Rutgers-IDM/openregistry,Jasig/openregistry,Rutgers-IDM/openregistry,msidd/openregistry,sheliu/openregistry,sheliu/openregistry,Unicon/openregistry,msidd/openregistry,msidd/openregistry,Unicon/openregistry
package org.openregistry.core.web.resources; import org.openregistry.core.service.identifier.NetIdManagementService; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; /** * RESTful resource used to expose functionality of managing the netids of canonical registry Persons * * @since 1.0 */ @Named @Singleton @Path("/netid") public class NetIdManagementResource { private static final String PRIMARY_YES_FLAG = "Y"; private static final String PRIMARY_NO_FLAG = "N"; private NetIdManagementService netIdManagementService; @Inject public NetIdManagementResource(NetIdManagementService netIdManagementService) { this.netIdManagementService = netIdManagementService; } @POST @Path("{currentNetId}") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response changeNetId(@FormParam("newNetId") String newNetIdValue, @DefaultValue("true") @FormParam("primary") boolean primary) { return null; } }
openregistry-webapp/src/main/java/org/openregistry/core/web/resources/NetIdManagementResource.java
NOJIRA: NetIdManagementResource initial checkin git-svn-id: 996c6d7d570f9e8d676b69394667d4ecb3e4cdb3@23116 1580c273-15eb-1042-8a87-dc5d815c88a0
openregistry-webapp/src/main/java/org/openregistry/core/web/resources/NetIdManagementResource.java
NOJIRA: NetIdManagementResource initial checkin
Java
apache-2.0
error: pathspec 'saturn-console-core/src/main/java/com/vip/saturn/job/console/service/StatisticsRefreshService.java' did not match any file(s) known to git
04fd7cd73e1e4d5eac7d227dea4fbf689b8084cd
1
vipshop/Saturn,vipshop/Saturn,vipshop/Saturn,vipshop/Saturn,vipshop/Saturn
package com.vip.saturn.job.console.service; import com.vip.saturn.job.console.exception.SaturnJobConsoleException; /** * @author timmy.hu */ public interface StatisticsRefreshService { void refreshStatistics(String zkClusterKey) throws SaturnJobConsoleException; void refreshStatistics2DB(boolean force); void refreshStatistics2DB(String zkClusterKey) throws SaturnJobConsoleException; }
saturn-console-core/src/main/java/com/vip/saturn/job/console/service/StatisticsRefreshService.java
#289 update code
saturn-console-core/src/main/java/com/vip/saturn/job/console/service/StatisticsRefreshService.java
#289 update code
Java
apache-2.0
error: pathspec 'allure-junit/allure-junit-adaptor/src/main/java/ru/yandex/qatools/allure/junit/AllureRunListener.java' did not match any file(s) known to git
cb6a7780e5109a1d6eea7ef1d6a594721800f30d
1
allure-framework/allure-core,allure-framework/allure1,allure-framework/allure-core,wuhuizuo/allure-core,allure-framework/allure1,allure-framework/allure-core,allure-framework/allure1,wuhuizuo/allure-core,allure-framework/allure1,wuhuizuo/allure-core,allure-framework/allure-core,wuhuizuo/allure-core
package ru.yandex.qatools.allure.junit; import org.junit.runner.Description; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; import ru.yandex.qatools.allure.Allure; import ru.yandex.qatools.allure.events.*; import ru.yandex.qatools.allure.utils.AnnotationManager; import java.lang.annotation.Annotation; import java.util.*; /** * @author Dmitry Baev charlie@yandex-team.ru * Date: 20.12.13 */ @SuppressWarnings("unused") public class AllureRunListener extends RunListener { private Allure lifecycle = Allure.LIFECYCLE; private static final Map<String, String> suites = new HashMap<>(); @Override public void testStarted(Description description) throws Exception { String suiteUid = getSuiteUid(description); TestCaseStartedEvent event = new TestCaseStartedEvent(suiteUid, description.getMethodName()); AnnotationManager am = new AnnotationManager(description.getAnnotations()); am.update(event); Allure.LIFECYCLE.fire(event); } @Override public void testFinished(Description description) throws Exception { Allure.LIFECYCLE.fire(new TestCaseFinishedEvent()); } @Override public void testFailure(Failure failure) throws Exception { Allure.LIFECYCLE.fire(new TestCaseFailureEvent().withThrowable(failure.getException())); } @Override public void testAssumptionFailure(Failure failure) { Allure.LIFECYCLE.fire(new TestCaseSkippedEvent().withThrowable(failure.getException())); } @Override public void testIgnored(Description description) throws Exception { //if test class annotated with @Ignored if (description.getMethodName() == null) { return; } testStarted(description); Allure.LIFECYCLE.fire(new TestCaseSkippedEvent().withThrowable(new Exception("Test ignored."))); testFinished(description); } @Override public void testRunFinished(Result result) throws Exception { for (String uid : suites.values()) { testSuiteFinished(uid); } } public void testSuiteStarted(String uid, String suiteName, Collection<Annotation> annotations) { TestSuiteStartedEvent event = new TestSuiteStartedEvent(uid, suiteName); AnnotationManager am = new AnnotationManager(annotations); am.update(event); Allure.LIFECYCLE.fire(event); } public void testSuiteFinished(String uid) { Allure.LIFECYCLE.fire(new TestSuiteFinishedEvent(uid)); } private String getSuiteUid(Description description) { String suiteName = description.getClassName(); Collection<Annotation> annotations = Arrays.asList(description.getTestClass().getAnnotations()); if (!suites.containsKey(suiteName)) { String uid = UUID.randomUUID().toString(); testSuiteStarted(uid, suiteName, annotations); suites.put(suiteName, uid); return uid; } return suites.get(suiteName); } public Allure getLifecycle() { return lifecycle; } public void setLifecycle(Allure lifecycle) { this.lifecycle = lifecycle; } }
allure-junit/allure-junit-adaptor/src/main/java/ru/yandex/qatools/allure/junit/AllureRunListener.java
Added junit run listener.
allure-junit/allure-junit-adaptor/src/main/java/ru/yandex/qatools/allure/junit/AllureRunListener.java
Added junit run listener.
Java
bsd-3-clause
1b944606f6f6c98c5f06636bd44ebb8890f9b6f4
0
rnathanday/dryad-repo,jamie-dryad/dryad-repo,jimallman/dryad-repo,jamie-dryad/dryad-repo,ojacobson/dryad-repo,jamie-dryad/dryad-repo,mdiggory/dryad-repo,ojacobson/dryad-repo,mdiggory/dryad-repo,ojacobson/dryad-repo,jimallman/dryad-repo,rnathanday/dryad-repo,mdiggory/dryad-repo,ojacobson/dryad-repo,ojacobson/dryad-repo,jamie-dryad/dryad-repo,jimallman/dryad-repo,rnathanday/dryad-repo,mdiggory/dryad-repo,jamie-dryad/dryad-repo,rnathanday/dryad-repo,ojacobson/dryad-repo,rnathanday/dryad-repo,rnathanday/dryad-repo,jimallman/dryad-repo,mdiggory/dryad-repo,jimallman/dryad-repo,jimallman/dryad-repo
/* * Browse.java * * Version: $Revision$ * * Date: $Date$ * * Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts * Institute of Technology. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the Hewlett-Packard Company nor the name of the * Massachusetts Institute of Technology nor the names of their * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.dspace.browse; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.WeakHashMap; import org.apache.log4j.Logger; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.DCValue; import org.dspace.content.Item; import org.dspace.content.ItemComparator; import org.dspace.content.ItemIterator; import org.dspace.core.ConfigurationManager; import org.dspace.core.Context; import org.dspace.storage.rdbms.DatabaseManager; import org.dspace.storage.rdbms.TableRow; /** * API for Browsing Items in DSpace by title, author, or date. Browses only * return archived Items. * * @author Peter Breton * @version $Revision$ */ public class Browse { // Browse types static final int AUTHORS_BROWSE = 0; static final int ITEMS_BY_TITLE_BROWSE = 1; static final int ITEMS_BY_AUTHOR_BROWSE = 2; static final int ITEMS_BY_DATE_BROWSE = 3; static final int SUBJECTS_BROWSE = 4; static final int ITEMS_BY_SUBJECT_BROWSE = 5; /** Log4j log */ private static Logger log = Logger.getLogger(Browse.class); /** * Constructor */ private Browse() { } /** * Return distinct Authors in the given scope. Author refers to a Dublin * Core field with element <em>contributor</em> and qualifier * <em>author</em>. * * <p> * Results are returned in alphabetical order. * </p> * * @param scope * The BrowseScope * @return A BrowseInfo object, the results of the browse * @exception SQLException * If a database error occurs */ public static BrowseInfo getAuthors(BrowseScope scope) throws SQLException { scope.setBrowseType(AUTHORS_BROWSE); scope.setAscending(true); scope.setSortByTitle(null); return doBrowse(scope); } /** * Return distinct Subjects in the given scope. Subjects refers to a Dublin * Core field with element <em>subject</em> and qualifier * <em>*</em>. * * <p> * Results are returned in alphabetical order. * </p> * * @param scope * The BrowseScope * @return A BrowseInfo object, the results of the browse * @exception SQLException * If a database error occurs */ public static BrowseInfo getSubjects(BrowseScope scope) throws SQLException { scope.setBrowseType(SUBJECTS_BROWSE); scope.setAscending(true); scope.setSortByTitle(null); return doBrowse(scope); } /** * Return Items indexed by title in the given scope. Title refers to a * Dublin Core field with element <em>title</em> and no qualifier. * * <p> * Results are returned in alphabetical order; that is, the Item with the * title which is first in alphabetical order will be returned first. * </p> * * @param scope * The BrowseScope * @return A BrowseInfo object, the results of the browse * @exception SQLException * If a database error occurs */ public static BrowseInfo getItemsByTitle(BrowseScope scope) throws SQLException { scope.setBrowseType(ITEMS_BY_TITLE_BROWSE); scope.setAscending(true); scope.setSortByTitle(null); return doBrowse(scope); } /** * Return Items indexed by date in the given scope. Date refers to a Dublin * Core field with element <em>date</em> and qualifier <em>issued</em>. * * <p> * If oldestfirst is true, the dates returned are the ones after the focus, * ordered from earliest to latest. Otherwise the dates are the ones before * the focus, and ordered from latest to earliest. For example: * </p> * * <p> * For example, if the focus is <em>1995</em>, and oldestfirst is true, * the results might look like this: * </p> * * <code>1993, 1994, 1995 (the focus), 1996, 1997.....</code> * * <p> * While if the focus is <em>1995</em>, and oldestfirst is false, the * results would be: * </p> * * <code>1997, 1996, 1995 (the focus), 1994, 1993 .....</code> * * @param scope * The BrowseScope * @param oldestfirst * If true, the dates returned are the ones after focus, ordered * from earliest to latest; otherwise the dates are the ones * before focus, ordered from latest to earliest. * @return A BrowseInfo object, the results of the browse * @exception SQLException * If a database error occurs */ public static BrowseInfo getItemsByDate(BrowseScope scope, boolean oldestfirst) throws SQLException { scope.setBrowseType(ITEMS_BY_DATE_BROWSE); scope.setAscending(oldestfirst); scope.setSortByTitle(null); return doBrowse(scope); } /** * <p> * Return Items in the given scope by the author (exact match). The focus of * the BrowseScope is the author to use; using a BrowseScope without a focus * causes an IllegalArgumentException to be thrown. * </p> * * <p> * Author refers to a Dublin Core field with element <em>contributor</em> * and qualifier <em>author</em>. * </p> * * @param scope * The BrowseScope * @param sortByTitle * If true, the returned items are sorted by title; otherwise * they are sorted by date issued. * @return A BrowseInfo object, the results of the browse * @exception SQLException * If a database error occurs */ public static BrowseInfo getItemsByAuthor(BrowseScope scope, boolean sortByTitle) throws SQLException { if (!scope.hasFocus()) { throw new IllegalArgumentException( "Must specify an author for getItemsByAuthor"); } if (!(scope.getFocus() instanceof String)) { throw new IllegalArgumentException( "The focus for getItemsByAuthor must be a String"); } scope.setBrowseType(ITEMS_BY_AUTHOR_BROWSE); scope.setAscending(true); scope.setSortByTitle(sortByTitle ? Boolean.TRUE : Boolean.FALSE); scope.setTotalAll(); return doBrowse(scope); } /** * <p> * Return Items in the given scope by the subject (exact match). The focus of * the BrowseScope is the subject to use; using a BrowseScope without a focus * causes an IllegalArgumentException to be thrown. * </p> * * <p> * Subject refers to a Dublin Core field with element <em>subject</em> * and qualifier <em>*</em>. * </p> * * @param scope * The BrowseScope * @param sortByTitle * If true, the returned items are sorted by title; otherwise * they are sorted by date issued. * @return A BrowseInfo object, the results of the browse * @exception SQLException * If a database error occurs */ public static BrowseInfo getItemsBySubject(BrowseScope scope, boolean sortByTitle) throws SQLException { if (!scope.hasFocus()) { throw new IllegalArgumentException( "Must specify a subject for getItemsBySubject"); } if (!(scope.getFocus() instanceof String)) { throw new IllegalArgumentException( "The focus for getItemsBySubject must be a String"); } scope.setBrowseType(ITEMS_BY_SUBJECT_BROWSE); scope.setAscending(true); scope.setSortByTitle(sortByTitle ? Boolean.TRUE : Boolean.FALSE); scope.setTotalAll(); return doBrowse(scope); } /** * Returns the last items submitted to DSpace in the given scope. * * @param scope * The Browse Scope * @return A List of Items submitted * @exception SQLException * If a database error occurs */ public static List getLastSubmitted(BrowseScope scope) throws SQLException { Context context = scope.getContext(); String sql = getLastSubmittedQuery(scope); if (log.isDebugEnabled()) { log.debug("SQL for last submitted is \"" + sql + "\""); } List results = DatabaseManager.query(context, sql).toList(); return getLastSubmittedResults(context, results); } /** * Return the SQL used to determine the last submitted Items for scope. * * @param scope * @return String query string */ private static String getLastSubmittedQuery(BrowseScope scope) { String table = getLastSubmittedTable(scope); String query = "SELECT * FROM " + table + getScopeClause(scope, "where") + " ORDER BY date_accessioned DESC"; if (!scope.hasNoLimit()) { if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) { // Oracle version of LIMIT...OFFSET - must use a sub-query and // ROWNUM query = "SELECT * FROM (" + query + ") WHERE ROWNUM <=" + scope.getTotal(); } else { // postgres, use LIMIT query = query + " LIMIT " + scope.getTotal(); } } return query; } /** * Return the name of the Browse index table to query for last submitted * items in the given scope. * * @param scope * @return name of table */ private static String getLastSubmittedTable(BrowseScope scope) { if (scope.isCommunityScope()) { return "CommunityItemsByDateAccession"; } else if (scope.isCollectionScope()) { return "CollectionItemsByDateAccession"; } return "ItemsByDateAccessioned"; } /** * Transform the query results into a List of Items. * * @param context * @param results * @return list of items * @throws SQLException */ private static List getLastSubmittedResults(Context context, List results) throws SQLException { if ((results == null) || (results.isEmpty())) { return Collections.EMPTY_LIST; } List items = new ArrayList(); // FIXME This seems like a very common need, so might // be factored out at some point. for (Iterator iterator = results.iterator(); iterator.hasNext();) { TableRow row = (TableRow) iterator.next(); Item item = Item.find(context, row.getIntColumn("item_id")); items.add(item); } return items; } //////////////////////////////////////// // Index maintainence methods //////////////////////////////////////// /** * This method should be called whenever an item is removed. * * @param context * The current DSpace context * @param id * The id of the item which has been removed * @exception SQLException * If a database error occurs */ public static void itemRemoved(Context context, int id) throws SQLException { String sql = "delete from {0} where item_id = " + id; String[] browseTables = BrowseTables.tables(); for (int i = 0; i < browseTables.length; i++) { String query = MessageFormat.format(sql, new String[] { browseTables[i] }); DatabaseManager.updateQuery(context, query); } } /** * This method should be called whenever an item has changed. Changes * include: * * <ul> * <li>DC values are added, removed, or modified * <li>the value of the in_archive flag changes * </ul> * * @param context - * The database context * @param item - * The item which has been added * @exception SQLException - * If a database error occurs */ public static void itemChanged(Context context, Item item) throws SQLException { // This is a bit heavy-weight, but without knowing what // changed, it's easiest just to replace the values // en masse. itemRemoved(context, item.getID()); if (!item.isArchived()) { return; } itemAdded(context, item); } /** * This method should be called whenever an item is added. * * @param context * The current DSpace context * @param item * The item which has been added * @exception SQLException * If a database error occurs */ public static void itemAdded(Context context, Item item) throws SQLException { // add all parent communities to communities2item table Community[] parents = item.getCommunities(); for (int j = 0; j < parents.length; j++) { TableRow row = DatabaseManager.create(context, "Communities2Item"); row.setColumn("item_id", item.getID()); row.setColumn("community_id", parents[j].getID()); DatabaseManager.update(context, row); } // get the metadata fields to index in the title and date tables // get the date, title and author fields String dateField = ConfigurationManager.getProperty("webui.browse.index.date"); if (dateField == null) { dateField = "dc.date.issued"; } String titleField = ConfigurationManager.getProperty("webui.browse.index.title"); if (titleField == null) { titleField = "dc.title"; } String authorField = ConfigurationManager.getProperty("webui.browse.index.author"); if (authorField == null) { authorField = "dc.contributor.*"; } String subjectField = ConfigurationManager.getProperty("webui.browse.index.subject"); if (subjectField == null) { subjectField = "dc.subject.*"; } // get the DC values for each of these fields DCValue[] titleArray = getMetadataField(item, titleField); DCValue[] dateArray = getMetadataField(item, dateField); DCValue[] authorArray = getMetadataField(item, authorField); DCValue[] subjectArray = getMetadataField(item, subjectField); // now build the data map Map table2dc = new HashMap(); table2dc.put("ItemsByTitle", titleArray); table2dc.put("ItemsByAuthor", authorArray); table2dc.put("ItemsByDate", dateArray); table2dc.put("ItemsByDateAccessioned", item.getDC("date", "accessioned", Item.ANY)); table2dc.put("ItemsBySubject", subjectArray); for (Iterator iterator = table2dc.keySet().iterator(); iterator .hasNext();) { String table = (String) iterator.next(); DCValue[] dc = (DCValue[]) table2dc.get(table); for (int i = 0; i < dc.length; i++) { TableRow row = DatabaseManager.create(context, table); row.setColumn("item_id", item.getID()); String value = dc[i].value; if ("ItemsByDateAccessioned".equals(table)) { row.setColumn("date_accessioned", value); } else if ("ItemsByDate".equals(table)) { row.setColumn("date_issued", value); } else if ("ItemsByAuthor".equals(table)) { // author name, and normalized sorting name // (which for now is simple lower-case) row.setColumn("author", value); row.setColumn("sort_author", value.toLowerCase()); } else if ("ItemsByTitle".equals(table)) { String title = NormalizedTitle.normalize(value, dc[i].language); row.setColumn("title", value); row.setColumn("sort_title", title.toLowerCase()); } else if ("ItemsBySubject".equals(table)) { row.setColumn("subject", value); row.setColumn("sort_subject", value.toLowerCase()); } DatabaseManager.update(context, row); } } } /** * Index all items in DSpace. This method may be resource-intensive. * * @param context * Current DSpace context * @return The number of items indexed. * @exception SQLException * If a database error occurs */ public static int indexAll(Context context) throws SQLException { indexRemoveAll(context); int count = 0; ItemIterator iterator = Item.findAll(context); while (iterator.hasNext()) { itemAdded(context, iterator.next()); count++; } return count; } /** * Remove all items in DSpace from the Browse index. * * @param context * Current DSpace context * @return The number of items removed. * @exception SQLException * If a database error occurs */ public static int indexRemoveAll(Context context) throws SQLException { int total = 0; String[] browseTables = BrowseTables.tables(); for (int i = 0; i < browseTables.length; i++) { String sql = "delete from " + browseTables[i]; total += DatabaseManager.updateQuery(context, sql); } return total; } //////////////////////////////////////// // Other methods //////////////////////////////////////// /** * Return the normalized form of title. * * @param title * @param lang * @return title */ public static String getNormalizedTitle(String title, String lang) { return NormalizedTitle.normalize(title, lang); } //////////////////////////////////////// // Private methods //////////////////////////////////////// private static DCValue[] getMetadataField(Item item, String md) { StringTokenizer dcf = new StringTokenizer(md, "."); String[] tokens = { "", "", "" }; int i = 0; while(dcf.hasMoreTokens()) { tokens[i] = dcf.nextToken().toLowerCase().trim(); i++; } String schema = tokens[0]; String element = tokens[1]; String qualifier = tokens[2]; DCValue[] values; if ("*".equals(qualifier)) { values = item.getMetadata(schema, element, Item.ANY, Item.ANY); } else if ("".equals(qualifier)) { values = item.getMetadata(schema, element, null, Item.ANY); } else { values = item.getMetadata(schema, element, qualifier, Item.ANY); } return values; } /** * Workhorse method for browse functionality. * * @param scope * @return BrowseInfo * @throws SQLException */ private static BrowseInfo doBrowse(BrowseScope scope) throws SQLException { // Check for a cached browse BrowseInfo cachedInfo = BrowseCache.get(scope); if (cachedInfo != null) { return cachedInfo; } // Run the Browse queries // If the focus is an Item, this returns the value String itemValue = getItemValue(scope); List results = new ArrayList(); results.addAll(getResultsBeforeFocus(scope, itemValue)); int beforeFocus = results.size(); results.addAll(getResultsAfterFocus(scope, itemValue, beforeFocus)); // Find out the total in the index, and the number of // matches for the query int total = countTotalInIndex(scope, results.size()); int matches = countMatches(scope, itemValue, total, results.size()); if (log.isDebugEnabled()) { log.debug("Number of matches " + matches); } int position = getPosition(total, matches, beforeFocus); sortResults(scope, results); BrowseInfo info = new BrowseInfo(results, position, total, beforeFocus); logInfo(info); BrowseCache.add(scope, info); return info; } /** * If focus refers to an Item, return a value for the item (its title, * author, accession date, etc). Otherwise return null. * * In general, the queries for these values look like this: select * max(date_issued) from ItemsByDate where item_id = 7; * * The max operator ensures that only one value is returned. * * If limiting to a community or collection, we add a clause like: * community_id = 7 collection_id = 201 * * @param scope * @return desired value for the item * @throws SQLException */ protected static String getItemValue(BrowseScope scope) throws SQLException { if (!scope.focusIsItem()) { return null; } PreparedStatement statement = null; ResultSet results = null; try { String tablename = BrowseTables.getTable(scope); String column = BrowseTables.getValueColumn(scope); String itemValueQuery = new StringBuffer().append("select ") .append("max(").append(column).append(") from ").append( tablename).append(" where ").append(" item_id = ") .append(scope.getFocusItemId()).append( getScopeClause(scope, "and")).toString(); statement = createStatement(scope, itemValueQuery); results = statement.executeQuery(); String itemValue = results.next() ? results.getString(1) : null; if (log.isDebugEnabled()) { log.debug("Subquery value is " + itemValue); } return itemValue; } finally { if (statement != null) { statement.close(); } if (results != null) { results.close(); } } } /** * Run a database query and return results before the focus. * * @param scope * The Browse Scope * @param itemValue * If the focus is an Item, this is its value in the index (its * title, author, etc). * @return list of Item results * @throws SQLException */ protected static List getResultsBeforeFocus(BrowseScope scope, String itemValue) throws SQLException { // Starting from beginning of index if (!scope.hasFocus()) { return Collections.EMPTY_LIST; } // No previous results desired if (scope.getNumberBefore() == 0) { return Collections.EMPTY_LIST; } // ItemsByAuthor. Since this is an exact match, it // does not make sense to return values before the // query. if (scope.getBrowseType() == ITEMS_BY_AUTHOR_BROWSE || scope.getBrowseType() == ITEMS_BY_SUBJECT_BROWSE) { return Collections.EMPTY_LIST; } PreparedStatement statement = createSql(scope, itemValue, false, false); List qresults = DatabaseManager.queryPrepared(statement).toList(); int numberDesired = scope.getNumberBefore(); List results = getResults(scope, qresults, numberDesired); if (!results.isEmpty()) { Collections.reverse(results); } return results; } /** * Run a database query and return results after the focus. * * @param scope * The Browse Scope * @param itemValue * If the focus is an Item, this is its value in the index (its * title, author, etc). * @param count * @return list of results after the focus * @throws SQLException */ protected static List getResultsAfterFocus(BrowseScope scope, String itemValue, int count) throws SQLException { // No results desired if (scope.getTotal() == 0) { return Collections.EMPTY_LIST; } PreparedStatement statement = createSql(scope, itemValue, true, false); List qresults = DatabaseManager.queryPrepared(statement).toList(); // The number of results we want is either -1 (everything) // or the total, less the number already retrieved. int numberDesired = -1; if (!scope.hasNoLimit()) { numberDesired = Math.max(scope.getTotal() - count, 0); } return getResults(scope, qresults, numberDesired); } /* * Return the total number of values in an index. * * <p> We total Authors with SQL like: select count(distinct author) from * ItemsByAuthor; ItemsByAuthor with: select count(*) from ItemsByAuthor * where author = ?; and every other index with: select count(*) from * ItemsByTitle; </p> * * <p> If limiting to a community or collection, we add a clause like: * community_id = 7 collection_id = 201 </p> */ protected static int countTotalInIndex(BrowseScope scope, int numberOfResults) throws SQLException { int browseType = scope.getBrowseType(); // When finding Items by Author, it often happens that // we find every single Item (eg, the Author only published // 2 works, and we asked for 15), and so can skip the // query. if ((browseType == ITEMS_BY_AUTHOR_BROWSE) && (scope.hasNoLimit() || (scope.getTotal() > numberOfResults))) { return numberOfResults; } PreparedStatement statement = null; Object obj = scope.getScope(); try { String table = BrowseTables.getTable(scope); StringBuffer buffer = new StringBuffer().append("select count(") .append(getTargetColumns(scope)).append(") from ").append( table); boolean hasWhere = false; if (browseType == ITEMS_BY_AUTHOR_BROWSE) { hasWhere = true; buffer.append(" where sort_author = ?"); } if (browseType == ITEMS_BY_SUBJECT_BROWSE) { hasWhere = true; buffer.append(" where sort_subject = ?"); } String connector = hasWhere ? "and" : "where"; String sql = buffer.append(getScopeClause(scope, connector)) .toString(); if (log.isDebugEnabled()) { log.debug("Total sql: \"" + sql + "\""); } statement = createStatement(scope, sql); if (browseType == ITEMS_BY_AUTHOR_BROWSE) { statement.setString(1, (String) scope.getFocus()); } if (browseType == ITEMS_BY_SUBJECT_BROWSE) { statement.setString(1, (String) scope.getFocus()); } return getIntValue(statement); } finally { if (statement != null) { statement.close(); } } } /** * Return the number of matches for the browse scope. * * @param scope * @param itemValue * item value we're looking for * @param totalInIndex * FIXME ?? * @param numberOfResults * FIXME ?? * @return number of matches * @throws SQLException */ protected static int countMatches(BrowseScope scope, String itemValue, int totalInIndex, int numberOfResults) throws SQLException { // Matched everything if (numberOfResults == totalInIndex) { return totalInIndex; } // Scope matches everything in the index // Note that this only works when the scope is all of DSpace, // since the Community and Collection index tables // include Items in other Communities/Collections if ((!scope.hasFocus()) && scope.isAllDSpaceScope()) { return totalInIndex; } PreparedStatement statement = null; try { statement = createSql(scope, itemValue, true, true); return getIntValue(statement); } finally { if(statement != null) { try { statement.close(); } catch(SQLException e) { log.error("Problem releasing statement", e); } } } } private static int getPosition(int total, int matches, int beforeFocus) { // Matched everything, so position is at start (0) if (total == matches) { return 0; } return total - matches - beforeFocus; } /** * Sort the results returned from the browse if necessary. The list of * results is sorted in-place. * * @param scope * @param results */ private static void sortResults(BrowseScope scope, List results) { // Currently we only sort ItemsByAuthor, Advisor, Subjects browses if ((scope.getBrowseType() != ITEMS_BY_AUTHOR_BROWSE) || (scope.getBrowseType() != ITEMS_BY_SUBJECT_BROWSE)) { return; } ItemComparator ic = scope.getSortByTitle().booleanValue() ? new ItemComparator( "title", null, Item.ANY, true) : new ItemComparator("date", "issued", Item.ANY, true); Collections.sort(results, ic); } /** * Transform the results of the query (TableRow objects_ into a List of * Strings (for getAuthors()) or Items (for all the other browses). * * @param scope * The Browse Scope * @param results * The results of the query * @param max * The maximum number of results to return * @return FIXME ?? * @throws SQLException */ private static List getResults(BrowseScope scope, List results, int max) throws SQLException { if (results == null) { return Collections.EMPTY_LIST; } List theResults = new ArrayList(); boolean hasLimit = !scope.hasNoLimit(); boolean isAuthorsBrowse = scope.getBrowseType() == AUTHORS_BROWSE; boolean isSubjectsBrowse = scope.getBrowseType() == SUBJECTS_BROWSE; for (Iterator iterator = results.iterator(); iterator.hasNext();) { TableRow row = (TableRow) iterator.next(); Object theValue = null; if (isAuthorsBrowse) theValue = (Object) row.getStringColumn("author"); else if (isSubjectsBrowse) theValue = (Object) row.getStringColumn("subject"); else theValue = (Object) new Integer(row.getIntColumn("item_id")); // Should not happen if (theValue == null) { continue; } // Exceeded limit if (hasLimit && (theResults.size() >= max)) { break; } theResults.add(theValue); if (log.isDebugEnabled()) { log.debug("Adding result " + theValue); } } return (isAuthorsBrowse||isSubjectsBrowse) ? theResults : toItems(scope.getContext(), theResults); } /** * Create a PreparedStatement to run the correct query for scope. * * @param scope * The Browse scope * @param subqueryValue * If the focus is an item, this is its value in the browse index * (its title, author, date, etc). Otherwise null. * @param after * If true, create SQL to find the items after the focus. * Otherwise create SQL to find the items before the focus. * @param isCount * If true, create SQL to count the number of matches for the * query. Otherwise just the query. * @return a prepared statement * @throws SQLException */ private static PreparedStatement createSql(BrowseScope scope, String subqueryValue, boolean after, boolean isCount) throws SQLException { String sqli = createSqlInternal(scope, subqueryValue, isCount); String sql = formatSql(scope, sqli, subqueryValue, after); PreparedStatement statement = createStatement(scope, sql); // Browses without a focus have no parameters to bind if (scope.hasFocus()) { String value = subqueryValue; if (value == null && scope.getFocus() instanceof String) { value = (String)scope.getFocus(); } statement.setString(1, value); // Binds the parameter in the subquery clause if (subqueryValue != null) { statement.setString(2, value); } } if (log.isDebugEnabled()) { log.debug("Created SQL \"" + sql + "\""); } return statement; } /** * Create a SQL string to run the correct query. * * @param scope * @param itemValue * FIXME ?? * @param isCount * @return */ private static String createSqlInternal(BrowseScope scope, String itemValue, boolean isCount) { String tablename = BrowseTables.getTable(scope); String column = BrowseTables.getValueColumn(scope); int browseType = scope.getBrowseType(); StringBuffer sqlb = new StringBuffer(); sqlb.append("select "); sqlb.append(isCount ? "count(" : ""); sqlb.append(getTargetColumns(scope)); /** * This next bit adds another column to the query, so authors don't show * up lower-case */ if ((browseType == AUTHORS_BROWSE) && !isCount) { sqlb.append(",sort_author"); } if ((browseType == SUBJECTS_BROWSE) && !isCount) { sqlb.append(",sort_subject"); } sqlb.append(isCount ? ")" : ""); sqlb.append(" from (SELECT DISTINCT * "); sqlb.append(" from "); sqlb.append(tablename); sqlb.append(" ) as distinct_view"); // If the browse uses items (or item ids) instead of String values // make a subquery. // We use a separate query to make sure the subquery works correctly // when item values are the same. (this is transactionally // safe because we set the isolation level). // If we're NOT searching from the start, add some clauses boolean addedWhereClause = false; if (scope.hasFocus()) { String subquery = null; if (scope.focusIsItem()) { subquery = new StringBuffer().append(" or ( ").append(column) .append(" = ? and item_id {0} ").append( scope.getFocusItemId()).append(")").toString(); } if (log.isDebugEnabled()) { log.debug("Subquery is \"" + subquery + "\""); } sqlb.append(" where ").append("(").append(column).append(" {1} ") .append("?").append(scope.focusIsItem() ? subquery : "") .append(")"); addedWhereClause = true; } String connector = addedWhereClause ? " and " : " where "; sqlb.append(getScopeClause(scope, connector)); // For counting, skip the "order by" and "limit" clauses if (isCount) { return sqlb.toString(); } // Add an order by clause -- a parameter sqlb .append(" order by ") .append(column) .append("{2}") .append( ((scope.focusIsString() && (scope.getBrowseType() != ITEMS_BY_DATE_BROWSE)) || (scope.getBrowseType() == AUTHORS_BROWSE) || (scope .getBrowseType() == SUBJECTS_BROWSE)) ? "" : ", item_id{2}"); String myquery = sqlb.toString(); // A limit on the total returned (Postgres extension) if (!scope.hasNoLimit()) { if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) { myquery = "SELECT * FROM (" + myquery + ") WHERE ROWNUM <= {3} "; } else { // postgres uses LIMIT myquery = myquery + " LIMIT {3} "; } } return myquery; } /** * Format SQL according to the browse type. * * @param scope * @param sql * @param subqueryValue * FIXME ?? * @param after * @return * * */ private static String formatSql(BrowseScope scope, String sql, String subqueryValue, boolean after) { boolean before = !after; int browseType = scope.getBrowseType(); boolean ascending = scope.getAscending(); int numberDesired = before ? scope.getNumberBefore() : scope.getTotal(); // Search operator // Normal case: before is less than, after is greater than or equal String beforeOperator = "<"; String afterOperator = ">="; // For authors, only equality is relevant if (browseType == ITEMS_BY_AUTHOR_BROWSE) { afterOperator = "="; } if (browseType == ITEMS_BY_SUBJECT_BROWSE) { afterOperator = "="; } // Subqueries add a clause which checks for the item specifically, // so we do not check for equality here if (subqueryValue != null) { beforeOperator = "<"; afterOperator = ">"; } if (!ascending) { beforeOperator = ">"; afterOperator = "<="; } if (browseType == ITEMS_BY_DATE_BROWSE) { if (!ascending) { beforeOperator = ">"; afterOperator = "<"; } else { beforeOperator = "<"; afterOperator = ">"; } } String beforeSubqueryOperator = "<"; String afterSubqueryOperator = ">="; // For authors, only equality is relevant if (browseType == ITEMS_BY_AUTHOR_BROWSE || browseType == ITEMS_BY_SUBJECT_BROWSE) { afterSubqueryOperator = "="; } if (!ascending) { beforeSubqueryOperator = ">"; afterSubqueryOperator = "<="; } String order = before ? " desc" : ""; if (!ascending) { order = before ? "" : " desc"; } // Note that it's OK to have unused arguments in the array; // see the javadoc of java.text.MessageFormat // for the whole story. List args = new ArrayList(); args.add(before ? beforeSubqueryOperator : afterSubqueryOperator); args.add(before ? beforeOperator : afterOperator); args.add(order); args.add(new Integer(numberDesired)); return MessageFormat.format(sql, args.toArray()); } /** * Log a message about the results of a browse. * * @param info */ private static void logInfo(BrowseInfo info) { if (!log.isDebugEnabled()) { return; } log.debug("Number of Results: " + info.getResultCount() + " Overall position: " + info.getOverallPosition() + " Total " + info.getTotal() + " Offset " + info.getOffset()); int lastIndex = (info.getOverallPosition() + info.getResultCount()); boolean noresults = (info.getTotal() == 0) || (info.getResultCount() == 0); if (noresults) { log.debug("Got no results"); } log.debug("Got results: " + info.getOverallPosition() + " to " + lastIndex + " out of " + info.getTotal()); } /** * Return the name or names of the column(s) to query for a browse. * * @param scope * The current browse scope * @return The name or names of the columns to query */ private static String getTargetColumns(BrowseScope scope) { int browseType = scope.getBrowseType(); if (browseType == AUTHORS_BROWSE) return "distinct author"; else if (browseType == SUBJECTS_BROWSE) return "distinct subject"; else return "*"; } /** * <p> * Return a scoping clause. * </p> * * <p> * If scope is ALLDSPACE_SCOPE, return the empty string. * </p> * * <p> * Otherwise, the SQL clause which is generated looks like: * </p> * CONNECTOR community_id = 7 CONNECTOR collection_id = 203 * * <p> * CONNECTOR may be empty, or it may be a SQL keyword like <em>where</em>, * <em>and</em>, and so forth. * </p> * * @param scope * @param connector * FIXME ?? * @return */ static String getScopeClause(BrowseScope scope, String connector) { if (scope.isAllDSpaceScope()) { return ""; } boolean isCommunity = scope.isCommunityScope(); Object obj = scope.getScope(); int id = (isCommunity) ? ((Community) obj).getID() : ((Collection) obj) .getID(); String column = (isCommunity) ? "community_id" : "collection_id"; return new StringBuffer().append(" ").append(connector).append(" ") .append(column).append(" = ").append(id).toString(); } /** * Create a PreparedStatement with the given sql. * * @param scope * The current Browse scope * @param sql * SQL query * @return A PreparedStatement with the given SQL * @exception SQLException * If a database error occurs */ private static PreparedStatement createStatement(BrowseScope scope, String sql) throws SQLException { Connection connection = scope.getContext().getDBConnection(); return connection.prepareStatement(sql); } /** * Return a single int value from the PreparedStatement. * * @param statement * A PreparedStatement for a query which returns a single value * of INTEGER type. * @return The integer value from the query. * @exception SQLException * If a database error occurs */ private static int getIntValue(PreparedStatement statement) throws SQLException { ResultSet results = null; try { results = statement.executeQuery(); return results.next() ? results.getInt(1) : (-1); } finally { if (results != null) { results.close(); } } } /** * Convert a list of item ids to full Items. * * @param context * The current DSpace context * @param ids * A list of item ids. Each member of the list is an Integer. * @return A list of Items with the given ids. * @exception SQLException * If a database error occurs */ private static List toItems(Context context, List ids) throws SQLException { // FIXME Again, this is probably a more general need List results = new ArrayList(); for (Iterator iterator = ids.iterator(); iterator.hasNext();) { Integer id = (Integer) iterator.next(); Item item = Item.find(context, id.intValue()); if (item != null) { results.add(item); } } return results; } } class NormalizedTitle { private static String[] STOP_WORDS = new String[] { "A", "An", "The" }; /** * Returns a normalized String corresponding to TITLE. * * @param title * @param lang * @return */ public static String normalize(String title, String lang) { if (lang == null) { return title; } return (lang.startsWith("en")) ? normalizeEnglish(title) : title; } /** * Returns a normalized String corresponding to TITLE. The normalization is * effected by: * + first removing leading spaces, if any + then removing the first * leading occurences of "a", "an" and "the" (in any case). + removing any * whitespace following an occurence of a stop word * * This simple strategy is only expected to be used for English words. * * @param oldtitle * @return */ public static String normalizeEnglish(String oldtitle) { // Corner cases if (oldtitle == null) { return null; } if (oldtitle.length() == 0) { return oldtitle; } // lower case, stupid! (sorry, just a rant about bad contractors) String title = oldtitle.toLowerCase(); // State variables // First find leading whitespace, if any int startAt = firstWhitespace(title); boolean modified = (startAt != 0); boolean usedStopWord = false; String stop = null; // Examine each stop word for (int i = 0; i < STOP_WORDS.length; i++) { stop = STOP_WORDS[i]; int stoplen = stop.length(); // The title must start with the stop word (skipping white space // and ignoring case). boolean found = title.toLowerCase().startsWith(stop.toLowerCase(), startAt) && ( // The title must be longer than whitespace plus the // stop word title.length() >= (startAt + stoplen + 1)) && // The stop word must be followed by white space Character.isWhitespace(title.charAt(startAt + stoplen)); if (found) { modified = true; usedStopWord = true; startAt += stoplen; // Strip leading whitespace again, if any int firstw = firstWhitespace(title, startAt); if (firstw != 0) { startAt = firstw; } // Only process a single stop word break; } } // If we didn't change anything, just return the title as-is if (!modified) { return title; } // If we just stripped white space, return a substring if (!usedStopWord) { return title.substring(startAt); } // Otherwise, return the substring with the stop word appended return new StringBuffer(title.substring(startAt)).append(", ").append( stop).toString(); } /** * Return the index of the first non-whitespace character in the String. * * @param title * @return */ private static int firstWhitespace(String title) { return firstWhitespace(title, 0); } /** * Return the index of the first non-whitespace character in the character * array. * * @param title * @return */ private static int firstWhitespace(char[] title) { return firstWhitespace(title, 0); } /** * Return the index of the first non-whitespace character in the String, * starting at position STARTAT. * * @param title * @param startAt * @return */ private static int firstWhitespace(String title, int startAt) { return firstWhitespace(title.toCharArray(), startAt); } /** * Return the index of the first letter or number in the character array, * starting at position STARTAT. * * @param title * @param startAt * @return */ private static int firstWhitespace(char[] title, int startAt) { int first = 0; for (int j = startAt; j < title.length; j++) { //if (Character.isWhitespace(title[j])) // Actually, let's skip anything that's not a letter or number if (!Character.isLetterOrDigit(title[j])) { first = j + 1; continue; } break; } return first; } } class BrowseCache { private static Map tableMax = new HashMap(); private static Map tableSize = new HashMap(); /** log4j object */ private static Logger log = Logger.getLogger(BrowseCache.class); private static Map cache = new WeakHashMap(); // Everything in the cache is held via Weak References, and is // subject to being gc-ed at any time. // The dateCache holds normal references, so anything in it // will stay around. private static SortedMap dateCache = new TreeMap(); private static final int CACHE_MAXIMUM = 30; /** * Look for cached Browse data corresponding to KEY. * * @param key * @return */ public static BrowseInfo get(BrowseScope key) { if (log.isDebugEnabled()) { log .debug("Checking browse cache with " + cache.size() + " objects"); } BrowseInfo cachedInfo = (BrowseInfo) cache.get(key); try { // Index has never been calculated if (getMaximum(key) == -1) { updateIndexData(key); } if (cachedInfo == null) { if (log.isDebugEnabled()) { log.debug("Not in browse cache"); } return null; } // If we found an object, make sure that the browse indexes // have not changed. // // The granularity for this is quite large; // any change to the index and we will calculate from scratch., // Thus, the cache works well when few changes are made, or // when changes are spaced widely apart. if (indexHasChanged(key)) { if (log.isDebugEnabled()) { log.debug("Index has changed"); } cache.remove(key); return null; } } catch (SQLException sqle) { if (log.isDebugEnabled()) { log.debug("Caught SQLException: " + sqle, sqle); } return null; } // Cached object if (log.isDebugEnabled()) { log.debug("Using cached browse"); } cachedInfo.setCached(true); return cachedInfo; } /** * Return true if an index has changed * * @param key * @return * @throws SQLException */ public static boolean indexHasChanged(BrowseScope key) throws SQLException { Context context = null; try { context = new Context(); TableRow results = countAndMax(context, key); long count = -1; int max = -1; if (results != null) { // use getIntColumn for Oracle count data if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) { count = results.getIntColumn("count"); } else //getLongColumn works for postgres { count = results.getLongColumn("count"); } max = results.getIntColumn("max"); } context.complete(); // Same? if ((count == getCount(key)) && (max == getMaximum(key))) { return false; } // Update 'em setMaximum(key, max); setCount(key, count); // The index has in fact changed return true; } catch (SQLException sqle) { if (context != null) { context.abort(); } throw sqle; } } /** * Compute and save the values for the number of values in the index, and * the maximum such value. * * @param key */ public static void updateIndexData(BrowseScope key) { Context context = null; try { context = new Context(); TableRow results = countAndMax(context, key); long count = -1; int max = -1; if (results != null) { //use getIntColumn for Oracle count data if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) { count = results.getIntColumn("count"); } else //getLongColumn works for postgres { count = results.getLongColumn("count"); } max = results.getIntColumn("max"); } context.complete(); setMaximum(key, max); setCount(key, count); } catch (Exception e) { if (context != null) { context.abort(); } e.printStackTrace(); } } /** * Retrieve the values for count and max * * @param context * @param scope * @return * @throws SQLException */ public static TableRow countAndMax(Context context, BrowseScope scope) throws SQLException { // The basic idea here is that we'll check an indexes // maximum id and its count: if the maximum id has changed, // then there are new values, and if the count has changed, // then some items may have been removed. We assume that // values never change. String sql = new StringBuffer().append( "select count({0}) as count, max({0}) as max from ").append( BrowseTables.getTable(scope)).append( Browse.getScopeClause(scope, "where")).toString(); // Format it to use the correct columns String countColumn = BrowseTables.getIndexColumn(scope); Object[] args = new Object[] { countColumn, countColumn }; String SQL = MessageFormat.format(sql, args); // Run the query if (log.isDebugEnabled()) { log.debug("Running SQL to check whether index has changed: \"" + SQL + "\""); } return DatabaseManager.querySingle(context, SQL); } /** * Add info to cache, using key. * * @param key * @param info */ public static void add(BrowseScope key, BrowseInfo info) { // Don't bother caching browses with no results, they are // fairly cheap to calculate if (info.getResultCount() == 0) { return; } // Add the info to the cache // Since the object is passed in to us (and thus the caller // may change it), we make a copy. cache.put(key.clone(), info); // Make sure the date cache is current cleanDateCache(); // Save a new entry into the date cache dateCache.put(new java.util.Date(), key); } /** * Remove entries from the date cache */ private static void cleanDateCache() { synchronized (dateCache) { // Plenty of room! if (dateCache.size() < CACHE_MAXIMUM) { return; } // Remove the oldest object dateCache.remove(dateCache.firstKey()); } } /** * Return the maximum value * * @param scope * @return */ private static int getMaximum(BrowseScope scope) { String table = BrowseTables.getTable(scope); Integer value = (Integer) tableMax.get(table); return (value == null) ? (-1) : value.intValue(); } private static long getCount(BrowseScope scope) { String table = BrowseTables.getTable(scope); Long value = (Long) tableSize.get(table); return (value == null) ? (-1) : value.longValue(); } private static void setMaximum(BrowseScope scope, int max) { String table = BrowseTables.getTable(scope); tableMax.put(table, new Integer(max)); } private static void setCount(BrowseScope scope, long count) { String table = BrowseTables.getTable(scope); tableSize.put(table, new Long(count)); } } // Encapsulates browse table info: // * Each scope and browsetype has a corresponding table or view // * Each browse table or view has a value column // * Some of the browse tables are true tables, others are views. // The index maintenance code needs to know the true tables. // The true tables have index columns, which can be used for caching class BrowseTables { private static final String[] BROWSE_TABLES = new String[] { "Communities2Item", "ItemsByAuthor", "ItemsByDate", "ItemsByDateAccessioned", "ItemsByTitle", "ItemsBySubject" }; /** * Return the browse tables. This only returns true tables, views are * ignored. * * @return */ public static String[] tables() { return BROWSE_TABLES; } /** * Return the browse table or view for scope. * * @param scope * @return */ public static String getTable(BrowseScope scope) { int browseType = scope.getBrowseType(); boolean isCommunity = scope.isCommunityScope(); boolean isCollection = scope.isCollectionScope(); if ((browseType == Browse.AUTHORS_BROWSE) || (browseType == Browse.ITEMS_BY_AUTHOR_BROWSE)) { if (isCommunity) { return "CommunityItemsByAuthor"; } if (isCollection) { return "CollectionItemsByAuthor"; } return "ItemsByAuthor"; } if (browseType == Browse.ITEMS_BY_TITLE_BROWSE) { if (isCommunity) { return "CommunityItemsByTitle"; } if (isCollection) { return "CollectionItemsByTitle"; } return "ItemsByTitle"; } if (browseType == Browse.ITEMS_BY_DATE_BROWSE) { if (isCommunity) { return "CommunityItemsByDate"; } if (isCollection) { return "CollectionItemsByDate"; } return "ItemsByDate"; } if ((browseType == Browse.SUBJECTS_BROWSE) || (browseType == Browse.ITEMS_BY_SUBJECT_BROWSE)) { if (isCommunity) { return "CommunityItemsBySubject"; } if (isCollection) { return "CollectionItemsBySubject"; } return "ItemsBySubject"; } throw new IllegalArgumentException( "No table for browse and scope combination"); } /** * Return the name of the column that holds the index. * * @param scope * @return */ public static String getIndexColumn(BrowseScope scope) { int browseType = scope.getBrowseType(); if (browseType == Browse.AUTHORS_BROWSE) { return "items_by_author_id"; } if (browseType == Browse.ITEMS_BY_AUTHOR_BROWSE) { return "items_by_author_id"; } if (browseType == Browse.ITEMS_BY_DATE_BROWSE) { return "items_by_date_id"; } if (browseType == Browse.ITEMS_BY_TITLE_BROWSE) { return "items_by_title_id"; } if (browseType == Browse.SUBJECTS_BROWSE) { return "items_by_subject_id"; } if (browseType == Browse.ITEMS_BY_SUBJECT_BROWSE) { return "items_by_subject_id"; } throw new IllegalArgumentException("Unknown browse type: " + browseType); } /** * Return the name of the column that holds the Browse value (the title, * author, date, etc). * * @param scope * @return */ public static String getValueColumn(BrowseScope scope) { int browseType = scope.getBrowseType(); if (browseType == Browse.AUTHORS_BROWSE) { return "sort_author"; } if (browseType == Browse.ITEMS_BY_AUTHOR_BROWSE) { return "sort_author"; } if (browseType == Browse.ITEMS_BY_DATE_BROWSE) { return "date_issued"; } // Note that we use the normalized form of the title if (browseType == Browse.ITEMS_BY_TITLE_BROWSE) { return "sort_title"; } if (browseType == Browse.SUBJECTS_BROWSE) { return "sort_subject"; } if (browseType == Browse.ITEMS_BY_SUBJECT_BROWSE) { return "sort_subject"; } throw new IllegalArgumentException("Unknown browse type: " + browseType); } }
dspace/src/org/dspace/browse/Browse.java
/* * Browse.java * * Version: $Revision$ * * Date: $Date$ * * Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts * Institute of Technology. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the Hewlett-Packard Company nor the name of the * Massachusetts Institute of Technology nor the names of their * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.dspace.browse; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.WeakHashMap; import org.apache.log4j.Logger; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.DCValue; import org.dspace.content.Item; import org.dspace.content.ItemComparator; import org.dspace.content.ItemIterator; import org.dspace.core.ConfigurationManager; import org.dspace.core.Context; import org.dspace.storage.rdbms.DatabaseManager; import org.dspace.storage.rdbms.TableRow; /** * API for Browsing Items in DSpace by title, author, or date. Browses only * return archived Items. * * @author Peter Breton * @version $Revision$ */ public class Browse { // Browse types static final int AUTHORS_BROWSE = 0; static final int ITEMS_BY_TITLE_BROWSE = 1; static final int ITEMS_BY_AUTHOR_BROWSE = 2; static final int ITEMS_BY_DATE_BROWSE = 3; static final int SUBJECTS_BROWSE = 4; static final int ITEMS_BY_SUBJECT_BROWSE = 5; /** Log4j log */ private static Logger log = Logger.getLogger(Browse.class); /** * Constructor */ private Browse() { } /** * Return distinct Authors in the given scope. Author refers to a Dublin * Core field with element <em>contributor</em> and qualifier * <em>author</em>. * * <p> * Results are returned in alphabetical order. * </p> * * @param scope * The BrowseScope * @return A BrowseInfo object, the results of the browse * @exception SQLException * If a database error occurs */ public static BrowseInfo getAuthors(BrowseScope scope) throws SQLException { scope.setBrowseType(AUTHORS_BROWSE); scope.setAscending(true); scope.setSortByTitle(null); return doBrowse(scope); } /** * Return distinct Subjects in the given scope. Subjects refers to a Dublin * Core field with element <em>subject</em> and qualifier * <em>*</em>. * * <p> * Results are returned in alphabetical order. * </p> * * @param scope * The BrowseScope * @return A BrowseInfo object, the results of the browse * @exception SQLException * If a database error occurs */ public static BrowseInfo getSubjects(BrowseScope scope) throws SQLException { scope.setBrowseType(SUBJECTS_BROWSE); scope.setAscending(true); scope.setSortByTitle(null); return doBrowse(scope); } /** * Return Items indexed by title in the given scope. Title refers to a * Dublin Core field with element <em>title</em> and no qualifier. * * <p> * Results are returned in alphabetical order; that is, the Item with the * title which is first in alphabetical order will be returned first. * </p> * * @param scope * The BrowseScope * @return A BrowseInfo object, the results of the browse * @exception SQLException * If a database error occurs */ public static BrowseInfo getItemsByTitle(BrowseScope scope) throws SQLException { scope.setBrowseType(ITEMS_BY_TITLE_BROWSE); scope.setAscending(true); scope.setSortByTitle(null); return doBrowse(scope); } /** * Return Items indexed by date in the given scope. Date refers to a Dublin * Core field with element <em>date</em> and qualifier <em>issued</em>. * * <p> * If oldestfirst is true, the dates returned are the ones after the focus, * ordered from earliest to latest. Otherwise the dates are the ones before * the focus, and ordered from latest to earliest. For example: * </p> * * <p> * For example, if the focus is <em>1995</em>, and oldestfirst is true, * the results might look like this: * </p> * * <code>1993, 1994, 1995 (the focus), 1996, 1997.....</code> * * <p> * While if the focus is <em>1995</em>, and oldestfirst is false, the * results would be: * </p> * * <code>1997, 1996, 1995 (the focus), 1994, 1993 .....</code> * * @param scope * The BrowseScope * @param oldestfirst * If true, the dates returned are the ones after focus, ordered * from earliest to latest; otherwise the dates are the ones * before focus, ordered from latest to earliest. * @return A BrowseInfo object, the results of the browse * @exception SQLException * If a database error occurs */ public static BrowseInfo getItemsByDate(BrowseScope scope, boolean oldestfirst) throws SQLException { scope.setBrowseType(ITEMS_BY_DATE_BROWSE); scope.setAscending(oldestfirst); scope.setSortByTitle(null); return doBrowse(scope); } /** * <p> * Return Items in the given scope by the author (exact match). The focus of * the BrowseScope is the author to use; using a BrowseScope without a focus * causes an IllegalArgumentException to be thrown. * </p> * * <p> * Author refers to a Dublin Core field with element <em>contributor</em> * and qualifier <em>author</em>. * </p> * * @param scope * The BrowseScope * @param sortByTitle * If true, the returned items are sorted by title; otherwise * they are sorted by date issued. * @return A BrowseInfo object, the results of the browse * @exception SQLException * If a database error occurs */ public static BrowseInfo getItemsByAuthor(BrowseScope scope, boolean sortByTitle) throws SQLException { if (!scope.hasFocus()) { throw new IllegalArgumentException( "Must specify an author for getItemsByAuthor"); } if (!(scope.getFocus() instanceof String)) { throw new IllegalArgumentException( "The focus for getItemsByAuthor must be a String"); } scope.setBrowseType(ITEMS_BY_AUTHOR_BROWSE); scope.setAscending(true); scope.setSortByTitle(sortByTitle ? Boolean.TRUE : Boolean.FALSE); scope.setTotalAll(); return doBrowse(scope); } /** * <p> * Return Items in the given scope by the subject (exact match). The focus of * the BrowseScope is the subject to use; using a BrowseScope without a focus * causes an IllegalArgumentException to be thrown. * </p> * * <p> * Subject refers to a Dublin Core field with element <em>subject</em> * and qualifier <em>*</em>. * </p> * * @param scope * The BrowseScope * @param sortByTitle * If true, the returned items are sorted by title; otherwise * they are sorted by date issued. * @return A BrowseInfo object, the results of the browse * @exception SQLException * If a database error occurs */ public static BrowseInfo getItemsBySubject(BrowseScope scope, boolean sortByTitle) throws SQLException { if (!scope.hasFocus()) { throw new IllegalArgumentException( "Must specify a subject for getItemsBySubject"); } if (!(scope.getFocus() instanceof String)) { throw new IllegalArgumentException( "The focus for getItemsBySubject must be a String"); } scope.setBrowseType(ITEMS_BY_SUBJECT_BROWSE); scope.setAscending(true); scope.setSortByTitle(sortByTitle ? Boolean.TRUE : Boolean.FALSE); scope.setTotalAll(); return doBrowse(scope); } /** * Returns the last items submitted to DSpace in the given scope. * * @param scope * The Browse Scope * @return A List of Items submitted * @exception SQLException * If a database error occurs */ public static List getLastSubmitted(BrowseScope scope) throws SQLException { Context context = scope.getContext(); String sql = getLastSubmittedQuery(scope); if (log.isDebugEnabled()) { log.debug("SQL for last submitted is \"" + sql + "\""); } List results = DatabaseManager.query(context, sql).toList(); return getLastSubmittedResults(context, results); } /** * Return the SQL used to determine the last submitted Items for scope. * * @param scope * @return String query string */ private static String getLastSubmittedQuery(BrowseScope scope) { String table = getLastSubmittedTable(scope); String query = "SELECT * FROM " + table + getScopeClause(scope, "where") + " ORDER BY date_accessioned DESC"; if (!scope.hasNoLimit()) { if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) { // Oracle version of LIMIT...OFFSET - must use a sub-query and // ROWNUM query = "SELECT * FROM (" + query + ") WHERE ROWNUM <=" + scope.getTotal(); } else { // postgres, use LIMIT query = query + " LIMIT " + scope.getTotal(); } } return query; } /** * Return the name of the Browse index table to query for last submitted * items in the given scope. * * @param scope * @return name of table */ private static String getLastSubmittedTable(BrowseScope scope) { if (scope.isCommunityScope()) { return "CommunityItemsByDateAccession"; } else if (scope.isCollectionScope()) { return "CollectionItemsByDateAccession"; } return "ItemsByDateAccessioned"; } /** * Transform the query results into a List of Items. * * @param context * @param results * @return list of items * @throws SQLException */ private static List getLastSubmittedResults(Context context, List results) throws SQLException { if ((results == null) || (results.isEmpty())) { return Collections.EMPTY_LIST; } List items = new ArrayList(); // FIXME This seems like a very common need, so might // be factored out at some point. for (Iterator iterator = results.iterator(); iterator.hasNext();) { TableRow row = (TableRow) iterator.next(); Item item = Item.find(context, row.getIntColumn("item_id")); items.add(item); } return items; } //////////////////////////////////////// // Index maintainence methods //////////////////////////////////////// /** * This method should be called whenever an item is removed. * * @param context * The current DSpace context * @param id * The id of the item which has been removed * @exception SQLException * If a database error occurs */ public static void itemRemoved(Context context, int id) throws SQLException { String sql = "delete from {0} where item_id = " + id; String[] browseTables = BrowseTables.tables(); for (int i = 0; i < browseTables.length; i++) { String query = MessageFormat.format(sql, new String[] { browseTables[i] }); DatabaseManager.updateQuery(context, query); } } /** * This method should be called whenever an item has changed. Changes * include: * * <ul> * <li>DC values are added, removed, or modified * <li>the value of the in_archive flag changes * </ul> * * @param context - * The database context * @param item - * The item which has been added * @exception SQLException - * If a database error occurs */ public static void itemChanged(Context context, Item item) throws SQLException { // This is a bit heavy-weight, but without knowing what // changed, it's easiest just to replace the values // en masse. itemRemoved(context, item.getID()); if (!item.isArchived()) { return; } itemAdded(context, item); } /** * This method should be called whenever an item is added. * * @param context * The current DSpace context * @param item * The item which has been added * @exception SQLException * If a database error occurs */ public static void itemAdded(Context context, Item item) throws SQLException { // add all parent communities to communities2item table Community[] parents = item.getCommunities(); for (int j = 0; j < parents.length; j++) { TableRow row = DatabaseManager.create(context, "Communities2Item"); row.setColumn("item_id", item.getID()); row.setColumn("community_id", parents[j].getID()); DatabaseManager.update(context, row); } // get the metadata fields to index in the title and date tables // get the date, title and author fields String dateField = ConfigurationManager.getProperty("webui.browse.index.date"); if (dateField == null) { dateField = "dc.date.issued"; } String titleField = ConfigurationManager.getProperty("webui.browse.index.title"); if (titleField == null) { titleField = "dc.title"; } String authorField = ConfigurationManager.getProperty("webui.browse.index.author"); if (authorField == null) { authorField = "dc.contributor.*"; } String subjectField = ConfigurationManager.getProperty("webui.browse.index.subject"); if (subjectField == null) { subjectField = "dc.subject.*"; } // get the DC values for each of these fields DCValue[] titleArray = getMetadataField(item, titleField); DCValue[] dateArray = getMetadataField(item, dateField); DCValue[] authorArray = getMetadataField(item, authorField); DCValue[] subjectArray = getMetadataField(item, subjectField); // now build the data map Map table2dc = new HashMap(); table2dc.put("ItemsByTitle", titleArray); table2dc.put("ItemsByAuthor", authorArray); table2dc.put("ItemsByDate", dateArray); table2dc.put("ItemsByDateAccessioned", item.getDC("date", "accessioned", Item.ANY)); table2dc.put("ItemsBySubject", subjectArray); for (Iterator iterator = table2dc.keySet().iterator(); iterator .hasNext();) { String table = (String) iterator.next(); DCValue[] dc = (DCValue[]) table2dc.get(table); for (int i = 0; i < dc.length; i++) { TableRow row = DatabaseManager.create(context, table); row.setColumn("item_id", item.getID()); String value = dc[i].value; if ("ItemsByDateAccessioned".equals(table)) { row.setColumn("date_accessioned", value); } else if ("ItemsByDate".equals(table)) { row.setColumn("date_issued", value); } else if ("ItemsByAuthor".equals(table)) { // author name, and normalized sorting name // (which for now is simple lower-case) row.setColumn("author", value); row.setColumn("sort_author", value.toLowerCase()); } else if ("ItemsByTitle".equals(table)) { String title = NormalizedTitle.normalize(value, dc[i].language); row.setColumn("title", value); row.setColumn("sort_title", title.toLowerCase()); } else if ("ItemsBySubject".equals(table)) { row.setColumn("subject", value); row.setColumn("sort_subject", value.toLowerCase()); } DatabaseManager.update(context, row); } } } /** * Index all items in DSpace. This method may be resource-intensive. * * @param context * Current DSpace context * @return The number of items indexed. * @exception SQLException * If a database error occurs */ public static int indexAll(Context context) throws SQLException { indexRemoveAll(context); int count = 0; ItemIterator iterator = Item.findAll(context); while (iterator.hasNext()) { itemAdded(context, iterator.next()); count++; } return count; } /** * Remove all items in DSpace from the Browse index. * * @param context * Current DSpace context * @return The number of items removed. * @exception SQLException * If a database error occurs */ public static int indexRemoveAll(Context context) throws SQLException { int total = 0; String[] browseTables = BrowseTables.tables(); for (int i = 0; i < browseTables.length; i++) { String sql = "delete from " + browseTables[i]; total += DatabaseManager.updateQuery(context, sql); } return total; } //////////////////////////////////////// // Other methods //////////////////////////////////////// /** * Return the normalized form of title. * * @param title * @param lang * @return title */ public static String getNormalizedTitle(String title, String lang) { return NormalizedTitle.normalize(title, lang); } //////////////////////////////////////// // Private methods //////////////////////////////////////// private static DCValue[] getMetadataField(Item item, String md) { StringTokenizer dcf = new StringTokenizer(md, "."); String[] tokens = { "", "", "" }; int i = 0; while(dcf.hasMoreTokens()) { tokens[i] = dcf.nextToken().toLowerCase().trim(); i++; } String schema = tokens[0]; String element = tokens[1]; String qualifier = tokens[2]; DCValue[] values; if ("*".equals(qualifier)) { values = item.getMetadata(schema, element, Item.ANY, Item.ANY); } else if ("".equals(qualifier)) { values = item.getMetadata(schema, element, null, Item.ANY); } else { values = item.getMetadata(schema, element, qualifier, Item.ANY); } return values; } /** * Workhorse method for browse functionality. * * @param scope * @return BrowseInfo * @throws SQLException */ private static BrowseInfo doBrowse(BrowseScope scope) throws SQLException { // Check for a cached browse BrowseInfo cachedInfo = BrowseCache.get(scope); if (cachedInfo != null) { return cachedInfo; } // Run the Browse queries // If the focus is an Item, this returns the value String itemValue = getItemValue(scope); List results = new ArrayList(); results.addAll(getResultsBeforeFocus(scope, itemValue)); int beforeFocus = results.size(); results.addAll(getResultsAfterFocus(scope, itemValue, beforeFocus)); // Find out the total in the index, and the number of // matches for the query int total = countTotalInIndex(scope, results.size()); int matches = countMatches(scope, itemValue, total, results.size()); if (log.isDebugEnabled()) { log.debug("Number of matches " + matches); } int position = getPosition(total, matches, beforeFocus); sortResults(scope, results); BrowseInfo info = new BrowseInfo(results, position, total, beforeFocus); logInfo(info); BrowseCache.add(scope, info); return info; } /** * If focus refers to an Item, return a value for the item (its title, * author, accession date, etc). Otherwise return null. * * In general, the queries for these values look like this: select * max(date_issued) from ItemsByDate where item_id = 7; * * The max operator ensures that only one value is returned. * * If limiting to a community or collection, we add a clause like: * community_id = 7 collection_id = 201 * * @param scope * @return desired value for the item * @throws SQLException */ protected static String getItemValue(BrowseScope scope) throws SQLException { if (!scope.focusIsItem()) { return null; } PreparedStatement statement = null; ResultSet results = null; try { String tablename = BrowseTables.getTable(scope); String column = BrowseTables.getValueColumn(scope); String itemValueQuery = new StringBuffer().append("select ") .append("max(").append(column).append(") from ").append( tablename).append(" where ").append(" item_id = ") .append(scope.getFocusItemId()).append( getScopeClause(scope, "and")).toString(); statement = createStatement(scope, itemValueQuery); results = statement.executeQuery(); String itemValue = results.next() ? results.getString(1) : null; if (log.isDebugEnabled()) { log.debug("Subquery value is " + itemValue); } return itemValue; } finally { if (statement != null) { statement.close(); } if (results != null) { results.close(); } } } /** * Run a database query and return results before the focus. * * @param scope * The Browse Scope * @param itemValue * If the focus is an Item, this is its value in the index (its * title, author, etc). * @return list of Item results * @throws SQLException */ protected static List getResultsBeforeFocus(BrowseScope scope, String itemValue) throws SQLException { // Starting from beginning of index if (!scope.hasFocus()) { return Collections.EMPTY_LIST; } // No previous results desired if (scope.getNumberBefore() == 0) { return Collections.EMPTY_LIST; } // ItemsByAuthor. Since this is an exact match, it // does not make sense to return values before the // query. if (scope.getBrowseType() == ITEMS_BY_AUTHOR_BROWSE || scope.getBrowseType() == ITEMS_BY_SUBJECT_BROWSE) { return Collections.EMPTY_LIST; } PreparedStatement statement = createSql(scope, itemValue, false, false); List qresults = DatabaseManager.queryPrepared(statement).toList(); int numberDesired = scope.getNumberBefore(); List results = getResults(scope, qresults, numberDesired); if (!results.isEmpty()) { Collections.reverse(results); } return results; } /** * Run a database query and return results after the focus. * * @param scope * The Browse Scope * @param itemValue * If the focus is an Item, this is its value in the index (its * title, author, etc). * @param count * @return list of results after the focus * @throws SQLException */ protected static List getResultsAfterFocus(BrowseScope scope, String itemValue, int count) throws SQLException { // No results desired if (scope.getTotal() == 0) { return Collections.EMPTY_LIST; } PreparedStatement statement = createSql(scope, itemValue, true, false); List qresults = DatabaseManager.queryPrepared(statement).toList(); // The number of results we want is either -1 (everything) // or the total, less the number already retrieved. int numberDesired = -1; if (!scope.hasNoLimit()) { numberDesired = Math.max(scope.getTotal() - count, 0); } return getResults(scope, qresults, numberDesired); } /* * Return the total number of values in an index. * * <p> We total Authors with SQL like: select count(distinct author) from * ItemsByAuthor; ItemsByAuthor with: select count(*) from ItemsByAuthor * where author = ?; and every other index with: select count(*) from * ItemsByTitle; </p> * * <p> If limiting to a community or collection, we add a clause like: * community_id = 7 collection_id = 201 </p> */ protected static int countTotalInIndex(BrowseScope scope, int numberOfResults) throws SQLException { int browseType = scope.getBrowseType(); // When finding Items by Author, it often happens that // we find every single Item (eg, the Author only published // 2 works, and we asked for 15), and so can skip the // query. if ((browseType == ITEMS_BY_AUTHOR_BROWSE) && (scope.hasNoLimit() || (scope.getTotal() > numberOfResults))) { return numberOfResults; } PreparedStatement statement = null; Object obj = scope.getScope(); try { String table = BrowseTables.getTable(scope); StringBuffer buffer = new StringBuffer().append("select count(") .append(getTargetColumns(scope)).append(") from ").append( table); boolean hasWhere = false; if (browseType == ITEMS_BY_AUTHOR_BROWSE) { hasWhere = true; buffer.append(" where sort_author = ?"); } if (browseType == ITEMS_BY_SUBJECT_BROWSE) { hasWhere = true; buffer.append(" where sort_subject = ?"); } String connector = hasWhere ? "and" : "where"; String sql = buffer.append(getScopeClause(scope, connector)) .toString(); if (log.isDebugEnabled()) { log.debug("Total sql: \"" + sql + "\""); } statement = createStatement(scope, sql); if (browseType == ITEMS_BY_AUTHOR_BROWSE) { statement.setString(1, (String) scope.getFocus()); } if (browseType == ITEMS_BY_SUBJECT_BROWSE) { statement.setString(1, (String) scope.getFocus()); } return getIntValue(statement); } finally { if (statement != null) { statement.close(); } } } /** * Return the number of matches for the browse scope. * * @param scope * @param itemValue * item value we're looking for * @param totalInIndex * FIXME ?? * @param numberOfResults * FIXME ?? * @return number of matches * @throws SQLException */ protected static int countMatches(BrowseScope scope, String itemValue, int totalInIndex, int numberOfResults) throws SQLException { // Matched everything if (numberOfResults == totalInIndex) { return totalInIndex; } // Scope matches everything in the index // Note that this only works when the scope is all of DSpace, // since the Community and Collection index tables // include Items in other Communities/Collections if ((!scope.hasFocus()) && scope.isAllDSpaceScope()) { return totalInIndex; } PreparedStatement statement = null; try { statement = createSql(scope, itemValue, true, true); return getIntValue(statement); } finally { if(statement != null) { try { statement.close(); } catch(SQLException e) { log.error("Problem releasing statement", e); } } } } private static int getPosition(int total, int matches, int beforeFocus) { // Matched everything, so position is at start (0) if (total == matches) { return 0; } return total - matches - beforeFocus; } /** * Sort the results returned from the browse if necessary. The list of * results is sorted in-place. * * @param scope * @param results */ private static void sortResults(BrowseScope scope, List results) { // Currently we only sort ItemsByAuthor, Advisor, Subjects browses if ((scope.getBrowseType() != ITEMS_BY_AUTHOR_BROWSE) || (scope.getBrowseType() != ITEMS_BY_SUBJECT_BROWSE)) { return; } ItemComparator ic = scope.getSortByTitle().booleanValue() ? new ItemComparator( "title", null, Item.ANY, true) : new ItemComparator("date", "issued", Item.ANY, true); Collections.sort(results, ic); } /** * Transform the results of the query (TableRow objects_ into a List of * Strings (for getAuthors()) or Items (for all the other browses). * * @param scope * The Browse Scope * @param results * The results of the query * @param max * The maximum number of results to return * @return FIXME ?? * @throws SQLException */ private static List getResults(BrowseScope scope, List results, int max) throws SQLException { if (results == null) { return Collections.EMPTY_LIST; } List theResults = new ArrayList(); boolean hasLimit = !scope.hasNoLimit(); boolean isAuthorsBrowse = scope.getBrowseType() == AUTHORS_BROWSE; boolean isSubjectsBrowse = scope.getBrowseType() == SUBJECTS_BROWSE; for (Iterator iterator = results.iterator(); iterator.hasNext();) { TableRow row = (TableRow) iterator.next(); Object theValue = null; if (isAuthorsBrowse) theValue = (Object) row.getStringColumn("author"); else if (isSubjectsBrowse) theValue = (Object) row.getStringColumn("subject"); else theValue = (Object) new Integer(row.getIntColumn("item_id")); // Should not happen if (theValue == null) { continue; } // Exceeded limit if (hasLimit && (theResults.size() >= max)) { break; } theResults.add(theValue); if (log.isDebugEnabled()) { log.debug("Adding result " + theValue); } } return (isAuthorsBrowse||isSubjectsBrowse) ? theResults : toItems(scope.getContext(), theResults); } /** * Create a PreparedStatement to run the correct query for scope. * * @param scope * The Browse scope * @param subqueryValue * If the focus is an item, this is its value in the browse index * (its title, author, date, etc). Otherwise null. * @param after * If true, create SQL to find the items after the focus. * Otherwise create SQL to find the items before the focus. * @param isCount * If true, create SQL to count the number of matches for the * query. Otherwise just the query. * @return a prepared statement * @throws SQLException */ private static PreparedStatement createSql(BrowseScope scope, String subqueryValue, boolean after, boolean isCount) throws SQLException { String sqli = createSqlInternal(scope, subqueryValue, isCount); String sql = formatSql(scope, sqli, subqueryValue, after); PreparedStatement statement = createStatement(scope, sql); // Browses without a focus have no parameters to bind if (scope.hasFocus()) { String value = subqueryValue; if (value == null && scope.getFocus() instanceof String) { value = (String)scope.getFocus(); } statement.setString(1, value); // Binds the parameter in the subquery clause if (subqueryValue != null) { statement.setString(2, value); } } if (log.isDebugEnabled()) { log.debug("Created SQL \"" + sql + "\""); } return statement; } /** * Create a SQL string to run the correct query. * * @param scope * @param itemValue * FIXME ?? * @param isCount * @return */ private static String createSqlInternal(BrowseScope scope, String itemValue, boolean isCount) { String tablename = BrowseTables.getTable(scope); String column = BrowseTables.getValueColumn(scope); int browseType = scope.getBrowseType(); StringBuffer sqlb = new StringBuffer(); sqlb.append("select "); sqlb.append(isCount ? "count(" : ""); sqlb.append(getTargetColumns(scope)); /** * This next bit adds another column to the query, so authors don't show * up lower-case */ if ((browseType == AUTHORS_BROWSE) && !isCount) { sqlb.append(",author"); } if ((browseType == SUBJECTS_BROWSE) && !isCount) { sqlb.append(",subject"); } sqlb.append(isCount ? ")" : ""); sqlb.append(" from (SELECT DISTINCT * "); sqlb.append(" from "); sqlb.append(tablename); sqlb.append(" ) as distinct_view"); // If the browse uses items (or item ids) instead of String values // make a subquery. // We use a separate query to make sure the subquery works correctly // when item values are the same. (this is transactionally // safe because we set the isolation level). // If we're NOT searching from the start, add some clauses boolean addedWhereClause = false; if (scope.hasFocus()) { String subquery = null; if (scope.focusIsItem()) { subquery = new StringBuffer().append(" or ( ").append(column) .append(" = ? and item_id {0} ").append( scope.getFocusItemId()).append(")").toString(); } if (log.isDebugEnabled()) { log.debug("Subquery is \"" + subquery + "\""); } sqlb.append(" where ").append("(").append(column).append(" {1} ") .append("?").append(scope.focusIsItem() ? subquery : "") .append(")"); addedWhereClause = true; } String connector = addedWhereClause ? " and " : " where "; sqlb.append(getScopeClause(scope, connector)); // For counting, skip the "order by" and "limit" clauses if (isCount) { return sqlb.toString(); } // Add an order by clause -- a parameter sqlb .append(" order by ") .append(column) .append("{2}") .append( ((scope.focusIsString() && (scope.getBrowseType() != ITEMS_BY_DATE_BROWSE)) || (scope.getBrowseType() == AUTHORS_BROWSE) || (scope .getBrowseType() == SUBJECTS_BROWSE)) ? "" : ", item_id{2}"); String myquery = sqlb.toString(); // A limit on the total returned (Postgres extension) if (!scope.hasNoLimit()) { if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) { myquery = "SELECT * FROM (" + myquery + ") WHERE ROWNUM <= {3} "; } else { // postgres uses LIMIT myquery = myquery + " LIMIT {3} "; } } return myquery; } /** * Format SQL according to the browse type. * * @param scope * @param sql * @param subqueryValue * FIXME ?? * @param after * @return * * */ private static String formatSql(BrowseScope scope, String sql, String subqueryValue, boolean after) { boolean before = !after; int browseType = scope.getBrowseType(); boolean ascending = scope.getAscending(); int numberDesired = before ? scope.getNumberBefore() : scope.getTotal(); // Search operator // Normal case: before is less than, after is greater than or equal String beforeOperator = "<"; String afterOperator = ">="; // For authors, only equality is relevant if (browseType == ITEMS_BY_AUTHOR_BROWSE) { afterOperator = "="; } if (browseType == ITEMS_BY_SUBJECT_BROWSE) { afterOperator = "="; } // Subqueries add a clause which checks for the item specifically, // so we do not check for equality here if (subqueryValue != null) { beforeOperator = "<"; afterOperator = ">"; } if (!ascending) { beforeOperator = ">"; afterOperator = "<="; } if (browseType == ITEMS_BY_DATE_BROWSE) { if (!ascending) { beforeOperator = ">"; afterOperator = "<"; } else { beforeOperator = "<"; afterOperator = ">"; } } String beforeSubqueryOperator = "<"; String afterSubqueryOperator = ">="; // For authors, only equality is relevant if (browseType == ITEMS_BY_AUTHOR_BROWSE || browseType == ITEMS_BY_SUBJECT_BROWSE) { afterSubqueryOperator = "="; } if (!ascending) { beforeSubqueryOperator = ">"; afterSubqueryOperator = "<="; } String order = before ? " desc" : ""; if (!ascending) { order = before ? "" : " desc"; } // Note that it's OK to have unused arguments in the array; // see the javadoc of java.text.MessageFormat // for the whole story. List args = new ArrayList(); args.add(before ? beforeSubqueryOperator : afterSubqueryOperator); args.add(before ? beforeOperator : afterOperator); args.add(order); args.add(new Integer(numberDesired)); return MessageFormat.format(sql, args.toArray()); } /** * Log a message about the results of a browse. * * @param info */ private static void logInfo(BrowseInfo info) { if (!log.isDebugEnabled()) { return; } log.debug("Number of Results: " + info.getResultCount() + " Overall position: " + info.getOverallPosition() + " Total " + info.getTotal() + " Offset " + info.getOffset()); int lastIndex = (info.getOverallPosition() + info.getResultCount()); boolean noresults = (info.getTotal() == 0) || (info.getResultCount() == 0); if (noresults) { log.debug("Got no results"); } log.debug("Got results: " + info.getOverallPosition() + " to " + lastIndex + " out of " + info.getTotal()); } /** * Return the name or names of the column(s) to query for a browse. * * @param scope * The current browse scope * @return The name or names of the columns to query */ private static String getTargetColumns(BrowseScope scope) { int browseType = scope.getBrowseType(); if (browseType == AUTHORS_BROWSE) return "distinct sort_author"; else if (browseType == SUBJECTS_BROWSE) return "distinct sort_subject"; else return "*"; } /** * <p> * Return a scoping clause. * </p> * * <p> * If scope is ALLDSPACE_SCOPE, return the empty string. * </p> * * <p> * Otherwise, the SQL clause which is generated looks like: * </p> * CONNECTOR community_id = 7 CONNECTOR collection_id = 203 * * <p> * CONNECTOR may be empty, or it may be a SQL keyword like <em>where</em>, * <em>and</em>, and so forth. * </p> * * @param scope * @param connector * FIXME ?? * @return */ static String getScopeClause(BrowseScope scope, String connector) { if (scope.isAllDSpaceScope()) { return ""; } boolean isCommunity = scope.isCommunityScope(); Object obj = scope.getScope(); int id = (isCommunity) ? ((Community) obj).getID() : ((Collection) obj) .getID(); String column = (isCommunity) ? "community_id" : "collection_id"; return new StringBuffer().append(" ").append(connector).append(" ") .append(column).append(" = ").append(id).toString(); } /** * Create a PreparedStatement with the given sql. * * @param scope * The current Browse scope * @param sql * SQL query * @return A PreparedStatement with the given SQL * @exception SQLException * If a database error occurs */ private static PreparedStatement createStatement(BrowseScope scope, String sql) throws SQLException { Connection connection = scope.getContext().getDBConnection(); return connection.prepareStatement(sql); } /** * Return a single int value from the PreparedStatement. * * @param statement * A PreparedStatement for a query which returns a single value * of INTEGER type. * @return The integer value from the query. * @exception SQLException * If a database error occurs */ private static int getIntValue(PreparedStatement statement) throws SQLException { ResultSet results = null; try { results = statement.executeQuery(); return results.next() ? results.getInt(1) : (-1); } finally { if (results != null) { results.close(); } } } /** * Convert a list of item ids to full Items. * * @param context * The current DSpace context * @param ids * A list of item ids. Each member of the list is an Integer. * @return A list of Items with the given ids. * @exception SQLException * If a database error occurs */ private static List toItems(Context context, List ids) throws SQLException { // FIXME Again, this is probably a more general need List results = new ArrayList(); for (Iterator iterator = ids.iterator(); iterator.hasNext();) { Integer id = (Integer) iterator.next(); Item item = Item.find(context, id.intValue()); if (item != null) { results.add(item); } } return results; } } class NormalizedTitle { private static String[] STOP_WORDS = new String[] { "A", "An", "The" }; /** * Returns a normalized String corresponding to TITLE. * * @param title * @param lang * @return */ public static String normalize(String title, String lang) { if (lang == null) { return title; } return (lang.startsWith("en")) ? normalizeEnglish(title) : title; } /** * Returns a normalized String corresponding to TITLE. The normalization is * effected by: * + first removing leading spaces, if any + then removing the first * leading occurences of "a", "an" and "the" (in any case). + removing any * whitespace following an occurence of a stop word * * This simple strategy is only expected to be used for English words. * * @param oldtitle * @return */ public static String normalizeEnglish(String oldtitle) { // Corner cases if (oldtitle == null) { return null; } if (oldtitle.length() == 0) { return oldtitle; } // lower case, stupid! (sorry, just a rant about bad contractors) String title = oldtitle.toLowerCase(); // State variables // First find leading whitespace, if any int startAt = firstWhitespace(title); boolean modified = (startAt != 0); boolean usedStopWord = false; String stop = null; // Examine each stop word for (int i = 0; i < STOP_WORDS.length; i++) { stop = STOP_WORDS[i]; int stoplen = stop.length(); // The title must start with the stop word (skipping white space // and ignoring case). boolean found = title.toLowerCase().startsWith(stop.toLowerCase(), startAt) && ( // The title must be longer than whitespace plus the // stop word title.length() >= (startAt + stoplen + 1)) && // The stop word must be followed by white space Character.isWhitespace(title.charAt(startAt + stoplen)); if (found) { modified = true; usedStopWord = true; startAt += stoplen; // Strip leading whitespace again, if any int firstw = firstWhitespace(title, startAt); if (firstw != 0) { startAt = firstw; } // Only process a single stop word break; } } // If we didn't change anything, just return the title as-is if (!modified) { return title; } // If we just stripped white space, return a substring if (!usedStopWord) { return title.substring(startAt); } // Otherwise, return the substring with the stop word appended return new StringBuffer(title.substring(startAt)).append(", ").append( stop).toString(); } /** * Return the index of the first non-whitespace character in the String. * * @param title * @return */ private static int firstWhitespace(String title) { return firstWhitespace(title, 0); } /** * Return the index of the first non-whitespace character in the character * array. * * @param title * @return */ private static int firstWhitespace(char[] title) { return firstWhitespace(title, 0); } /** * Return the index of the first non-whitespace character in the String, * starting at position STARTAT. * * @param title * @param startAt * @return */ private static int firstWhitespace(String title, int startAt) { return firstWhitespace(title.toCharArray(), startAt); } /** * Return the index of the first letter or number in the character array, * starting at position STARTAT. * * @param title * @param startAt * @return */ private static int firstWhitespace(char[] title, int startAt) { int first = 0; for (int j = startAt; j < title.length; j++) { //if (Character.isWhitespace(title[j])) // Actually, let's skip anything that's not a letter or number if (!Character.isLetterOrDigit(title[j])) { first = j + 1; continue; } break; } return first; } } class BrowseCache { private static Map tableMax = new HashMap(); private static Map tableSize = new HashMap(); /** log4j object */ private static Logger log = Logger.getLogger(BrowseCache.class); private static Map cache = new WeakHashMap(); // Everything in the cache is held via Weak References, and is // subject to being gc-ed at any time. // The dateCache holds normal references, so anything in it // will stay around. private static SortedMap dateCache = new TreeMap(); private static final int CACHE_MAXIMUM = 30; /** * Look for cached Browse data corresponding to KEY. * * @param key * @return */ public static BrowseInfo get(BrowseScope key) { if (log.isDebugEnabled()) { log .debug("Checking browse cache with " + cache.size() + " objects"); } BrowseInfo cachedInfo = (BrowseInfo) cache.get(key); try { // Index has never been calculated if (getMaximum(key) == -1) { updateIndexData(key); } if (cachedInfo == null) { if (log.isDebugEnabled()) { log.debug("Not in browse cache"); } return null; } // If we found an object, make sure that the browse indexes // have not changed. // // The granularity for this is quite large; // any change to the index and we will calculate from scratch., // Thus, the cache works well when few changes are made, or // when changes are spaced widely apart. if (indexHasChanged(key)) { if (log.isDebugEnabled()) { log.debug("Index has changed"); } cache.remove(key); return null; } } catch (SQLException sqle) { if (log.isDebugEnabled()) { log.debug("Caught SQLException: " + sqle, sqle); } return null; } // Cached object if (log.isDebugEnabled()) { log.debug("Using cached browse"); } cachedInfo.setCached(true); return cachedInfo; } /** * Return true if an index has changed * * @param key * @return * @throws SQLException */ public static boolean indexHasChanged(BrowseScope key) throws SQLException { Context context = null; try { context = new Context(); TableRow results = countAndMax(context, key); long count = -1; int max = -1; if (results != null) { // use getIntColumn for Oracle count data if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) { count = results.getIntColumn("count"); } else //getLongColumn works for postgres { count = results.getLongColumn("count"); } max = results.getIntColumn("max"); } context.complete(); // Same? if ((count == getCount(key)) && (max == getMaximum(key))) { return false; } // Update 'em setMaximum(key, max); setCount(key, count); // The index has in fact changed return true; } catch (SQLException sqle) { if (context != null) { context.abort(); } throw sqle; } } /** * Compute and save the values for the number of values in the index, and * the maximum such value. * * @param key */ public static void updateIndexData(BrowseScope key) { Context context = null; try { context = new Context(); TableRow results = countAndMax(context, key); long count = -1; int max = -1; if (results != null) { //use getIntColumn for Oracle count data if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) { count = results.getIntColumn("count"); } else //getLongColumn works for postgres { count = results.getLongColumn("count"); } max = results.getIntColumn("max"); } context.complete(); setMaximum(key, max); setCount(key, count); } catch (Exception e) { if (context != null) { context.abort(); } e.printStackTrace(); } } /** * Retrieve the values for count and max * * @param context * @param scope * @return * @throws SQLException */ public static TableRow countAndMax(Context context, BrowseScope scope) throws SQLException { // The basic idea here is that we'll check an indexes // maximum id and its count: if the maximum id has changed, // then there are new values, and if the count has changed, // then some items may have been removed. We assume that // values never change. String sql = new StringBuffer().append( "select count({0}) as count, max({0}) as max from ").append( BrowseTables.getTable(scope)).append( Browse.getScopeClause(scope, "where")).toString(); // Format it to use the correct columns String countColumn = BrowseTables.getIndexColumn(scope); Object[] args = new Object[] { countColumn, countColumn }; String SQL = MessageFormat.format(sql, args); // Run the query if (log.isDebugEnabled()) { log.debug("Running SQL to check whether index has changed: \"" + SQL + "\""); } return DatabaseManager.querySingle(context, SQL); } /** * Add info to cache, using key. * * @param key * @param info */ public static void add(BrowseScope key, BrowseInfo info) { // Don't bother caching browses with no results, they are // fairly cheap to calculate if (info.getResultCount() == 0) { return; } // Add the info to the cache // Since the object is passed in to us (and thus the caller // may change it), we make a copy. cache.put(key.clone(), info); // Make sure the date cache is current cleanDateCache(); // Save a new entry into the date cache dateCache.put(new java.util.Date(), key); } /** * Remove entries from the date cache */ private static void cleanDateCache() { synchronized (dateCache) { // Plenty of room! if (dateCache.size() < CACHE_MAXIMUM) { return; } // Remove the oldest object dateCache.remove(dateCache.firstKey()); } } /** * Return the maximum value * * @param scope * @return */ private static int getMaximum(BrowseScope scope) { String table = BrowseTables.getTable(scope); Integer value = (Integer) tableMax.get(table); return (value == null) ? (-1) : value.intValue(); } private static long getCount(BrowseScope scope) { String table = BrowseTables.getTable(scope); Long value = (Long) tableSize.get(table); return (value == null) ? (-1) : value.longValue(); } private static void setMaximum(BrowseScope scope, int max) { String table = BrowseTables.getTable(scope); tableMax.put(table, new Integer(max)); } private static void setCount(BrowseScope scope, long count) { String table = BrowseTables.getTable(scope); tableSize.put(table, new Long(count)); } } // Encapsulates browse table info: // * Each scope and browsetype has a corresponding table or view // * Each browse table or view has a value column // * Some of the browse tables are true tables, others are views. // The index maintenance code needs to know the true tables. // The true tables have index columns, which can be used for caching class BrowseTables { private static final String[] BROWSE_TABLES = new String[] { "Communities2Item", "ItemsByAuthor", "ItemsByDate", "ItemsByDateAccessioned", "ItemsByTitle", "ItemsBySubject" }; /** * Return the browse tables. This only returns true tables, views are * ignored. * * @return */ public static String[] tables() { return BROWSE_TABLES; } /** * Return the browse table or view for scope. * * @param scope * @return */ public static String getTable(BrowseScope scope) { int browseType = scope.getBrowseType(); boolean isCommunity = scope.isCommunityScope(); boolean isCollection = scope.isCollectionScope(); if ((browseType == Browse.AUTHORS_BROWSE) || (browseType == Browse.ITEMS_BY_AUTHOR_BROWSE)) { if (isCommunity) { return "CommunityItemsByAuthor"; } if (isCollection) { return "CollectionItemsByAuthor"; } return "ItemsByAuthor"; } if (browseType == Browse.ITEMS_BY_TITLE_BROWSE) { if (isCommunity) { return "CommunityItemsByTitle"; } if (isCollection) { return "CollectionItemsByTitle"; } return "ItemsByTitle"; } if (browseType == Browse.ITEMS_BY_DATE_BROWSE) { if (isCommunity) { return "CommunityItemsByDate"; } if (isCollection) { return "CollectionItemsByDate"; } return "ItemsByDate"; } if ((browseType == Browse.SUBJECTS_BROWSE) || (browseType == Browse.ITEMS_BY_SUBJECT_BROWSE)) { if (isCommunity) { return "CommunityItemsBySubject"; } if (isCollection) { return "CollectionItemsBySubject"; } return "ItemsBySubject"; } throw new IllegalArgumentException( "No table for browse and scope combination"); } /** * Return the name of the column that holds the index. * * @param scope * @return */ public static String getIndexColumn(BrowseScope scope) { int browseType = scope.getBrowseType(); if (browseType == Browse.AUTHORS_BROWSE) { return "items_by_author_id"; } if (browseType == Browse.ITEMS_BY_AUTHOR_BROWSE) { return "items_by_author_id"; } if (browseType == Browse.ITEMS_BY_DATE_BROWSE) { return "items_by_date_id"; } if (browseType == Browse.ITEMS_BY_TITLE_BROWSE) { return "items_by_title_id"; } if (browseType == Browse.SUBJECTS_BROWSE) { return "items_by_subject_id"; } if (browseType == Browse.ITEMS_BY_SUBJECT_BROWSE) { return "items_by_subject_id"; } throw new IllegalArgumentException("Unknown browse type: " + browseType); } /** * Return the name of the column that holds the Browse value (the title, * author, date, etc). * * @param scope * @return */ public static String getValueColumn(BrowseScope scope) { int browseType = scope.getBrowseType(); if (browseType == Browse.AUTHORS_BROWSE) { return "sort_author"; } if (browseType == Browse.ITEMS_BY_AUTHOR_BROWSE) { return "sort_author"; } if (browseType == Browse.ITEMS_BY_DATE_BROWSE) { return "date_issued"; } // Note that we use the normalized form of the title if (browseType == Browse.ITEMS_BY_TITLE_BROWSE) { return "sort_title"; } if (browseType == Browse.SUBJECTS_BROWSE) { return "sort_subject"; } if (browseType == Browse.ITEMS_BY_SUBJECT_BROWSE) { return "sort_subject"; } throw new IllegalArgumentException("Unknown browse type: " + browseType); } }
SF patch #1544829 fixes SF bug #1544807 Browse-by-Subject/Author paging mechanism broken git-svn-id: 39c64a9546defcc59b5f71fe8fe20b2d01c24c1f@1572 9c30dcfa-912a-0410-8fc2-9e0234be79fd
dspace/src/org/dspace/browse/Browse.java
SF patch #1544829 fixes SF bug #1544807 Browse-by-Subject/Author paging mechanism broken
Java
bsd-3-clause
error: pathspec 'dspace/src/org/dspace/app/webui/util/DCInputSet.java' did not match any file(s) known to git
8a684b5e53c8bcfc5ff2d7f0e0dc1033a4661a7f
1
ojacobson/dryad-repo,ojacobson/dryad-repo,mdiggory/dryad-repo,rnathanday/dryad-repo,rnathanday/dryad-repo,jamie-dryad/dryad-repo,mdiggory/dryad-repo,rnathanday/dryad-repo,jimallman/dryad-repo,jimallman/dryad-repo,jimallman/dryad-repo,mdiggory/dryad-repo,rnathanday/dryad-repo,jimallman/dryad-repo,jamie-dryad/dryad-repo,jimallman/dryad-repo,rnathanday/dryad-repo,jamie-dryad/dryad-repo,ojacobson/dryad-repo,rnathanday/dryad-repo,mdiggory/dryad-repo,jamie-dryad/dryad-repo,ojacobson/dryad-repo,jamie-dryad/dryad-repo,ojacobson/dryad-repo,ojacobson/dryad-repo,mdiggory/dryad-repo,jimallman/dryad-repo
/* * DCInputSet.java * * Version: $Revision$ * * Date: $Date$ */ package org.dspace.app.webui.util; import java.util.ArrayList; import java.util.List; import java.util.Vector; import java.util.Map; /** * Class representing all DC inputs required for a submission, organized into pages * * @author Brian S. Hughes, based on work by Jenny Toves, OCLC * @version */ public class DCInputSet { /** name of the input set */ private String formName = null; /** the inputs ordered by page and row position */ private DCInput[][] inputPages = null; /** constructor */ public DCInputSet(String formName, Vector pages, Map listMap) { this.formName = formName; inputPages = new DCInput[pages.size()][]; for ( int i = 0; i < inputPages.length; i++ ) { Vector page = (Vector)pages.get(i); inputPages[i] = new DCInput[page.size()]; for ( int j = 0; j < inputPages[i].length; j++ ) { inputPages[i][j] = new DCInput((Map)page.get(j), listMap); } } } /** * Return the name of the form that defines this input set * @return formName the name of the form */ public String getFormName() { return formName; } /** * Return the number of pages in this input set * @return number of pages */ public int getNumberPages() { return inputPages.length; } /** * Get all the rows for a page from the form definition * * @param pageNum desired page within set * @param addTitleAlternative flag to add the additional title row * @param addPublishedBefore flag to add the additional published info * * @return an array containing the page's displayable rows */ public DCInput[] getPageRows(int pageNum, boolean addTitleAlternative, boolean addPublishedBefore) { List filteredInputs = new ArrayList(); if ( pageNum < inputPages.length ) { for (int i = 0; i < inputPages[pageNum].length; i++ ) { DCInput input = inputPages[pageNum][i]; if (doField(input, addTitleAlternative, addPublishedBefore)) { filteredInputs.add(input); } } } // Convert list into an array DCInput[] inputArray = new DCInput[filteredInputs.size()]; return (DCInput[])filteredInputs.toArray(inputArray); } /** * Does this set of inputs include an alternate title field? * * @return true if the current set has an alternate title field */ public boolean isDefinedMultTitles() { return isFieldPresent("title.alternative"); } /** * Does this set of inputs include the previously published fields? * * @return true if the current set has all the prev. published fields */ public boolean isDefinedPubBefore() { return ( isFieldPresent("date.issued") && isFieldPresent("identifier.citation") && isFieldPresent("publisher.null") ); } /** * Does the current input set define the named field? * Scan through every field in every page of the input set * * @return true if the current set has the named field */ private boolean isFieldPresent(String fieldName) { for (int i = 0; i < inputPages.length; i++) { DCInput[] pageInputs = inputPages[i]; for (int row = 0; row < pageInputs.length; row++) { String fullName = pageInputs[row].getElement() + "." + pageInputs[row].getQualifier(); if (fullName.equals(fieldName)) { return true; } } } return false; } private static boolean doField(DCInput dcf, boolean addTitleAlternative, boolean addPublishedBefore) { String rowName = dcf.getElement() + "." + dcf.getQualifier(); if ( rowName.equals("title.alternative") && ! addTitleAlternative ) { return false; } if (rowName.equals("date.issued") && ! addPublishedBefore ) { return false; } if (rowName.equals("publisher.null") && ! addPublishedBefore ) { return false; } if (rowName.equals("identifier.citation") && ! addPublishedBefore ) { return false; } return true; } }
dspace/src/org/dspace/app/webui/util/DCInputSet.java
Adding support for customizabel submission git-svn-id: 39c64a9546defcc59b5f71fe8fe20b2d01c24c1f@1092 9c30dcfa-912a-0410-8fc2-9e0234be79fd
dspace/src/org/dspace/app/webui/util/DCInputSet.java
Adding support for customizabel submission
Java
bsd-3-clause
error: pathspec 'projects/core/src/main/java/gov/nih/nci/cabig/caaers/domain/report/ReportVersion.java' did not match any file(s) known to git
4770c566f24f1e54494abdea933a452f59703d40
1
NCIP/caaers,NCIP/caaers,CBIIT/caaers,CBIIT/caaers,NCIP/caaers,CBIIT/caaers,NCIP/caaers,CBIIT/caaers,CBIIT/caaers
package gov.nih.nci.cabig.caaers.domain.report; import gov.nih.nci.cabig.caaers.domain.ReportStatus; import gov.nih.nci.cabig.caaers.domain.Submitter; import gov.nih.nci.cabig.ctms.domain.AbstractMutableDomainObject; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; import org.hibernate.annotations.Type; /** * Every report has a report version * * @author Krikor Krumlian * */ @Entity @Table(name = "report_versions") @GenericGenerator(name = "id-generator", strategy = "native", parameters = { @Parameter(name = "sequence", value = "seq_report_versions_id") } ) public class ReportVersion extends AbstractMutableDomainObject implements Serializable { private Date createdOn; private Date dueOn; private Date submittedOn; private Date withdrawnOn; private Submitter submitter; private Boolean physicianSignoff; private String email; private String reportVersionId; private ReportStatus reportStatus; private Report report; //////Logic @Column(name = "status_code") @Type(type = "reportStatus") public ReportStatus getReportStatus() { return reportStatus; } public void setReportStatus(ReportStatus reportStatus) { this.reportStatus = reportStatus; } // This is annotated this way so that the IndexColumn in the parent // will work with the bidirectional mapping @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(insertable=false, updatable=false, nullable=false) public Report getReport() { return report; } public void setReport(Report report) { this.report = report; } @Temporal(value=TemporalType.TIMESTAMP) public Date getCreatedOn() { return createdOn; } public void setCreatedOn(Date createdOn) { this.createdOn = createdOn; } @Temporal(value=TemporalType.TIMESTAMP) public Date getSubmittedOn() { return submittedOn; } public void setSubmittedOn(Date submittedOn) { this.submittedOn = submittedOn; } public Date getWithdrawnOn() { return withdrawnOn; } public void setWithdrawnOn(Date withdrawnOn) { this.withdrawnOn = withdrawnOn; } public Date getDueOn() { return dueOn; } public void setDueOn(Date dueOn) { this.dueOn = dueOn; } @Transient public void addSubmitter(){ if (submitter == null) setSubmitter(new Submitter()); } // non-total cascade allows us to skip saving if the reporter hasn't been filled in yet @OneToOne(mappedBy = "report") @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) public Submitter getSubmitter() { return submitter; } public void setSubmitter(Submitter submitter) { this.submitter = submitter; if (submitter != null) submitter.setReport(this); } @Column(name="physician_signoff") public Boolean getPhysicianSignoff() { return physicianSignoff; } public void setPhysicianSignoff(Boolean physicianSignoff) { this.physicianSignoff = physicianSignoff; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Transient public String[] getEmailAsArray(){ if (this.email == null) { return null; } String[] emails = this.email.split(","); return emails; } public String getReportVersionId() { if ((this.reportVersionId == null) || (this.reportVersionId != null && this.reportVersionId.equals("NA")) ){ setReportVersionId("NA"); } return reportVersionId; } public void setReportVersionId(String reportVersionId) { String id; if ( getId() != null ){ id = Integer.toString(getId() + 1000); if (this.getReport() != null && this.getReport().getReportDefinition() != null && this.getReport().getReportDefinition().getOrganization() !=null){ System.out.println("I am in"); id = id + this.getReport().getReportDefinition().getOrganization().getId(); System.out.println("this is the id"); this.reportVersionId = id; } }else { this.reportVersionId = reportVersionId; } } }
projects/core/src/main/java/gov/nih/nci/cabig/caaers/domain/report/ReportVersion.java
kind of an important one not to commit ! SVN-Revision: 3077
projects/core/src/main/java/gov/nih/nci/cabig/caaers/domain/report/ReportVersion.java
kind of an important one not to commit !
Java
bsd-3-clause
error: pathspec 'core/src/main/java/org/hisp/dhis/android/core/option/OptionSetCollectionRepository.java' did not match any file(s) known to git
3814b9ed6796f00c3e52a49b90b0d3f3e630aaa4
1
dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk
/* * Copyright (c) 2004-2019, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.option; import org.hisp.dhis.android.core.arch.repositories.children.ChildrenAppender; import org.hisp.dhis.android.core.arch.repositories.collection.ReadOnlyIdentifiableCollectionRepositoryImpl; import org.hisp.dhis.android.core.arch.repositories.filters.EnumFilterConnector; import org.hisp.dhis.android.core.arch.repositories.filters.FilterConnectorFactory; import org.hisp.dhis.android.core.arch.repositories.filters.IntegerFilterConnector; import org.hisp.dhis.android.core.arch.repositories.scope.RepositoryScope; import org.hisp.dhis.android.core.common.IdentifiableObjectStore; import org.hisp.dhis.android.core.common.ValueType; import java.util.Map; import javax.inject.Inject; import dagger.Reusable; @Reusable public final class OptionSetCollectionRepository extends ReadOnlyIdentifiableCollectionRepositoryImpl<OptionSet, OptionSetCollectionRepository> { @Inject OptionSetCollectionRepository(final IdentifiableObjectStore<OptionSet> store, final Map<String, ChildrenAppender<OptionSet>> childrenAppenders, final RepositoryScope scope) { super(store, childrenAppenders, scope, new FilterConnectorFactory<>(scope, s -> new OptionSetCollectionRepository(store, childrenAppenders, s))); } public IntegerFilterConnector<OptionSetCollectionRepository> byVersion() { return cf.integer(OptionSetFields.VERSION); } public EnumFilterConnector<OptionSetCollectionRepository, ValueType> byValueType() { return cf.enumC(OptionSetFields.VALUE_TYPE); } public OptionSetCollectionRepository withOptions() { return cf.withChild(OptionSetFields.OPTIONS); } }
core/src/main/java/org/hisp/dhis/android/core/option/OptionSetCollectionRepository.java
[ANDROSDK-725] Add OptionSetCollectionRepository
core/src/main/java/org/hisp/dhis/android/core/option/OptionSetCollectionRepository.java
[ANDROSDK-725] Add OptionSetCollectionRepository
Java
mit
d0e302b0506f5817e65dff13ce11e9e6d04dabab
0
XZot1K/ZotLib
package XZot1K.plugins.zl.libraries; import XZot1K.plugins.zl.Manager; import XZot1K.plugins.zl.ZotLib; import org.bukkit.ChatColor; public class GeneralLibrary { private ZotLib plugin = Manager.getPlugin(); /** * Color codes the given text * * @param msg The message you want colored. * @return The message color coded. */ public String color(String msg) { return ChatColor.translateAlternateColorCodes('&', msg); } /** * Sends the console a message of your choice through the ZotLib. * @param message The message you want to send to console. */ public void sendConsoleMessage(String message) { plugin.getServer().getConsoleSender().sendMessage(color(plugin.getPrefix() + message)); } }
src/XZot1K/plugins/zl/libraries/GeneralLibrary.java
package XZot1K.plugins.zl.libraries; import XZot1K.plugins.zl.Manager; import XZot1K.plugins.zl.ZotLib; import org.bukkit.ChatColor; public class GeneralLibrary { private ZotLib plugin = Manager.getPlugin(); /* The "color" method will go through the fed text and use the & symbol to color code it. After this process is done it will return your new message. */ public String color(String msg) { return ChatColor.translateAlternateColorCodes('&', msg); } // The "sendConsoleMessage" method sends the console a message of your choice through the ZotLib. public void sendConsoleMessage(String message) { plugin.getServer().getConsoleSender().sendMessage(color(plugin.getPrefix() + message)); } }
Replaced the normal comments with JavaDoc comments.
src/XZot1K/plugins/zl/libraries/GeneralLibrary.java
Replaced the normal comments with JavaDoc comments.
Java
mit
dbdc5089e20bd870e105926644f267741c362057
0
wizzardo/Tools,wizzardo/Tools
package com.wizzardo.tools.cache; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; /** * @author: moxa * Date: 9/27/13 */ public class CacheTest { @Test public void simpleCache() { Cache<Integer, Integer> cache = new Cache<Integer, Integer>(1, new Computable<Integer, Integer>() { @Override public Integer compute(Integer s) { return new Integer(s * s); } }); Assert.assertEquals(Integer.valueOf(4), cache.get(2)); Integer cached = cache.get(16); Assert.assertTrue(cached == cache.get(16)); try { Thread.sleep(1501); } catch (InterruptedException ignored) { } Assert.assertTrue(cached != cache.get(16)); } @Test public void exceptions() { Cache<Integer, Integer> cache = new Cache<Integer, Integer>(0, new Computable<Integer, Integer>() { @Override public Integer compute(Integer s) { throw new RuntimeException(); } }); try { cache.get(1); assert false; } catch (Exception e) { } try { cache.get(1); assert false; } catch (Exception e) { } } @Test public void testTTL() throws InterruptedException { Cache<String, String> cache = new Cache<String, String>(1, new Computable<String, String>() { @Override public String compute(String s) { return s.toUpperCase(); } }); cache.get("foo", true); Thread.sleep(500); cache.get("bar"); Thread.sleep(490); Assert.assertEquals(2, cache.size()); Thread.sleep(500); Assert.assertEquals(1, cache.size()); Thread.sleep(20); Assert.assertEquals(0, cache.size()); } @Test public void testCustomTTL() throws InterruptedException { Cache<String, String> cache = new Cache<String, String>(1, new Computable<String, String>() { @Override public String compute(String s) { return s.toUpperCase(); } }); cache.get("foo"); String bar = "BAR"; cache.put("bar", bar, 500); Assert.assertTrue(bar == cache.get("bar")); Thread.sleep(550); Assert.assertTrue(bar != cache.get("bar")); } @Test public void removeOldestTest() throws InterruptedException { Cache<String, String> cache = new Cache<String, String>(1, new Computable<String, String>() { @Override public String compute(String s) { return s.toUpperCase(); } }) { int i = 1; @Override public void onRemoveItem(String s, String s2) { Assert.assertEquals("foo" + (i++), s); } }; cache.get("foo1"); cache.get("foo2"); cache.get("foo3"); Assert.assertEquals(3, cache.size()); cache.removeOldest(); Assert.assertEquals(2, cache.size()); cache.removeOldest(); Assert.assertEquals(1, cache.size()); cache.removeOldest(); Assert.assertEquals(0, cache.size()); } @Test public void sizeLimitedCacheTest() throws InterruptedException { Cache<String, String> cache = new SizeLimitedCache<String, String>(1, 1, new Computable<String, String>() { @Override public String compute(String s) { return s.toUpperCase(); } }); Assert.assertEquals(0, cache.size()); cache.get("foo1"); Assert.assertEquals(1, cache.size()); cache.get("foo2"); Assert.assertEquals(1, cache.size()); cache.get("foo3"); Assert.assertEquals(1, cache.size()); cache.get("foo4"); Assert.assertEquals(1, cache.size()); } @Test public void memoryLimitedCacheTest() throws InterruptedException { MemoryLimitedCache<String, MemoryLimitedCache.SizeProvider> cache = new MemoryLimitedCache<String, MemoryLimitedCache.SizeProvider>(5, 1, new Computable<String, MemoryLimitedCache.SizeProvider>() { @Override public MemoryLimitedCache.SizeProvider compute(final String s) { return new MemoryLimitedCache.SizeProvider() { @Override public long size() { return s.length(); } }; } }); Assert.assertEquals(0, cache.size()); cache.get("foo1"); Assert.assertEquals(1, cache.size()); cache.get("foo2"); Assert.assertEquals(1, cache.size()); cache.get("foo3"); Assert.assertEquals(1, cache.size()); cache.get("foo4"); Assert.assertEquals(1, cache.size()); Assert.assertEquals(4, cache.memoryUsed()); Assert.assertEquals(5, cache.limit()); } @Test public void wait_test() { final AtomicInteger counter = new AtomicInteger(); final Cache<String, String> cache = new Cache<String, String>(1, new Computable<String, String>() { @Override public String compute(String s) { try { Thread.sleep(100); } catch (InterruptedException e) { } counter.incrementAndGet(); return s.toUpperCase(); } }); Thread t = new Thread(new Runnable() { @Override public void run() { cache.get("foo"); Assert.assertEquals(1, counter.get()); } }); t.start(); cache.get("foo"); try { t.join(); } catch (InterruptedException e) { } Assert.assertEquals(1, counter.get()); } @Test public void outdated_test() throws InterruptedException { final Cache<String, String> cache = new Cache<String, String>(1, new Computable<String, String>() { AtomicInteger counter = new AtomicInteger(); @Override public String compute(String s) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } return s + "_" + counter.getAndIncrement(); } }).allowOutdated(); Assert.assertEquals("foo_0", cache.get("foo")); Assert.assertEquals(1, cache.size()); Thread.sleep(1200); final CountDownLatch latch = new CountDownLatch(1); new Thread(new Runnable() { @Override public void run() { Assert.assertEquals("foo_1", cache.get("foo")); latch.countDown(); } }).start(); Thread.sleep(100); Assert.assertEquals("foo_0", cache.get("foo")); latch.await(); } }
src/test/java/com/wizzardo/tools/cache/CacheTest.java
package com.wizzardo.tools.cache; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.atomic.AtomicInteger; /** * @author: moxa * Date: 9/27/13 */ public class CacheTest { @Test public void simpleCache() { Cache<Integer, Integer> cache = new Cache<Integer, Integer>(1, new Computable<Integer, Integer>() { @Override public Integer compute(Integer s) { return new Integer(s * s); } }); Assert.assertEquals(Integer.valueOf(4), cache.get(2)); Integer cached = cache.get(16); Assert.assertTrue(cached == cache.get(16)); try { Thread.sleep(1501); } catch (InterruptedException ignored) { } Assert.assertTrue(cached != cache.get(16)); } @Test public void exceptions() { Cache<Integer, Integer> cache = new Cache<Integer, Integer>(0, new Computable<Integer, Integer>() { @Override public Integer compute(Integer s) { throw new RuntimeException(); } }); try { cache.get(1); assert false; } catch (Exception e) { } try { cache.get(1); assert false; } catch (Exception e) { } } @Test public void testTTL() throws InterruptedException { Cache<String, String> cache = new Cache<String, String>(1, new Computable<String, String>() { @Override public String compute(String s) { return s.toUpperCase(); } }); cache.get("foo", true); Thread.sleep(500); cache.get("bar"); Thread.sleep(490); Assert.assertEquals(2, cache.size()); Thread.sleep(500); Assert.assertEquals(1, cache.size()); Thread.sleep(20); Assert.assertEquals(0, cache.size()); } @Test public void testCustomTTL() throws InterruptedException { Cache<String, String> cache = new Cache<String, String>(1, new Computable<String, String>() { @Override public String compute(String s) { return s.toUpperCase(); } }); cache.get("foo"); String bar = "BAR"; cache.put("bar", bar, 500); Assert.assertTrue(bar == cache.get("bar")); Thread.sleep(550); Assert.assertTrue(bar != cache.get("bar")); } @Test public void removeOldestTest() throws InterruptedException { Cache<String, String> cache = new Cache<String, String>(1, new Computable<String, String>() { @Override public String compute(String s) { return s.toUpperCase(); } }) { int i = 1; @Override public void onRemoveItem(String s, String s2) { Assert.assertEquals("foo" + (i++), s); } }; cache.get("foo1"); cache.get("foo2"); cache.get("foo3"); Assert.assertEquals(3, cache.size()); cache.removeOldest(); Assert.assertEquals(2, cache.size()); cache.removeOldest(); Assert.assertEquals(1, cache.size()); cache.removeOldest(); Assert.assertEquals(0, cache.size()); } @Test public void sizeLimitedCacheTest() throws InterruptedException { Cache<String, String> cache = new SizeLimitedCache<String, String>(1, 1, new Computable<String, String>() { @Override public String compute(String s) { return s.toUpperCase(); } }); Assert.assertEquals(0, cache.size()); cache.get("foo1"); Assert.assertEquals(1, cache.size()); cache.get("foo2"); Assert.assertEquals(1, cache.size()); cache.get("foo3"); Assert.assertEquals(1, cache.size()); cache.get("foo4"); Assert.assertEquals(1, cache.size()); } @Test public void memoryLimitedCacheTest() throws InterruptedException { MemoryLimitedCache<String, MemoryLimitedCache.SizeProvider> cache = new MemoryLimitedCache<String, MemoryLimitedCache.SizeProvider>(5, 1, new Computable<String, MemoryLimitedCache.SizeProvider>() { @Override public MemoryLimitedCache.SizeProvider compute(final String s) { return new MemoryLimitedCache.SizeProvider() { @Override public long size() { return s.length(); } }; } }); Assert.assertEquals(0, cache.size()); cache.get("foo1"); Assert.assertEquals(1, cache.size()); cache.get("foo2"); Assert.assertEquals(1, cache.size()); cache.get("foo3"); Assert.assertEquals(1, cache.size()); cache.get("foo4"); Assert.assertEquals(1, cache.size()); Assert.assertEquals(4, cache.memoryUsed()); Assert.assertEquals(5, cache.limit()); } @Test public void wait_test() { final AtomicInteger counter = new AtomicInteger(); final Cache<String, String> cache = new Cache<String, String>(1, new Computable<String, String>() { @Override public String compute(String s) { try { Thread.sleep(100); } catch (InterruptedException e) { } counter.incrementAndGet(); return s.toUpperCase(); } }); Thread t = new Thread(new Runnable() { @Override public void run() { cache.get("foo"); Assert.assertEquals(1, counter.get()); } }); t.start(); cache.get("foo"); try { t.join(); } catch (InterruptedException e) { } Assert.assertEquals(1, counter.get()); } }
add test for outdated cache
src/test/java/com/wizzardo/tools/cache/CacheTest.java
add test for outdated cache
Java
agpl-3.0
b1102dd540c3dab4193fe3ee167156386a5c3e03
0
ianopolous/Peergos,Peergos/Peergos,ianopolous/Peergos,ianopolous/Peergos,Peergos/Peergos,Peergos/Peergos
package peergos.shared.io.ipfs.multiaddr; import peergos.shared.io.ipfs.multibase.*; import peergos.shared.io.ipfs.multihash.Multihash; import peergos.shared.io.ipfs.cid.Cid; import java.io.*; import java.net.*; import java.util.*; public class Protocol { public static int LENGTH_PREFIXED_VAR_SIZE = -1; private static final String IPV4_REGEX = "\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z"; enum Type { IP4(4, 32, "ip4"), TCP(6, 16, "tcp"), DCCP(33, 16, "dccp"), IP6(41, 128, "ip6"), DNS(53, LENGTH_PREFIXED_VAR_SIZE, "dns"), DNS4(54, LENGTH_PREFIXED_VAR_SIZE, "dns4"), DNS6(55, LENGTH_PREFIXED_VAR_SIZE, "dns6"), DNSADDR(56, LENGTH_PREFIXED_VAR_SIZE, "dnsaddr"), SCTP(132, 16, "sctp"), UDP(273, 16, "udp"), UTP(301, 0, "utp"), UDT(302, 0, "udt"), UNIX(400, LENGTH_PREFIXED_VAR_SIZE, "unix"), P2P(421, LENGTH_PREFIXED_VAR_SIZE, "p2p"), IPFS(421, LENGTH_PREFIXED_VAR_SIZE, "ipfs"), HTTPS(443, 0, "https"), ONION(444, 80, "onion"), ONION3(445, 296, "onion3"), GARLIC64(446, LENGTH_PREFIXED_VAR_SIZE, "garlic64"), GARLIC32(447, LENGTH_PREFIXED_VAR_SIZE, "garlic32"), QUIC(460, 0, "quic"), WS(477, 0, "ws"), WSS(478, 0, "wss"), P2PCIRCUIT(290, 0, "p2p-circuit"), HTTP(480, 0, "http"); public final int code, size; public final String name; private final byte[] encoded; Type(int code, int size, String name) { this.code = code; this.size = size; this.name = name; this.encoded = encode(code); } static byte[] encode(int code) { byte[] varint = new byte[(32 - Integer.numberOfLeadingZeros(code)+6)/7]; putUvarint(varint, code); return varint; } } public final Type type; public Protocol(Type type) { this.type = type; } public void appendCode(OutputStream out) throws IOException { out.write(type.encoded); } public boolean isTerminal() { return type == Type.UNIX; } public int size() { return type.size; } public String name() { return type.name; } public int code() { return type.code; } @Override public String toString() { return name(); } public byte[] addressToBytes(String addr) { try { switch (type) { case IP4: if (! addr.matches(IPV4_REGEX)) throw new IllegalStateException("Invalid IPv4 address: " + addr); return Inet4Address.getByName(addr).getAddress(); case IP6: return Inet6Address.getByName(addr).getAddress(); case TCP: case UDP: case DCCP: case SCTP: int x = Integer.parseInt(addr); if (x > 65535) throw new IllegalStateException("Failed to parse "+type.name+" address "+addr + " (> 65535"); return new byte[]{(byte)(x >>8), (byte)x}; case P2P: case IPFS: { Multihash hash = Cid.decode(addr); ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] hashBytes = hash.toBytes(); byte[] varint = new byte[(32 - Integer.numberOfLeadingZeros(hashBytes.length) + 6) / 7]; putUvarint(varint, hashBytes.length); bout.write(varint); bout.write(hashBytes); return bout.toByteArray(); } case ONION: { String[] split = addr.split(":"); if (split.length != 2) throw new IllegalStateException("Onion address needs a port: " + addr); // onion address without the ".onion" substring if (split[0].length() != 16) throw new IllegalStateException("failed to parse " + name() + " addr: " + addr + " not a Tor onion address."); byte[] onionHostBytes = Multibase.decode(Multibase.Base.Base32.prefix + split[0]); if (onionHostBytes.length != 10) throw new IllegalStateException("Invalid onion address host: " + split[0]); int port = Integer.parseInt(split[1]); if (port > 65535) throw new IllegalStateException("Port is > 65535: " + port); if (port < 1) throw new IllegalStateException("Port is < 1: " + port); ByteArrayOutputStream b = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(b); dout.write(onionHostBytes); dout.writeShort(port); dout.flush(); return b.toByteArray(); } case ONION3: { String[] split = addr.split(":"); if (split.length != 2) throw new IllegalStateException("Onion3 address needs a port: " + addr); // onion3 address without the ".onion" substring if (split[0].length() != 56) throw new IllegalStateException("failed to parse " + name() + " addr: " + addr + " not a Tor onion3 address."); byte[] onionHostBytes = Multibase.decode(Multibase.Base.Base32.prefix + split[0]); if (onionHostBytes.length != 35) throw new IllegalStateException("Invalid onion3 address host: " + split[0]); int port = Integer.parseInt(split[1]); if (port > 65535) throw new IllegalStateException("Port is > 65535: " + port); if (port < 1) throw new IllegalStateException("Port is < 1: " + port); ByteArrayOutputStream b = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(b); dout.write(onionHostBytes); dout.writeShort(port); dout.flush(); return b.toByteArray(); } case GARLIC32: { // an i2p base32 address with a length of greater than 55 characters is // using an Encrypted Leaseset v2. all other base32 addresses will always be // exactly 52 characters if (addr.length() < 55 && addr.length() != 52 || addr.contains(":")) { throw new IllegalStateException(String.format("Invalid garlic addr: %s not a i2p base32 address. len: %d", addr, addr.length())); } while (addr.length() % 8 != 0) { addr += "="; } ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] hashBytes = Multibase.decode(Multibase.Base.Base32.prefix + addr); byte[] varint = new byte[(32 - Integer.numberOfLeadingZeros(hashBytes.length) + 6) / 7]; putUvarint(varint, hashBytes.length); bout.write(varint); bout.write(hashBytes); return bout.toByteArray(); } case GARLIC64: { // i2p base64 address will be between 516 and 616 characters long, depending on certificate type if (addr.length() < 516 || addr.length() > 616 || addr.contains(":")) { throw new IllegalStateException(String.format("Invalid garlic addr: %s not a i2p base64 address. len: %d", addr, addr.length())); } ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] hashBytes = Multibase.decode(Multibase.Base.Base64.prefix + addr.replaceAll("-", "+").replaceAll("~", "/")); byte[] varint = new byte[(32 - Integer.numberOfLeadingZeros(hashBytes.length) + 6) / 7]; putUvarint(varint, hashBytes.length); bout.write(varint); bout.write(hashBytes); return bout.toByteArray(); } case UNIX: { if (addr.startsWith("/")) addr = addr.substring(1); byte[] path = addr.getBytes(); ByteArrayOutputStream b = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(b); byte[] length = new byte[(32 - Integer.numberOfLeadingZeros(path.length)+6)/7]; putUvarint(length, path.length); dout.write(length); dout.write(path); dout.flush(); return b.toByteArray(); } case DNS4: case DNS6: case DNSADDR: { ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] hashBytes = addr.getBytes(); byte[] varint = new byte[(32 - Integer.numberOfLeadingZeros(hashBytes.length) + 6) / 7]; putUvarint(varint, hashBytes.length); bout.write(varint); bout.write(hashBytes); return bout.toByteArray(); } default: throw new IllegalStateException("Unknown multiaddr type: " + type); } } catch (IOException e) { throw new RuntimeException(e); } } public String readAddress(InputStream in) throws IOException { int sizeForAddress = sizeForAddress(in); byte[] buf; switch (type) { case IP4: buf = new byte[sizeForAddress]; read(in, buf); return Inet4Address.getByAddress(buf).toString().substring(1); case IP6: buf = new byte[sizeForAddress]; read(in, buf); return Inet6Address.getByAddress(buf).toString().substring(1); case TCP: case UDP: case DCCP: case SCTP: return Integer.toString((in.read() << 8) | (in.read())); case IPFS: buf = new byte[sizeForAddress]; read(in, buf); return Cid.cast(buf).toString(); case ONION: { byte[] host = new byte[10]; read(in, host); String port = Integer.toString((in.read() << 8) | (in.read())); return Multibase.encode(Multibase.Base.Base32, host).substring(1) + ":" + port; } case ONION3: { byte[] host = new byte[35]; read(in, host); String port = Integer.toString((in.read() << 8) | (in.read())); return Multibase.encode(Multibase.Base.Base32, host).substring(1) + ":" + port; } case GARLIC32: { buf = new byte[sizeForAddress]; read(in, buf); // an i2p base32 for an Encrypted Leaseset v2 will be at least 35 bytes // long other than that, they will be exactly 32 bytes if (buf.length < 35 && buf.length != 32) { throw new IllegalStateException("Invalid garlic addr length: " + buf.length); } return Multibase.encode(Multibase.Base.Base32, buf).substring(1); } case GARLIC64: { buf = new byte[sizeForAddress]; read(in, buf); // A garlic64 address will always be greater than 386 bytes if (buf.length < 386) { throw new IllegalStateException("Invalid garlic64 addr length: " + buf.length); } return Multibase.encode(Multibase.Base.Base64, buf).substring(1).replaceAll("\\+", "-").replaceAll("/", "~"); } case UNIX: buf = new byte[sizeForAddress]; read(in, buf); return new String(buf); case DNS4: case DNS6: case DNSADDR: buf = new byte[sizeForAddress]; read(in, buf); return new String(buf); } throw new IllegalStateException("Unimplemented protocol type: "+type.name); } private static void read(InputStream in, byte[] b) throws IOException { read(in, b, 0, b.length); } private static void read(InputStream in, byte[] b, int offset, int len) throws IOException { int total=0, r=0; while (total < len && r != -1) { r = in.read(b, offset + total, len - total); if (r >=0) total += r; } } public int sizeForAddress(InputStream in) throws IOException { if (type.size > 0) return type.size/8; if (type.size == 0) return 0; return (int)readVarint(in); } static int putUvarint(byte[] buf, long x) { int i = 0; while (x >= 0x80) { buf[i] = (byte)(x | 0x80); x >>= 7; i++; } buf[i] = (byte)x; return i + 1; } static long readVarint(InputStream in) throws IOException { long x = 0; int s=0; for (int i=0; i < 10; i++) { int b = in.read(); if (b == -1) throw new EOFException(); if (b < 0x80) { if (i > 9 || i == 9 && b > 1) { throw new IllegalStateException("Overflow reading varint" +(-(i + 1))); } return x | (((long)b) << s); } x |= ((long)b & 0x7f) << s; s += 7; } throw new IllegalStateException("Varint too long!"); } private static Map<String, Protocol> byName = new HashMap<>(); private static Map<Integer, Protocol> byCode = new HashMap<>(); static { for (Protocol.Type t: Protocol.Type.values()) { Protocol p = new Protocol(t); byName.put(p.name(), p); byCode.put(p.code(), p); } } public static Protocol get(String name) { if (byName.containsKey(name)) return byName.get(name); throw new IllegalStateException("No protocol with name: "+name); } public static Protocol get(int code) { if (byCode.containsKey(code)) return byCode.get(code); throw new IllegalStateException("No protocol with code: "+code); } }
src/peergos/shared/io/ipfs/multiaddr/Protocol.java
package peergos.shared.io.ipfs.multiaddr; import peergos.shared.io.ipfs.multibase.*; import peergos.shared.io.ipfs.multibase.binary.*; import peergos.shared.io.ipfs.multihash.*; import peergos.shared.io.ipfs.cid.*; import java.io.*; import java.net.*; import java.util.*; public class Protocol { public static int LENGTH_PREFIXED_VAR_SIZE = -1; private static final String IPV4_REGEX = "\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z"; enum Type { IP4(4, 32, "ip4"), TCP(6, 16, "tcp"), UDP(17, 16, "udp"), DCCP(33, 16, "dccp"), IP6(41, 128, "ip6"), SCTP(132, 16, "sctp"), UTP(301, 0, "utp"), UDT(302, 0, "udt"), IPFS(421, LENGTH_PREFIXED_VAR_SIZE, "ipfs"), P2P(421, LENGTH_PREFIXED_VAR_SIZE, "p2p"), HTTPS(443, 0, "https"), HTTP(480, 0, "http"), ONION(444, 80, "onion"); public final int code, size; public final String name; private final byte[] encoded; Type(int code, int size, String name) { this.code = code; this.size = size; this.name = name; this.encoded = encode(code); } static byte[] encode(int code) { byte[] varint = new byte[(32 - Integer.numberOfLeadingZeros(code)+6)/7]; putUvarint(varint, code); return varint; } } public final Type type; public Protocol(Type type) { this.type = type; } public void appendCode(OutputStream out) throws IOException { out.write(type.encoded); } public int size() { return type.size; } public String name() { return type.name; } public int code() { return type.code; } @Override public String toString() { return name(); } public byte[] addressToBytes(String addr) { try { switch (type) { case IP4: if (! addr.matches(IPV4_REGEX)) throw new IllegalStateException("Invalid IPv4 address: " + addr); return Inet4Address.getByName(addr).getAddress(); case IP6: return Inet6Address.getByName(addr).getAddress(); case TCP: case UDP: case DCCP: case SCTP: int x = Integer.parseInt(addr); if (x > 65535) throw new IllegalStateException("Failed to parse "+type.name+" address "+addr + " (> 65535"); return new byte[]{(byte)(x >>8), (byte)x}; case P2P: case IPFS: Multihash hash = Cid.decode(addr); ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] hashBytes = hash.toBytes(); byte[] varint = new byte[(32 - Integer.numberOfLeadingZeros(hashBytes.length)+6)/7]; putUvarint(varint, hashBytes.length); bout.write(varint); bout.write(hashBytes); return bout.toByteArray(); case ONION: String[] split = addr.split(":"); if (split.length != 2) throw new IllegalStateException("Onion address needs a port: "+addr); // onion address without the ".onion" substring if (split[0].length() != 16) throw new IllegalStateException("failed to parse "+name()+" addr: "+addr+" not a Tor onion address."); byte[] onionHostBytes = new Base32().decode(split[0].toUpperCase()); int port = Integer.parseInt(split[1]); if (port > 65535) throw new IllegalStateException("Port is > 65535: "+port); if (port < 1) throw new IllegalStateException("Port is < 1: "+port); ByteArrayOutputStream b = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(b); dout.write(onionHostBytes); dout.writeShort(port); dout.flush(); return b.toByteArray(); } } catch (IOException e) { throw new RuntimeException(e); } throw new IllegalStateException("Failed to parse address: "+addr); } public String readAddress(InputStream in) throws IOException { int sizeForAddress = sizeForAddress(in); byte[] buf; switch (type) { case IP4: buf = new byte[sizeForAddress]; in.read(buf); return Inet4Address.getByAddress(buf).toString().substring(1); case IP6: buf = new byte[sizeForAddress]; in.read(buf); return Inet6Address.getByAddress(buf).toString().substring(1); case TCP: case UDP: case DCCP: case SCTP: return Integer.toString((in.read() << 8) | (in.read())); case P2P: case IPFS: buf = new byte[sizeForAddress]; in.read(buf); return Cid.cast(buf).toString(); case ONION: byte[] host = new byte[10]; in.read(host); String port = Integer.toString((in.read() << 8) | (in.read())); return new String(new Base32().encode(host))+":"+port; } throw new IllegalStateException("Unimplemented protocol type: "+type.name); } public int sizeForAddress(InputStream in) throws IOException { if (type.size > 0) return type.size/8; if (type.size == 0) return 0; return (int)readVarint(in); } static int putUvarint(byte[] buf, long x) { int i = 0; while (x >= 0x80) { buf[i] = (byte)(x | 0x80); x >>= 7; i++; } buf[i] = (byte)x; return i + 1; } static long readVarint(InputStream in) throws IOException { long x = 0; int s=0; for (int i=0; i < 10; i++) { int b = in.read(); if (b == -1) throw new EOFException(); if (b < 0x80) { if (i > 9 || i == 9 && b > 1) { throw new IllegalStateException("Overflow reading varint" +(-(i + 1))); } return x | (((long)b) << s); } x |= ((long)b & 0x7f) << s; s += 7; } throw new IllegalStateException("Varint too long!"); } private static Map<String, Protocol> byName = new HashMap<>(); private static Map<Integer, Protocol> byCode = new HashMap<>(); static { for (Protocol.Type t: Protocol.Type.values()) { Protocol p = new Protocol(t); byName.put(p.name(), p); byCode.put(p.code(), p); } } public static Protocol get(String name) { if (byName.containsKey(name)) return byName.get(name); throw new IllegalStateException("No protocol with name: "+name); } public static Protocol get(int code) { if (byCode.containsKey(code)) return byCode.get(code); throw new IllegalStateException("No protocol with code: "+code); } }
Update multiaddress to support onionv3 and i2p garlic addresses
src/peergos/shared/io/ipfs/multiaddr/Protocol.java
Update multiaddress to support onionv3 and i2p garlic addresses
Java
agpl-3.0
4196764d886730c3810d96bfa60f23d31fcb50b0
0
ua-eas/kfs-devops-automation-fork,kuali/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs,UniversityOfHawaii/kfs,kuali/kfs,bhutchinson/kfs,ua-eas/kfs-devops-automation-fork,ua-eas/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,kkronenb/kfs,UniversityOfHawaii/kfs,ua-eas/kfs,quikkian-ua-devops/will-financials,kuali/kfs,ua-eas/kfs,kkronenb/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,smith750/kfs,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,kkronenb/kfs,bhutchinson/kfs,kkronenb/kfs,smith750/kfs,bhutchinson/kfs,ua-eas/kfs-devops-automation-fork,kuali/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,UniversityOfHawaii/kfs,smith750/kfs,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,ua-eas/kfs,kuali/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,bhutchinson/kfs,quikkian-ua-devops/kfs,smith750/kfs
/* * Copyright 2006-2007 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kfs.module.purap.document; import java.sql.Date; import java.util.LinkedHashMap; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.kuali.kfs.module.purap.PurapConstants; import org.kuali.kfs.module.purap.businessobject.Carrier; import org.kuali.kfs.module.purap.businessobject.DeliveryRequiredDateReason; import org.kuali.kfs.module.purap.businessobject.SensitiveData; import org.kuali.kfs.module.purap.document.service.AccountsPayableDocumentSpecificService; import org.kuali.kfs.module.purap.document.service.BulkReceivingService; import org.kuali.kfs.module.purap.document.service.RequisitionService; import org.kuali.kfs.module.purap.document.validation.event.AttributedContinuePurapEvent; import org.kuali.kfs.module.purap.service.SensitiveDataService; import org.kuali.kfs.module.purap.util.PurApRelatedViews; import org.kuali.kfs.sys.context.SpringContext; import org.kuali.kfs.sys.document.FinancialSystemTransactionalDocumentBase; import org.kuali.kfs.vnd.VendorConstants; import org.kuali.kfs.vnd.businessobject.VendorAddress; import org.kuali.kfs.vnd.businessobject.VendorDetail; import org.kuali.kfs.vnd.document.service.VendorService; import org.kuali.rice.kew.exception.WorkflowException; import org.kuali.rice.kim.bo.Person; import org.kuali.rice.kns.bo.Campus; import org.kuali.rice.kns.bo.Country; import org.kuali.rice.kns.bo.DocumentHeader; import org.kuali.rice.kns.rule.event.KualiDocumentEvent; import org.kuali.rice.kns.service.CountryService; import org.kuali.rice.kns.service.DataDictionaryService; import org.kuali.rice.kns.service.DateTimeService; import org.kuali.rice.kns.service.KualiModuleService; import org.kuali.rice.kns.util.GlobalVariables; import org.kuali.rice.kns.util.KNSPropertyConstants; import org.kuali.rice.kns.util.ObjectUtils; import org.kuali.rice.kns.workflow.service.KualiWorkflowDocument; public class BulkReceivingDocument extends FinancialSystemTransactionalDocumentBase implements ReceivingDocument{ private static final Logger LOG = Logger.getLogger(BulkReceivingDocument.class); private Integer purchaseOrderIdentifier; private Date shipmentReceivedDate; private String shipmentPackingSlipNumber; private String carrierCode; private String shipmentBillOfLadingNumber; private String shipmentReferenceNumber; private String shipmentWeight; private Integer noOfCartons; private String trackingNumber; /** * Primary Vendor */ private Integer vendorHeaderGeneratedIdentifier; private Integer vendorDetailAssignedIdentifier; private String vendorName; private String vendorLine1Address; private String vendorLine2Address; private String vendorCityName; private String vendorStateCode; private String vendorPostalCode; private String vendorCountryCode; private String vendorAddressInternationalProvinceName; private String vendorNoteText; /** * Alternate Vendor */ private Integer alternateVendorHeaderGeneratedIdentifier; private Integer alternateVendorDetailAssignedIdentifier; private String alternateVendorName; /** * Goods delivered vendor */ private Integer goodsDeliveredVendorHeaderGeneratedIdentifier; private Integer goodsDeliveredVendorDetailAssignedIdentifier; private String goodsDeliveredVendorNumber; /** * Delivery Information */ private boolean deliveryBuildingOtherIndicator; private String deliveryBuildingCode; private String deliveryBuildingName; private String deliveryBuildingRoomNumber; private String deliveryBuildingLine1Address; private String deliveryBuildingLine2Address; private String deliveryCityName; private String deliveryStateCode; private String deliveryPostalCode; private String deliveryCountryCode; private String deliveryCampusCode; private String deliveryInstructionText; private String deliveryAdditionalInstructionText; private String deliveryToName; private String deliveryToEmailAddress; private String deliveryToPhoneNumber; private String requestorPersonName; private String requestorPersonPhoneNumber; private String requestorPersonEmailAddress; private String preparerPersonName; private String preparerPersonPhoneNumber; private String deliveryCampusName; private String institutionContactName; private String institutionContactPhoneNumber; private String institutionContactEmailAddress; private Campus deliveryCampus; private Country vendorCountry; private Carrier carrier; private VendorDetail vendorDetail; private VendorDetail alternateVendorDetail; private Integer accountsPayablePurchasingDocumentLinkIdentifier; private transient PurApRelatedViews relatedViews; /** * Not persisted in DB */ private String vendorNumber; private String alternateVendorNumber; private String goodsDeliveredVendorName; private String vendorContact; private Integer vendorAddressGeneratedIdentifier; private boolean sensitive; public BulkReceivingDocument() { super(); } public boolean isSensitive() { List<SensitiveData> sensitiveData = SpringContext.getBean(SensitiveDataService.class).getSensitiveDatasAssignedByRelatedDocId(getAccountsPayablePurchasingDocumentLinkIdentifier()); if (ObjectUtils.isNotNull(sensitiveData) && !sensitiveData.isEmpty()) { return true; } return false; } public void initiateDocument(){ setShipmentReceivedDate(SpringContext.getBean(DateTimeService.class).getCurrentSqlDate()); } public void populateBulkReceivingFromPurchaseOrder(PurchaseOrderDocument po){ setPurchaseOrderIdentifier( po.getPurapDocumentIdentifier() ); getDocumentHeader().setOrganizationDocumentNumber( po.getDocumentHeader().getOrganizationDocumentNumber() ); setAccountsPayablePurchasingDocumentLinkIdentifier( po.getAccountsPayablePurchasingDocumentLinkIdentifier() ); //copy vendor setVendorHeaderGeneratedIdentifier( po.getVendorHeaderGeneratedIdentifier() ); setVendorDetailAssignedIdentifier( po.getVendorDetailAssignedIdentifier() ); setVendorName( po.getVendorName() ); setVendorNumber( po.getVendorNumber() ); setVendorLine1Address( po.getVendorLine1Address() ); setVendorLine2Address( po.getVendorLine2Address() ); setVendorCityName( po.getVendorCityName() ); setVendorStateCode( po.getVendorStateCode() ); setVendorPostalCode( po.getVendorPostalCode() ); setVendorCountryCode( po.getVendorCountryCode() ); setVendorDetail(po.getVendorDetail()); setVendorNumber(po.getVendorNumber()); setVendorAddressInternationalProvinceName(po.getVendorAddressInternationalProvinceName()); setVendorNoteText(po.getVendorNoteText()); setVendorAddressGeneratedIdentifier(po.getVendorAddressGeneratedIdentifier()); //copy alternate vendor setAlternateVendorName( po.getAlternateVendorName() ); setAlternateVendorNumber( StringUtils.isEmpty(po.getAlternateVendorNumber()) ? null : po.getAlternateVendorNumber()); setAlternateVendorDetailAssignedIdentifier( po.getAlternateVendorDetailAssignedIdentifier() ); setAlternateVendorHeaderGeneratedIdentifier( po.getAlternateVendorHeaderGeneratedIdentifier() ); //copy delivery setDeliveryBuildingCode( po.getDeliveryBuildingCode() ); setDeliveryBuildingLine1Address( po.getDeliveryBuildingLine1Address() ); setDeliveryBuildingLine2Address( po.getDeliveryBuildingLine2Address() ); setDeliveryBuildingName( po.getDeliveryBuildingName() ); setDeliveryBuildingRoomNumber( po.getDeliveryBuildingRoomNumber() ); setDeliveryCampusCode( po.getDeliveryCampusCode() ); setDeliveryCityName( po.getDeliveryCityName() ); setDeliveryCountryCode( po.getDeliveryCountryCode() ); setDeliveryInstructionText( po.getDeliveryInstructionText() ); setDeliveryPostalCode( po.getDeliveryPostalCode() ); setDeliveryStateCode( po.getDeliveryStateCode() ); setDeliveryToEmailAddress( po.getDeliveryToEmailAddress() ); setDeliveryToName( po.getDeliveryToName() ); setDeliveryToPhoneNumber( po.getDeliveryToPhoneNumber() ); setInstitutionContactName(po.getInstitutionContactName()); setInstitutionContactPhoneNumber(po.getInstitutionContactPhoneNumber()); setInstitutionContactEmailAddress(po.getInstitutionContactEmailAddress()); //Requestor and Requisition preparer setRequestorPersonName(po.getRequestorPersonName()); setRequestorPersonPhoneNumber(po.getRequestorPersonPhoneNumber()); setRequestorPersonEmailAddress(po.getRequestorPersonEmailAddress()); RequisitionDocument reqDoc = SpringContext.getBean(RequisitionService.class).getRequisitionById(po.getRequisitionIdentifier()); if (reqDoc != null){ // reqDoc is null when called from unit test String requisitionPreparer = reqDoc.getDocumentHeader().getWorkflowDocument().getInitiatorNetworkId(); /** * This is to get the user name for display */ Person initiatorUser = org.kuali.rice.kim.service.KIMServiceLocator.getPersonService().getPersonByPrincipalName(requisitionPreparer); setPreparerPersonName(initiatorUser.getName()); } if (getVendorNumber() != null){ setGoodsDeliveredVendorHeaderGeneratedIdentifier(getVendorHeaderGeneratedIdentifier()); setGoodsDeliveredVendorDetailAssignedIdentifier(getVendorDetailAssignedIdentifier()); setGoodsDeliveredVendorNumber(getVendorNumber()); setGoodsDeliveredVendorName(getVendorName()); } populateVendorDetails(); populateDocumentDescription(po); } private void populateVendorDetails(){ if (getVendorHeaderGeneratedIdentifier() != null && getVendorDetailAssignedIdentifier() != null){ VendorDetail tempVendor = new VendorDetail(); tempVendor.setVendorHeaderGeneratedIdentifier(getVendorHeaderGeneratedIdentifier()); tempVendor.setVendorDetailAssignedIdentifier(getVendorDetailAssignedIdentifier()); setVendorNumber(tempVendor.getVendorNumber()); } if (getAlternateVendorHeaderGeneratedIdentifier() != null && getAlternateVendorDetailAssignedIdentifier() != null){ VendorDetail vendorDetail = SpringContext.getBean(VendorService.class).getVendorDetail(getAlternateVendorHeaderGeneratedIdentifier(), getAlternateVendorDetailAssignedIdentifier()); //copied from creditmemocreateserviceimpl.populatedocumentfromvendor String userCampus = GlobalVariables.getUserSession().getPerson().getCampusCode(); VendorAddress vendorAddress = SpringContext.getBean(VendorService.class).getVendorDefaultAddress(getAlternateVendorHeaderGeneratedIdentifier(), getAlternateVendorDetailAssignedIdentifier(), VendorConstants.AddressTypes.REMIT, userCampus); if (vendorAddress == null) { // pick up the default vendor po address type vendorAddress = SpringContext.getBean(VendorService.class).getVendorDefaultAddress(getAlternateVendorHeaderGeneratedIdentifier(), getAlternateVendorDetailAssignedIdentifier(), VendorConstants.AddressTypes.PURCHASE_ORDER, userCampus); } if (vendorAddress != null){ setAlternateVendorName(vendorDetail.getVendorName()); setAlternateVendorNumber(vendorDetail.getVendorNumber()); vendorDetail.setDefaultAddressLine1(vendorAddress.getVendorLine1Address()); vendorDetail.setDefaultAddressLine2(vendorAddress.getVendorLine2Address()); vendorDetail.setDefaultAddressCity(vendorAddress.getVendorCityName()); vendorDetail.setDefaultAddressCountryCode(vendorAddress.getVendorCountryCode()); vendorDetail.setDefaultAddressPostalCode(vendorAddress.getVendorZipCode()); vendorDetail.setDefaultAddressStateCode(vendorAddress.getVendorStateCode()); vendorDetail.setDefaultAddressInternationalProvince(vendorAddress.getVendorAddressInternationalProvinceName()); } setAlternateVendorDetail(vendorDetail); } if (getGoodsDeliveredVendorHeaderGeneratedIdentifier() != null && getGoodsDeliveredVendorDetailAssignedIdentifier() != null){ VendorDetail tempVendor = new VendorDetail(); tempVendor.setVendorHeaderGeneratedIdentifier(getGoodsDeliveredVendorHeaderGeneratedIdentifier()); tempVendor.setVendorDetailAssignedIdentifier(getGoodsDeliveredVendorDetailAssignedIdentifier()); setGoodsDeliveredVendorNumber(tempVendor.getVendorNumber()); if (StringUtils.equals(getVendorNumber(),getGoodsDeliveredVendorNumber())){ setGoodsDeliveredVendorName(getVendorName()); }else { setGoodsDeliveredVendorName(getAlternateVendorName()); } } } /** * Perform logic needed to clear the initial fields on a Receiving Line Document */ public void clearInitFields() { // Clearing document overview fields getDocumentHeader().setDocumentDescription(null); getDocumentHeader().setExplanation(null); getDocumentHeader().setFinancialDocumentTotalAmount(null); getDocumentHeader().setOrganizationDocumentNumber(null); setPurchaseOrderIdentifier(null); setShipmentReceivedDate(SpringContext.getBean(DateTimeService.class).getCurrentSqlDate()); setShipmentPackingSlipNumber(null); setShipmentBillOfLadingNumber(null); setCarrierCode(null); } @Override public void processAfterRetrieve() { super.processAfterRetrieve(); refreshNonUpdateableReferences(); populateVendorDetails(); } @Override public void prepareForSave(KualiDocumentEvent event) { if (event instanceof AttributedContinuePurapEvent) { SpringContext.getBean(BulkReceivingService.class).populateBulkReceivingFromPurchaseOrder(this); if (getPurchaseOrderIdentifier() == null){ getDocumentHeader().setDocumentDescription(PurapConstants.BulkReceivingDocumentStrings.MESSAGE_BULK_RECEIVING_DEFAULT_DOC_DESCRIPTION);; } }else{ if (getGoodsDeliveredVendorNumber() != null){ VendorDetail tempVendor = new VendorDetail(); tempVendor.setVendorNumber(getGoodsDeliveredVendorNumber()); setGoodsDeliveredVendorHeaderGeneratedIdentifier(tempVendor.getVendorHeaderGeneratedIdentifier()); setGoodsDeliveredVendorDetailAssignedIdentifier(tempVendor.getVendorDetailAssignedIdentifier()); } } super.prepareForSave(event); } private void populateDocumentDescription(PurchaseOrderDocument poDocument) { String description = "PO: " + poDocument.getPurapDocumentIdentifier() + " Vendor: " + poDocument.getVendorName(); int noteTextMaxLength = SpringContext.getBean(DataDictionaryService.class).getAttributeMaxLength(DocumentHeader.class, KNSPropertyConstants.DOCUMENT_DESCRIPTION).intValue(); if (noteTextMaxLength < description.length()) { description = description.substring(0, noteTextMaxLength); } getDocumentHeader().setDocumentDescription(description); } public Integer getAccountsPayablePurchasingDocumentLinkIdentifier() { return accountsPayablePurchasingDocumentLinkIdentifier; } public void setAccountsPayablePurchasingDocumentLinkIdentifier(Integer accountsPayablePurchasingDocumentLinkIdentifier) { this.accountsPayablePurchasingDocumentLinkIdentifier = accountsPayablePurchasingDocumentLinkIdentifier; } public Integer getAlternateVendorDetailAssignedIdentifier() { return alternateVendorDetailAssignedIdentifier; } public void setAlternateVendorDetailAssignedIdentifier(Integer alternateVendorDetailAssignedIdentifier) { this.alternateVendorDetailAssignedIdentifier = alternateVendorDetailAssignedIdentifier; } public Integer getAlternateVendorHeaderGeneratedIdentifier() { return alternateVendorHeaderGeneratedIdentifier; } public void setAlternateVendorHeaderGeneratedIdentifier(Integer alternateVendorHeaderGeneratedIdentifier) { this.alternateVendorHeaderGeneratedIdentifier = alternateVendorHeaderGeneratedIdentifier; } public String getAlternateVendorName() { return alternateVendorName; } public void setAlternateVendorName(String alternateVendorName) { this.alternateVendorName = alternateVendorName; } public Carrier getCarrier() { return carrier; } public void setCarrier(Carrier carrier) { this.carrier = carrier; } public String getCarrierCode() { return carrierCode; } public void setCarrierCode(String carrierCode) { this.carrierCode = carrierCode; } public String getDeliveryBuildingCode() { return deliveryBuildingCode; } public void setDeliveryBuildingCode(String deliveryBuildingCode) { this.deliveryBuildingCode = deliveryBuildingCode; } public String getDeliveryBuildingLine1Address() { return deliveryBuildingLine1Address; } public void setDeliveryBuildingLine1Address(String deliveryBuildingLine1Address) { this.deliveryBuildingLine1Address = deliveryBuildingLine1Address; } public String getDeliveryBuildingLine2Address() { return deliveryBuildingLine2Address; } public void setDeliveryBuildingLine2Address(String deliveryBuildingLine2Address) { this.deliveryBuildingLine2Address = deliveryBuildingLine2Address; } public String getDeliveryBuildingName() { return deliveryBuildingName; } public void setDeliveryBuildingName(String deliveryBuildingName) { this.deliveryBuildingName = deliveryBuildingName; } public String getDeliveryBuildingRoomNumber() { return deliveryBuildingRoomNumber; } public void setDeliveryBuildingRoomNumber(String deliveryBuildingRoomNumber) { this.deliveryBuildingRoomNumber = deliveryBuildingRoomNumber; } public Campus getDeliveryCampus() { return deliveryCampus = (Campus) SpringContext.getBean(KualiModuleService.class).getResponsibleModuleService(Campus.class).retrieveExternalizableBusinessObjectIfNecessary(this, deliveryCampus, "deliveryCampus"); } public void setDeliveryCampus(Campus deliveryCampus) { this.deliveryCampus = deliveryCampus; } public String getDeliveryCampusCode() { return deliveryCampusCode; } public void setDeliveryCampusCode(String deliveryCampusCode) { this.deliveryCampusCode = deliveryCampusCode; } public String getDeliveryCityName() { return deliveryCityName; } public void setDeliveryCityName(String deliveryCityName) { this.deliveryCityName = deliveryCityName; } public String getDeliveryCountryCode() { return deliveryCountryCode; } public void setDeliveryCountryCode(String deliveryCountryCode) { this.deliveryCountryCode = deliveryCountryCode; } public String getDeliveryCountryName() { Country country = SpringContext.getBean(CountryService.class).getByPrimaryId(getDeliveryCountryCode()); if (country != null) return country.getPostalCountryName(); return null; } public String getDeliveryInstructionText() { return deliveryInstructionText; } public void setDeliveryInstructionText(String deliveryInstructionText) { this.deliveryInstructionText = deliveryInstructionText; } public String getDeliveryPostalCode() { return deliveryPostalCode; } public void setDeliveryPostalCode(String deliveryPostalCode) { this.deliveryPostalCode = deliveryPostalCode; } public String getDeliveryStateCode() { return deliveryStateCode; } public void setDeliveryStateCode(String deliveryStateCode) { this.deliveryStateCode = deliveryStateCode; } public String getDeliveryToEmailAddress() { return deliveryToEmailAddress; } public void setDeliveryToEmailAddress(String deliveryToEmailAddress) { this.deliveryToEmailAddress = deliveryToEmailAddress; } public String getDeliveryToName() { return deliveryToName; } public void setDeliveryToName(String deliveryToName) { this.deliveryToName = deliveryToName; } public String getDeliveryToPhoneNumber() { return deliveryToPhoneNumber; } public void setDeliveryToPhoneNumber(String deliveryToPhoneNumber) { this.deliveryToPhoneNumber = deliveryToPhoneNumber; } public String getGoodsDeliveredVendorNumber() { return goodsDeliveredVendorNumber; } public void setGoodsDeliveredVendorNumber(String goodsDeliveredVendorNumber) { this.goodsDeliveredVendorNumber = goodsDeliveredVendorNumber; } public Integer getNoOfCartons() { return noOfCartons; } public void setNoOfCartons(Integer noOfCartons) { this.noOfCartons = noOfCartons; } public Integer getPurchaseOrderIdentifier() { return purchaseOrderIdentifier; } public void setPurchaseOrderIdentifier(Integer purchaseOrderIdentifier) { this.purchaseOrderIdentifier = purchaseOrderIdentifier; } public String getShipmentBillOfLadingNumber() { return shipmentBillOfLadingNumber; } public void setShipmentBillOfLadingNumber(String shipmentBillOfLadingNumber) { this.shipmentBillOfLadingNumber = shipmentBillOfLadingNumber; } public String getShipmentPackingSlipNumber() { return shipmentPackingSlipNumber; } public void setShipmentPackingSlipNumber(String shipmentPackingSlipNumber) { this.shipmentPackingSlipNumber = shipmentPackingSlipNumber; } public Date getShipmentReceivedDate() { return shipmentReceivedDate; } public void setShipmentReceivedDate(Date shipmentReceivedDate) { this.shipmentReceivedDate = shipmentReceivedDate; } public String getShipmentReferenceNumber() { return shipmentReferenceNumber; } public void setShipmentReferenceNumber(String shipmentReferenceNumber) { this.shipmentReferenceNumber = shipmentReferenceNumber; } public String getVendorCityName() { return vendorCityName; } public void setVendorCityName(String vendorCityName) { this.vendorCityName = vendorCityName; } public Country getVendorCountry() { vendorCountry = SpringContext.getBean(CountryService.class).getByPrimaryIdIfNecessary(this, vendorCountryCode, vendorCountry); return vendorCountry; } public void setVendorCountry(Country vendorCountry) { this.vendorCountry = vendorCountry; } public String getVendorCountryCode() { return vendorCountryCode; } public void setVendorCountryCode(String vendorCountryCode) { this.vendorCountryCode = vendorCountryCode; } public VendorDetail getVendorDetail() { return vendorDetail; } public void setVendorDetail(VendorDetail vendorDetail) { this.vendorDetail = vendorDetail; } public Integer getVendorDetailAssignedIdentifier() { return vendorDetailAssignedIdentifier; } public void setVendorDetailAssignedIdentifier(Integer vendorDetailAssignedIdentifier) { this.vendorDetailAssignedIdentifier = vendorDetailAssignedIdentifier; } public Integer getVendorHeaderGeneratedIdentifier() { return vendorHeaderGeneratedIdentifier; } public void setVendorHeaderGeneratedIdentifier(Integer vendorHeaderGeneratedIdentifier) { this.vendorHeaderGeneratedIdentifier = vendorHeaderGeneratedIdentifier; } public String getVendorLine1Address() { return vendorLine1Address; } public void setVendorLine1Address(String vendorLine1Address) { this.vendorLine1Address = vendorLine1Address; } public String getVendorLine2Address() { return vendorLine2Address; } public void setVendorLine2Address(String vendorLine2Address) { this.vendorLine2Address = vendorLine2Address; } public String getVendorName() { return vendorName; } public void setVendorName(String vendorName) { this.vendorName = vendorName; } public String getVendorPostalCode() { return vendorPostalCode; } public void setVendorPostalCode(String vendorPostalCode) { this.vendorPostalCode = vendorPostalCode; } public String getVendorStateCode() { return vendorStateCode; } public void setVendorStateCode(String vendorStateCode) { this.vendorStateCode = vendorStateCode; } public String getVendorNumber() { return vendorNumber; } public void setVendorNumber(String vendorNumber) { this.vendorNumber = vendorNumber; } public String getAlternateVendorNumber() { return alternateVendorNumber; } public void setAlternateVendorNumber(String alternateVendorNumber) { this.alternateVendorNumber = alternateVendorNumber; } public String getVendorContact() { return vendorContact; } public void setVendorContact(String vendorContact) { this.vendorContact = vendorContact; } public VendorDetail getAlternateVendorDetail() { return alternateVendorDetail; } public void setAlternateVendorDetail(VendorDetail alternateVendorDetail) { this.alternateVendorDetail = alternateVendorDetail; } public String getShipmentWeight() { return shipmentWeight; } public void setShipmentWeight(String shipmentWeight) { this.shipmentWeight = shipmentWeight; } public String getGoodsDeliveredVendorName() { return goodsDeliveredVendorName; } public void setGoodsDeliveredVendorName(String goodsDeliveredVendorName) { this.goodsDeliveredVendorName = goodsDeliveredVendorName; } public String getVendorAddressInternationalProvinceName() { return vendorAddressInternationalProvinceName; } public void setVendorAddressInternationalProvinceName(String vendorAddressInternationalProvinceName) { this.vendorAddressInternationalProvinceName = vendorAddressInternationalProvinceName; } public String getDeliveryCampusName() { return deliveryCampusName; } public void setDeliveryCampusName(String deliveryCampusName) { this.deliveryCampusName = deliveryCampusName; } public String getRequestorPersonName() { return requestorPersonName; } public void setRequestorPersonName(String requestorPersonName) { this.requestorPersonName = requestorPersonName; } public String getRequestorPersonPhoneNumber() { return requestorPersonPhoneNumber; } public void setRequestorPersonPhoneNumber(String requestorPersonPhoneNumber) { this.requestorPersonPhoneNumber = requestorPersonPhoneNumber; } public String getPreparerPersonName() { return preparerPersonName; } public void setPreparerPersonName(String preparerPersonName) { this.preparerPersonName = preparerPersonName; } public String getPreparerPersonPhoneNumber() { return preparerPersonPhoneNumber; } public void setPreparerPersonPhoneNumber(String preparerPersonPhoneNumber) { this.preparerPersonPhoneNumber = preparerPersonPhoneNumber; } public String getTrackingNumber() { return trackingNumber; } public void setTrackingNumber(String trackingNumber) { this.trackingNumber = trackingNumber; } public String getVendorNoteText() { return vendorNoteText; } public void setVendorNoteText(String vendorNoteText) { this.vendorNoteText = vendorNoteText; } public String getRequestorPersonEmailAddress() { return requestorPersonEmailAddress; } public void setRequestorPersonEmailAddress(String requestorPersonEmailAddress) { this.requestorPersonEmailAddress = requestorPersonEmailAddress; } public String getInstitutionContactEmailAddress() { return institutionContactEmailAddress; } public void setInstitutionContactEmailAddress(String institutionContactEmailAddress) { this.institutionContactEmailAddress = institutionContactEmailAddress; } public String getInstitutionContactName() { return institutionContactName; } public void setInstitutionContactName(String institutionContactName) { this.institutionContactName = institutionContactName; } public String getInstitutionContactPhoneNumber() { return institutionContactPhoneNumber; } public void setInstitutionContactPhoneNumber(String institutionContactPhoneNumber) { this.institutionContactPhoneNumber = institutionContactPhoneNumber; } public String getDeliveryAdditionalInstructionText() { return deliveryAdditionalInstructionText; } public void setDeliveryAdditionalInstructionText(String deliveryAdditionalInstructionText) { this.deliveryAdditionalInstructionText = deliveryAdditionalInstructionText; } public Integer getGoodsDeliveredVendorDetailAssignedIdentifier() { return goodsDeliveredVendorDetailAssignedIdentifier; } public void setGoodsDeliveredVendorDetailAssignedIdentifier(Integer goodsDeliveredVendorDetailAssignedIdentifier) { this.goodsDeliveredVendorDetailAssignedIdentifier = goodsDeliveredVendorDetailAssignedIdentifier; } public Integer getGoodsDeliveredVendorHeaderGeneratedIdentifier() { return goodsDeliveredVendorHeaderGeneratedIdentifier; } public void setGoodsDeliveredVendorHeaderGeneratedIdentifier(Integer goodsDeliveredVendorHeaderGeneratedIdentifier) { this.goodsDeliveredVendorHeaderGeneratedIdentifier = goodsDeliveredVendorHeaderGeneratedIdentifier; } public Integer getVendorAddressGeneratedIdentifier() { return vendorAddressGeneratedIdentifier; } public void setVendorAddressGeneratedIdentifier(Integer vendorAddressGeneratedIdentifier) { this.vendorAddressGeneratedIdentifier = vendorAddressGeneratedIdentifier; } public void setRelatedViews(PurApRelatedViews relatedViews) { this.relatedViews = relatedViews; } public PurApRelatedViews getRelatedViews() { if (relatedViews == null) { relatedViews = new PurApRelatedViews(this.documentNumber, this.accountsPayablePurchasingDocumentLinkIdentifier); } return relatedViews; } public void appSpecificRouteDocumentToUser(KualiWorkflowDocument workflowDocument, String userNetworkId, String annotation, String responsibility) throws WorkflowException { // TODO Auto-generated method stub } public Date getDeliveryRequiredDate() { // TODO Auto-generated method stub return null; } public DeliveryRequiredDateReason getDeliveryRequiredDateReason() { // TODO Auto-generated method stub return null; } public String getDeliveryRequiredDateReasonCode() { // TODO Auto-generated method stub return null; } public AccountsPayableDocumentSpecificService getDocumentSpecificService() { // TODO Auto-generated method stub return null; } public PurchaseOrderDocument getPurchaseOrderDocument() { // TODO Auto-generated method stub return null; } public boolean isDeliveryBuildingOtherIndicator() { return deliveryBuildingOtherIndicator; } public void setDeliveryBuildingOtherIndicator(boolean deliveryBuildingOtherIndicator) { this.deliveryBuildingOtherIndicator = deliveryBuildingOtherIndicator; } /** * TODO: Have to discuss with Chris/Dan to move all these methods to somewhere else in the Receiving class hierarchy * @see org.kuali.kfs.module.purap.document.ReceivingDocument#setDeliveryRequiredDate(java.sql.Date) */ public void setDeliveryRequiredDate(Date deliveryRequiredDate) { // TODO Auto-generated method stub } public void setDeliveryRequiredDateReasonCode(String deliveryRequiredDateReasonCode) { // TODO Auto-generated method stub } public void setPurchaseOrderDocument(PurchaseOrderDocument po) { // TODO Auto-generated method stub } public <T> T getItem(int pos) { // TODO Auto-generated method stub return null; } public Class getItemClass() { // TODO Auto-generated method stub return null; } public List getItems() { // TODO Auto-generated method stub return null; } public void setItems(List items) { // TODO Auto-generated method stub } @Override public boolean isBoNotesSupport() { return true; } /** * Always returns false. * This method is needed here because it's called by some tag files shared with PurAp documents. */ public boolean getIsATypeOfPurDoc() { return false; } /** * Always returns false. * This method is needed here because it's called by some tag files shared with PurAp documents. */ public boolean getIsATypeOfPODoc() { return false; } /** * Always returns false. * This method is needed here because it's called by some tag files shared with PurAp documents. */ public boolean getIsPODoc() { return false; } /** * Always returns false. * This method is needed here because it's called by some tag files shared with PurAp documents. */ public boolean getIsReqsDoc() { return false; } protected LinkedHashMap toStringMapper() { LinkedHashMap m = new LinkedHashMap(); m.put("documentNumber", this.documentNumber); m.put("PO", getPurchaseOrderIdentifier()); return m; } }
work/src/org/kuali/kfs/module/purap/document/BulkReceivingDocument.java
/* * Copyright 2006-2007 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kfs.module.purap.document; import java.sql.Date; import java.util.LinkedHashMap; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.kuali.kfs.module.purap.PurapConstants; import org.kuali.kfs.module.purap.businessobject.Carrier; import org.kuali.kfs.module.purap.businessobject.DeliveryRequiredDateReason; import org.kuali.kfs.module.purap.businessobject.SensitiveData; import org.kuali.kfs.module.purap.document.service.AccountsPayableDocumentSpecificService; import org.kuali.kfs.module.purap.document.service.BulkReceivingService; import org.kuali.kfs.module.purap.document.service.RequisitionService; import org.kuali.kfs.module.purap.document.validation.event.AttributedContinuePurapEvent; import org.kuali.kfs.module.purap.service.SensitiveDataService; import org.kuali.kfs.module.purap.util.PurApRelatedViews; import org.kuali.kfs.sys.context.SpringContext; import org.kuali.kfs.sys.document.FinancialSystemTransactionalDocumentBase; import org.kuali.kfs.vnd.VendorConstants; import org.kuali.kfs.vnd.businessobject.VendorAddress; import org.kuali.kfs.vnd.businessobject.VendorDetail; import org.kuali.kfs.vnd.document.service.VendorService; import org.kuali.rice.kew.exception.WorkflowException; import org.kuali.rice.kim.bo.Person; import org.kuali.rice.kns.bo.Campus; import org.kuali.rice.kns.bo.Country; import org.kuali.rice.kns.bo.DocumentHeader; import org.kuali.rice.kns.rule.event.KualiDocumentEvent; import org.kuali.rice.kns.service.CountryService; import org.kuali.rice.kns.service.DataDictionaryService; import org.kuali.rice.kns.service.DateTimeService; import org.kuali.rice.kns.service.KualiModuleService; import org.kuali.rice.kns.util.GlobalVariables; import org.kuali.rice.kns.util.KNSPropertyConstants; import org.kuali.rice.kns.util.ObjectUtils; import org.kuali.rice.kns.workflow.service.KualiWorkflowDocument; public class BulkReceivingDocument extends FinancialSystemTransactionalDocumentBase implements ReceivingDocument{ private static final Logger LOG = Logger.getLogger(BulkReceivingDocument.class); private Integer purchaseOrderIdentifier; private Date shipmentReceivedDate; private String shipmentPackingSlipNumber; private String carrierCode; private String shipmentBillOfLadingNumber; private String shipmentReferenceNumber; private String shipmentWeight; private Integer noOfCartons; private String trackingNumber; /** * Primary Vendor */ private Integer vendorHeaderGeneratedIdentifier; private Integer vendorDetailAssignedIdentifier; private String vendorName; private String vendorLine1Address; private String vendorLine2Address; private String vendorCityName; private String vendorStateCode; private String vendorPostalCode; private String vendorCountryCode; private String vendorAddressInternationalProvinceName; private String vendorNoteText; /** * Alternate Vendor */ private Integer alternateVendorHeaderGeneratedIdentifier; private Integer alternateVendorDetailAssignedIdentifier; private String alternateVendorName; /** * Goods delivered vendor */ private Integer goodsDeliveredVendorHeaderGeneratedIdentifier; private Integer goodsDeliveredVendorDetailAssignedIdentifier; private String goodsDeliveredVendorNumber; /** * Delivery Information */ private boolean deliveryBuildingOtherIndicator; private String deliveryBuildingCode; private String deliveryBuildingName; private String deliveryBuildingRoomNumber; private String deliveryBuildingLine1Address; private String deliveryBuildingLine2Address; private String deliveryCityName; private String deliveryStateCode; private String deliveryPostalCode; private String deliveryCountryCode; private String deliveryCampusCode; private String deliveryInstructionText; private String deliveryAdditionalInstructionText; private String deliveryToName; private String deliveryToEmailAddress; private String deliveryToPhoneNumber; private String requestorPersonName; private String requestorPersonPhoneNumber; private String requestorPersonEmailAddress; private String preparerPersonName; private String preparerPersonPhoneNumber; private String deliveryCampusName; private String institutionContactName; private String institutionContactPhoneNumber; private String institutionContactEmailAddress; private Campus deliveryCampus; private Country vendorCountry; private Carrier carrier; private VendorDetail vendorDetail; private VendorDetail alternateVendorDetail; private Integer accountsPayablePurchasingDocumentLinkIdentifier; private transient PurApRelatedViews relatedViews; /** * Not persisted in DB */ private String vendorNumber; private String alternateVendorNumber; private String goodsDeliveredVendorName; private String vendorContact; private Integer vendorAddressGeneratedIdentifier; private boolean sensitive; public BulkReceivingDocument() { super(); } public boolean isSensitive() { List<SensitiveData> sensitiveData = SpringContext.getBean(SensitiveDataService.class).getSensitiveDatasAssignedByRelatedDocId(getAccountsPayablePurchasingDocumentLinkIdentifier()); if (ObjectUtils.isNotNull(sensitiveData) && !sensitiveData.isEmpty()) { return true; } return false; } public void initiateDocument(){ setShipmentReceivedDate(SpringContext.getBean(DateTimeService.class).getCurrentSqlDate()); } public void populateBulkReceivingFromPurchaseOrder(PurchaseOrderDocument po){ setPurchaseOrderIdentifier( po.getPurapDocumentIdentifier() ); getDocumentHeader().setOrganizationDocumentNumber( po.getDocumentHeader().getOrganizationDocumentNumber() ); setAccountsPayablePurchasingDocumentLinkIdentifier( po.getAccountsPayablePurchasingDocumentLinkIdentifier() ); //copy vendor setVendorHeaderGeneratedIdentifier( po.getVendorHeaderGeneratedIdentifier() ); setVendorDetailAssignedIdentifier( po.getVendorDetailAssignedIdentifier() ); setVendorName( po.getVendorName() ); setVendorNumber( po.getVendorNumber() ); setVendorLine1Address( po.getVendorLine1Address() ); setVendorLine2Address( po.getVendorLine2Address() ); setVendorCityName( po.getVendorCityName() ); setVendorStateCode( po.getVendorStateCode() ); setVendorPostalCode( po.getVendorPostalCode() ); setVendorCountryCode( po.getVendorCountryCode() ); setVendorDetail(po.getVendorDetail()); setVendorNumber(po.getVendorNumber()); setVendorAddressInternationalProvinceName(po.getVendorAddressInternationalProvinceName()); setVendorNoteText(po.getVendorNoteText()); setVendorAddressGeneratedIdentifier(po.getVendorAddressGeneratedIdentifier()); //copy alternate vendor setAlternateVendorName( po.getAlternateVendorName() ); setAlternateVendorNumber( StringUtils.isEmpty(po.getAlternateVendorNumber()) ? null : po.getAlternateVendorNumber()); setAlternateVendorDetailAssignedIdentifier( po.getAlternateVendorDetailAssignedIdentifier() ); setAlternateVendorHeaderGeneratedIdentifier( po.getAlternateVendorHeaderGeneratedIdentifier() ); //copy delivery setDeliveryBuildingCode( po.getDeliveryBuildingCode() ); setDeliveryBuildingLine1Address( po.getDeliveryBuildingLine1Address() ); setDeliveryBuildingLine2Address( po.getDeliveryBuildingLine2Address() ); setDeliveryBuildingName( po.getDeliveryBuildingName() ); setDeliveryBuildingRoomNumber( po.getDeliveryBuildingRoomNumber() ); setDeliveryCampusCode( po.getDeliveryCampusCode() ); setDeliveryCityName( po.getDeliveryCityName() ); setDeliveryCountryCode( po.getDeliveryCountryCode() ); setDeliveryInstructionText( po.getDeliveryInstructionText() ); setDeliveryPostalCode( po.getDeliveryPostalCode() ); setDeliveryStateCode( po.getDeliveryStateCode() ); setDeliveryToEmailAddress( po.getDeliveryToEmailAddress() ); setDeliveryToName( po.getDeliveryToName() ); setDeliveryToPhoneNumber( po.getDeliveryToPhoneNumber() ); setDeliveryCampus(po.getDeliveryCampus()); setInstitutionContactName(po.getInstitutionContactName()); setInstitutionContactPhoneNumber(po.getInstitutionContactPhoneNumber()); setInstitutionContactEmailAddress(po.getInstitutionContactEmailAddress()); //Requestor and Requisition preparer setRequestorPersonName(po.getRequestorPersonName()); setRequestorPersonPhoneNumber(po.getRequestorPersonPhoneNumber()); setRequestorPersonEmailAddress(po.getRequestorPersonEmailAddress()); RequisitionDocument reqDoc = SpringContext.getBean(RequisitionService.class).getRequisitionById(po.getRequisitionIdentifier()); if (reqDoc != null){ // reqDoc is null when called from unit test String requisitionPreparer = reqDoc.getDocumentHeader().getWorkflowDocument().getInitiatorNetworkId(); /** * This is to get the user name for display */ Person initiatorUser = org.kuali.rice.kim.service.KIMServiceLocator.getPersonService().getPersonByPrincipalName(requisitionPreparer); setPreparerPersonName(initiatorUser.getName()); } if (getVendorNumber() != null){ setGoodsDeliveredVendorHeaderGeneratedIdentifier(getVendorHeaderGeneratedIdentifier()); setGoodsDeliveredVendorDetailAssignedIdentifier(getVendorDetailAssignedIdentifier()); setGoodsDeliveredVendorNumber(getVendorNumber()); setGoodsDeliveredVendorName(getVendorName()); } populateVendorDetails(); populateDocumentDescription(po); } private void populateVendorDetails(){ if (getVendorHeaderGeneratedIdentifier() != null && getVendorDetailAssignedIdentifier() != null){ VendorDetail tempVendor = new VendorDetail(); tempVendor.setVendorHeaderGeneratedIdentifier(getVendorHeaderGeneratedIdentifier()); tempVendor.setVendorDetailAssignedIdentifier(getVendorDetailAssignedIdentifier()); setVendorNumber(tempVendor.getVendorNumber()); } if (getAlternateVendorHeaderGeneratedIdentifier() != null && getAlternateVendorDetailAssignedIdentifier() != null){ VendorDetail vendorDetail = SpringContext.getBean(VendorService.class).getVendorDetail(getAlternateVendorHeaderGeneratedIdentifier(), getAlternateVendorDetailAssignedIdentifier()); //copied from creditmemocreateserviceimpl.populatedocumentfromvendor String userCampus = GlobalVariables.getUserSession().getPerson().getCampusCode(); VendorAddress vendorAddress = SpringContext.getBean(VendorService.class).getVendorDefaultAddress(getAlternateVendorHeaderGeneratedIdentifier(), getAlternateVendorDetailAssignedIdentifier(), VendorConstants.AddressTypes.REMIT, userCampus); if (vendorAddress == null) { // pick up the default vendor po address type vendorAddress = SpringContext.getBean(VendorService.class).getVendorDefaultAddress(getAlternateVendorHeaderGeneratedIdentifier(), getAlternateVendorDetailAssignedIdentifier(), VendorConstants.AddressTypes.PURCHASE_ORDER, userCampus); } if (vendorAddress != null){ setAlternateVendorName(vendorDetail.getVendorName()); setAlternateVendorNumber(vendorDetail.getVendorNumber()); vendorDetail.setDefaultAddressLine1(vendorAddress.getVendorLine1Address()); vendorDetail.setDefaultAddressLine2(vendorAddress.getVendorLine2Address()); vendorDetail.setDefaultAddressCity(vendorAddress.getVendorCityName()); vendorDetail.setDefaultAddressCountryCode(vendorAddress.getVendorCountryCode()); vendorDetail.setDefaultAddressPostalCode(vendorAddress.getVendorZipCode()); vendorDetail.setDefaultAddressStateCode(vendorAddress.getVendorStateCode()); vendorDetail.setDefaultAddressInternationalProvince(vendorAddress.getVendorAddressInternationalProvinceName()); } setAlternateVendorDetail(vendorDetail); } if (getGoodsDeliveredVendorHeaderGeneratedIdentifier() != null && getGoodsDeliveredVendorDetailAssignedIdentifier() != null){ VendorDetail tempVendor = new VendorDetail(); tempVendor.setVendorHeaderGeneratedIdentifier(getGoodsDeliveredVendorHeaderGeneratedIdentifier()); tempVendor.setVendorDetailAssignedIdentifier(getGoodsDeliveredVendorDetailAssignedIdentifier()); setGoodsDeliveredVendorNumber(tempVendor.getVendorNumber()); if (StringUtils.equals(getVendorNumber(),getGoodsDeliveredVendorNumber())){ setGoodsDeliveredVendorName(getVendorName()); }else { setGoodsDeliveredVendorName(getAlternateVendorName()); } } } /** * Perform logic needed to clear the initial fields on a Receiving Line Document */ public void clearInitFields() { // Clearing document overview fields getDocumentHeader().setDocumentDescription(null); getDocumentHeader().setExplanation(null); getDocumentHeader().setFinancialDocumentTotalAmount(null); getDocumentHeader().setOrganizationDocumentNumber(null); setPurchaseOrderIdentifier(null); setShipmentReceivedDate(SpringContext.getBean(DateTimeService.class).getCurrentSqlDate()); setShipmentPackingSlipNumber(null); setShipmentBillOfLadingNumber(null); setCarrierCode(null); } @Override public void processAfterRetrieve() { super.processAfterRetrieve(); refreshNonUpdateableReferences(); populateVendorDetails(); } @Override public void prepareForSave(KualiDocumentEvent event) { if (event instanceof AttributedContinuePurapEvent) { SpringContext.getBean(BulkReceivingService.class).populateBulkReceivingFromPurchaseOrder(this); if (getPurchaseOrderIdentifier() == null){ getDocumentHeader().setDocumentDescription(PurapConstants.BulkReceivingDocumentStrings.MESSAGE_BULK_RECEIVING_DEFAULT_DOC_DESCRIPTION);; } }else{ if (getGoodsDeliveredVendorNumber() != null){ VendorDetail tempVendor = new VendorDetail(); tempVendor.setVendorNumber(getGoodsDeliveredVendorNumber()); setGoodsDeliveredVendorHeaderGeneratedIdentifier(tempVendor.getVendorHeaderGeneratedIdentifier()); setGoodsDeliveredVendorDetailAssignedIdentifier(tempVendor.getVendorDetailAssignedIdentifier()); } } super.prepareForSave(event); } private void populateDocumentDescription(PurchaseOrderDocument poDocument) { String description = "PO: " + poDocument.getPurapDocumentIdentifier() + " Vendor: " + poDocument.getVendorName(); int noteTextMaxLength = SpringContext.getBean(DataDictionaryService.class).getAttributeMaxLength(DocumentHeader.class, KNSPropertyConstants.DOCUMENT_DESCRIPTION).intValue(); if (noteTextMaxLength < description.length()) { description = description.substring(0, noteTextMaxLength); } getDocumentHeader().setDocumentDescription(description); } public Integer getAccountsPayablePurchasingDocumentLinkIdentifier() { return accountsPayablePurchasingDocumentLinkIdentifier; } public void setAccountsPayablePurchasingDocumentLinkIdentifier(Integer accountsPayablePurchasingDocumentLinkIdentifier) { this.accountsPayablePurchasingDocumentLinkIdentifier = accountsPayablePurchasingDocumentLinkIdentifier; } public Integer getAlternateVendorDetailAssignedIdentifier() { return alternateVendorDetailAssignedIdentifier; } public void setAlternateVendorDetailAssignedIdentifier(Integer alternateVendorDetailAssignedIdentifier) { this.alternateVendorDetailAssignedIdentifier = alternateVendorDetailAssignedIdentifier; } public Integer getAlternateVendorHeaderGeneratedIdentifier() { return alternateVendorHeaderGeneratedIdentifier; } public void setAlternateVendorHeaderGeneratedIdentifier(Integer alternateVendorHeaderGeneratedIdentifier) { this.alternateVendorHeaderGeneratedIdentifier = alternateVendorHeaderGeneratedIdentifier; } public String getAlternateVendorName() { return alternateVendorName; } public void setAlternateVendorName(String alternateVendorName) { this.alternateVendorName = alternateVendorName; } public Carrier getCarrier() { return carrier; } public void setCarrier(Carrier carrier) { this.carrier = carrier; } public String getCarrierCode() { return carrierCode; } public void setCarrierCode(String carrierCode) { this.carrierCode = carrierCode; } public String getDeliveryBuildingCode() { return deliveryBuildingCode; } public void setDeliveryBuildingCode(String deliveryBuildingCode) { this.deliveryBuildingCode = deliveryBuildingCode; } public String getDeliveryBuildingLine1Address() { return deliveryBuildingLine1Address; } public void setDeliveryBuildingLine1Address(String deliveryBuildingLine1Address) { this.deliveryBuildingLine1Address = deliveryBuildingLine1Address; } public String getDeliveryBuildingLine2Address() { return deliveryBuildingLine2Address; } public void setDeliveryBuildingLine2Address(String deliveryBuildingLine2Address) { this.deliveryBuildingLine2Address = deliveryBuildingLine2Address; } public String getDeliveryBuildingName() { return deliveryBuildingName; } public void setDeliveryBuildingName(String deliveryBuildingName) { this.deliveryBuildingName = deliveryBuildingName; } public String getDeliveryBuildingRoomNumber() { return deliveryBuildingRoomNumber; } public void setDeliveryBuildingRoomNumber(String deliveryBuildingRoomNumber) { this.deliveryBuildingRoomNumber = deliveryBuildingRoomNumber; } public Campus getDeliveryCampus() { return deliveryCampus = (Campus) SpringContext.getBean(KualiModuleService.class).getResponsibleModuleService(Campus.class).retrieveExternalizableBusinessObjectIfNecessary(this, deliveryCampus, "deliveryCampus"); } public void setDeliveryCampus(Campus deliveryCampus) { this.deliveryCampus = deliveryCampus; } public String getDeliveryCampusCode() { return deliveryCampusCode; } public void setDeliveryCampusCode(String deliveryCampusCode) { this.deliveryCampusCode = deliveryCampusCode; } public String getDeliveryCityName() { return deliveryCityName; } public void setDeliveryCityName(String deliveryCityName) { this.deliveryCityName = deliveryCityName; } public String getDeliveryCountryCode() { return deliveryCountryCode; } public void setDeliveryCountryCode(String deliveryCountryCode) { this.deliveryCountryCode = deliveryCountryCode; } public String getDeliveryCountryName() { Country country = SpringContext.getBean(CountryService.class).getByPrimaryId(getDeliveryCountryCode()); if (country != null) return country.getPostalCountryName(); return null; } public String getDeliveryInstructionText() { return deliveryInstructionText; } public void setDeliveryInstructionText(String deliveryInstructionText) { this.deliveryInstructionText = deliveryInstructionText; } public String getDeliveryPostalCode() { return deliveryPostalCode; } public void setDeliveryPostalCode(String deliveryPostalCode) { this.deliveryPostalCode = deliveryPostalCode; } public String getDeliveryStateCode() { return deliveryStateCode; } public void setDeliveryStateCode(String deliveryStateCode) { this.deliveryStateCode = deliveryStateCode; } public String getDeliveryToEmailAddress() { return deliveryToEmailAddress; } public void setDeliveryToEmailAddress(String deliveryToEmailAddress) { this.deliveryToEmailAddress = deliveryToEmailAddress; } public String getDeliveryToName() { return deliveryToName; } public void setDeliveryToName(String deliveryToName) { this.deliveryToName = deliveryToName; } public String getDeliveryToPhoneNumber() { return deliveryToPhoneNumber; } public void setDeliveryToPhoneNumber(String deliveryToPhoneNumber) { this.deliveryToPhoneNumber = deliveryToPhoneNumber; } public String getGoodsDeliveredVendorNumber() { return goodsDeliveredVendorNumber; } public void setGoodsDeliveredVendorNumber(String goodsDeliveredVendorNumber) { this.goodsDeliveredVendorNumber = goodsDeliveredVendorNumber; } public Integer getNoOfCartons() { return noOfCartons; } public void setNoOfCartons(Integer noOfCartons) { this.noOfCartons = noOfCartons; } public Integer getPurchaseOrderIdentifier() { return purchaseOrderIdentifier; } public void setPurchaseOrderIdentifier(Integer purchaseOrderIdentifier) { this.purchaseOrderIdentifier = purchaseOrderIdentifier; } public String getShipmentBillOfLadingNumber() { return shipmentBillOfLadingNumber; } public void setShipmentBillOfLadingNumber(String shipmentBillOfLadingNumber) { this.shipmentBillOfLadingNumber = shipmentBillOfLadingNumber; } public String getShipmentPackingSlipNumber() { return shipmentPackingSlipNumber; } public void setShipmentPackingSlipNumber(String shipmentPackingSlipNumber) { this.shipmentPackingSlipNumber = shipmentPackingSlipNumber; } public Date getShipmentReceivedDate() { return shipmentReceivedDate; } public void setShipmentReceivedDate(Date shipmentReceivedDate) { this.shipmentReceivedDate = shipmentReceivedDate; } public String getShipmentReferenceNumber() { return shipmentReferenceNumber; } public void setShipmentReferenceNumber(String shipmentReferenceNumber) { this.shipmentReferenceNumber = shipmentReferenceNumber; } public String getVendorCityName() { return vendorCityName; } public void setVendorCityName(String vendorCityName) { this.vendorCityName = vendorCityName; } public Country getVendorCountry() { vendorCountry = SpringContext.getBean(CountryService.class).getByPrimaryIdIfNecessary(this, vendorCountryCode, vendorCountry); return vendorCountry; } public void setVendorCountry(Country vendorCountry) { this.vendorCountry = vendorCountry; } public String getVendorCountryCode() { return vendorCountryCode; } public void setVendorCountryCode(String vendorCountryCode) { this.vendorCountryCode = vendorCountryCode; } public VendorDetail getVendorDetail() { return vendorDetail; } public void setVendorDetail(VendorDetail vendorDetail) { this.vendorDetail = vendorDetail; } public Integer getVendorDetailAssignedIdentifier() { return vendorDetailAssignedIdentifier; } public void setVendorDetailAssignedIdentifier(Integer vendorDetailAssignedIdentifier) { this.vendorDetailAssignedIdentifier = vendorDetailAssignedIdentifier; } public Integer getVendorHeaderGeneratedIdentifier() { return vendorHeaderGeneratedIdentifier; } public void setVendorHeaderGeneratedIdentifier(Integer vendorHeaderGeneratedIdentifier) { this.vendorHeaderGeneratedIdentifier = vendorHeaderGeneratedIdentifier; } public String getVendorLine1Address() { return vendorLine1Address; } public void setVendorLine1Address(String vendorLine1Address) { this.vendorLine1Address = vendorLine1Address; } public String getVendorLine2Address() { return vendorLine2Address; } public void setVendorLine2Address(String vendorLine2Address) { this.vendorLine2Address = vendorLine2Address; } public String getVendorName() { return vendorName; } public void setVendorName(String vendorName) { this.vendorName = vendorName; } public String getVendorPostalCode() { return vendorPostalCode; } public void setVendorPostalCode(String vendorPostalCode) { this.vendorPostalCode = vendorPostalCode; } public String getVendorStateCode() { return vendorStateCode; } public void setVendorStateCode(String vendorStateCode) { this.vendorStateCode = vendorStateCode; } public String getVendorNumber() { return vendorNumber; } public void setVendorNumber(String vendorNumber) { this.vendorNumber = vendorNumber; } public String getAlternateVendorNumber() { return alternateVendorNumber; } public void setAlternateVendorNumber(String alternateVendorNumber) { this.alternateVendorNumber = alternateVendorNumber; } public String getVendorContact() { return vendorContact; } public void setVendorContact(String vendorContact) { this.vendorContact = vendorContact; } public VendorDetail getAlternateVendorDetail() { return alternateVendorDetail; } public void setAlternateVendorDetail(VendorDetail alternateVendorDetail) { this.alternateVendorDetail = alternateVendorDetail; } public String getShipmentWeight() { return shipmentWeight; } public void setShipmentWeight(String shipmentWeight) { this.shipmentWeight = shipmentWeight; } public String getGoodsDeliveredVendorName() { return goodsDeliveredVendorName; } public void setGoodsDeliveredVendorName(String goodsDeliveredVendorName) { this.goodsDeliveredVendorName = goodsDeliveredVendorName; } public String getVendorAddressInternationalProvinceName() { return vendorAddressInternationalProvinceName; } public void setVendorAddressInternationalProvinceName(String vendorAddressInternationalProvinceName) { this.vendorAddressInternationalProvinceName = vendorAddressInternationalProvinceName; } public String getDeliveryCampusName() { return deliveryCampusName; } public void setDeliveryCampusName(String deliveryCampusName) { this.deliveryCampusName = deliveryCampusName; } public String getRequestorPersonName() { return requestorPersonName; } public void setRequestorPersonName(String requestorPersonName) { this.requestorPersonName = requestorPersonName; } public String getRequestorPersonPhoneNumber() { return requestorPersonPhoneNumber; } public void setRequestorPersonPhoneNumber(String requestorPersonPhoneNumber) { this.requestorPersonPhoneNumber = requestorPersonPhoneNumber; } public String getPreparerPersonName() { return preparerPersonName; } public void setPreparerPersonName(String preparerPersonName) { this.preparerPersonName = preparerPersonName; } public String getPreparerPersonPhoneNumber() { return preparerPersonPhoneNumber; } public void setPreparerPersonPhoneNumber(String preparerPersonPhoneNumber) { this.preparerPersonPhoneNumber = preparerPersonPhoneNumber; } public String getTrackingNumber() { return trackingNumber; } public void setTrackingNumber(String trackingNumber) { this.trackingNumber = trackingNumber; } public String getVendorNoteText() { return vendorNoteText; } public void setVendorNoteText(String vendorNoteText) { this.vendorNoteText = vendorNoteText; } public String getRequestorPersonEmailAddress() { return requestorPersonEmailAddress; } public void setRequestorPersonEmailAddress(String requestorPersonEmailAddress) { this.requestorPersonEmailAddress = requestorPersonEmailAddress; } public String getInstitutionContactEmailAddress() { return institutionContactEmailAddress; } public void setInstitutionContactEmailAddress(String institutionContactEmailAddress) { this.institutionContactEmailAddress = institutionContactEmailAddress; } public String getInstitutionContactName() { return institutionContactName; } public void setInstitutionContactName(String institutionContactName) { this.institutionContactName = institutionContactName; } public String getInstitutionContactPhoneNumber() { return institutionContactPhoneNumber; } public void setInstitutionContactPhoneNumber(String institutionContactPhoneNumber) { this.institutionContactPhoneNumber = institutionContactPhoneNumber; } public String getDeliveryAdditionalInstructionText() { return deliveryAdditionalInstructionText; } public void setDeliveryAdditionalInstructionText(String deliveryAdditionalInstructionText) { this.deliveryAdditionalInstructionText = deliveryAdditionalInstructionText; } public Integer getGoodsDeliveredVendorDetailAssignedIdentifier() { return goodsDeliveredVendorDetailAssignedIdentifier; } public void setGoodsDeliveredVendorDetailAssignedIdentifier(Integer goodsDeliveredVendorDetailAssignedIdentifier) { this.goodsDeliveredVendorDetailAssignedIdentifier = goodsDeliveredVendorDetailAssignedIdentifier; } public Integer getGoodsDeliveredVendorHeaderGeneratedIdentifier() { return goodsDeliveredVendorHeaderGeneratedIdentifier; } public void setGoodsDeliveredVendorHeaderGeneratedIdentifier(Integer goodsDeliveredVendorHeaderGeneratedIdentifier) { this.goodsDeliveredVendorHeaderGeneratedIdentifier = goodsDeliveredVendorHeaderGeneratedIdentifier; } public Integer getVendorAddressGeneratedIdentifier() { return vendorAddressGeneratedIdentifier; } public void setVendorAddressGeneratedIdentifier(Integer vendorAddressGeneratedIdentifier) { this.vendorAddressGeneratedIdentifier = vendorAddressGeneratedIdentifier; } public void setRelatedViews(PurApRelatedViews relatedViews) { this.relatedViews = relatedViews; } public PurApRelatedViews getRelatedViews() { if (relatedViews == null) { relatedViews = new PurApRelatedViews(this.documentNumber, this.accountsPayablePurchasingDocumentLinkIdentifier); } return relatedViews; } public void appSpecificRouteDocumentToUser(KualiWorkflowDocument workflowDocument, String userNetworkId, String annotation, String responsibility) throws WorkflowException { // TODO Auto-generated method stub } public Date getDeliveryRequiredDate() { // TODO Auto-generated method stub return null; } public DeliveryRequiredDateReason getDeliveryRequiredDateReason() { // TODO Auto-generated method stub return null; } public String getDeliveryRequiredDateReasonCode() { // TODO Auto-generated method stub return null; } public AccountsPayableDocumentSpecificService getDocumentSpecificService() { // TODO Auto-generated method stub return null; } public PurchaseOrderDocument getPurchaseOrderDocument() { // TODO Auto-generated method stub return null; } public boolean isDeliveryBuildingOtherIndicator() { return deliveryBuildingOtherIndicator; } public void setDeliveryBuildingOtherIndicator(boolean deliveryBuildingOtherIndicator) { this.deliveryBuildingOtherIndicator = deliveryBuildingOtherIndicator; } /** * TODO: Have to discuss with Chris/Dan to move all these methods to somewhere else in the Receiving class hierarchy * @see org.kuali.kfs.module.purap.document.ReceivingDocument#setDeliveryRequiredDate(java.sql.Date) */ public void setDeliveryRequiredDate(Date deliveryRequiredDate) { // TODO Auto-generated method stub } public void setDeliveryRequiredDateReasonCode(String deliveryRequiredDateReasonCode) { // TODO Auto-generated method stub } public void setPurchaseOrderDocument(PurchaseOrderDocument po) { // TODO Auto-generated method stub } public <T> T getItem(int pos) { // TODO Auto-generated method stub return null; } public Class getItemClass() { // TODO Auto-generated method stub return null; } public List getItems() { // TODO Auto-generated method stub return null; } public void setItems(List items) { // TODO Auto-generated method stub } @Override public boolean isBoNotesSupport() { return true; } /** * Always returns false. * This method is needed here because it's called by some tag files shared with PurAp documents. */ public boolean getIsATypeOfPurDoc() { return false; } /** * Always returns false. * This method is needed here because it's called by some tag files shared with PurAp documents. */ public boolean getIsATypeOfPODoc() { return false; } /** * Always returns false. * This method is needed here because it's called by some tag files shared with PurAp documents. */ public boolean getIsPODoc() { return false; } /** * Always returns false. * This method is needed here because it's called by some tag files shared with PurAp documents. */ public boolean getIsReqsDoc() { return false; } protected LinkedHashMap toStringMapper() { LinkedHashMap m = new LinkedHashMap(); m.put("documentNumber", this.documentNumber); m.put("PO", getPurchaseOrderIdentifier()); return m; } }
KULPURAP-3735 - NPE when clicking contiune in bulk receiving
work/src/org/kuali/kfs/module/purap/document/BulkReceivingDocument.java
KULPURAP-3735 - NPE when clicking contiune in bulk receiving
Java
agpl-3.0
1ca527447e9538995d9295cbe0fe964a4bf0e87f
0
bisq-network/exchange,bisq-network/exchange,bitsquare/bitsquare,bitsquare/bitsquare
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.core.filter; import bisq.core.btc.nodes.BtcNodes; import bisq.core.locale.Res; import bisq.core.payment.payload.PaymentAccountPayload; import bisq.core.payment.payload.PaymentMethod; import bisq.core.provider.ProvidersRepository; import bisq.core.user.Preferences; import bisq.core.user.User; import bisq.network.p2p.NodeAddress; import bisq.network.p2p.P2PService; import bisq.network.p2p.P2PServiceListener; import bisq.network.p2p.storage.HashMapChangedListener; import bisq.network.p2p.storage.payload.ProtectedStorageEntry; import bisq.common.app.DevEnv; import bisq.common.app.Version; import bisq.common.config.Config; import bisq.common.config.ConfigFileEditor; import bisq.common.crypto.KeyRing; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.Sha256Hash; import javax.inject.Inject; import javax.inject.Named; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import org.bouncycastle.util.encoders.Base64; import java.security.PublicKey; import java.nio.charset.StandardCharsets; import java.math.BigInteger; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Consumer; import java.lang.reflect.Method; import lombok.extern.slf4j.Slf4j; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkNotNull; import static org.bitcoinj.core.Utils.HEX; /** * We only support one active filter, if we receive multiple we use the one with the more recent creationDate. */ @Slf4j public class FilterManager { private static final String BANNED_PRICE_RELAY_NODES = "bannedPriceRelayNodes"; private static final String BANNED_SEED_NODES = "bannedSeedNodes"; private static final String BANNED_BTC_NODES = "bannedBtcNodes"; /////////////////////////////////////////////////////////////////////////////////////////// // Listener /////////////////////////////////////////////////////////////////////////////////////////// public interface Listener { void onFilterAdded(Filter filter); } private final P2PService p2PService; private final KeyRing keyRing; private final User user; private final Preferences preferences; private final ConfigFileEditor configFileEditor; private final ProvidersRepository providersRepository; private final boolean ignoreDevMsg; private final ObjectProperty<Filter> filterProperty = new SimpleObjectProperty<>(); private final List<Listener> listeners = new CopyOnWriteArrayList<>(); private final List<String> publicKeys; private ECKey filterSigningKey; private final Set<Filter> invalidFilters = new HashSet<>(); /////////////////////////////////////////////////////////////////////////////////////////// // Constructor /////////////////////////////////////////////////////////////////////////////////////////// @Inject public FilterManager(P2PService p2PService, KeyRing keyRing, User user, Preferences preferences, Config config, ProvidersRepository providersRepository, @Named(Config.IGNORE_DEV_MSG) boolean ignoreDevMsg, @Named(Config.USE_DEV_PRIVILEGE_KEYS) boolean useDevPrivilegeKeys) { this.p2PService = p2PService; this.keyRing = keyRing; this.user = user; this.preferences = preferences; this.configFileEditor = new ConfigFileEditor(config.configFile); this.providersRepository = providersRepository; this.ignoreDevMsg = ignoreDevMsg; publicKeys = useDevPrivilegeKeys ? Collections.singletonList(DevEnv.DEV_PRIVILEGE_PUB_KEY) : List.of("0358d47858acdc41910325fce266571540681ef83a0d6fedce312bef9810793a27", "029340c3e7d4bb0f9e651b5f590b434fecb6175aeaa57145c7804ff05d210e534f", "034dc7530bf66ffd9580aa98031ea9a18ac2d269f7c56c0e71eca06105b9ed69f9"); } /////////////////////////////////////////////////////////////////////////////////////////// // API /////////////////////////////////////////////////////////////////////////////////////////// public void onAllServicesInitialized() { if (ignoreDevMsg) { return; } p2PService.getP2PDataStorage().getMap().values().stream() .map(ProtectedStorageEntry::getProtectedStoragePayload) .filter(protectedStoragePayload -> protectedStoragePayload instanceof Filter) .map(protectedStoragePayload -> (Filter) protectedStoragePayload) .forEach(this::onFilterAddedFromNetwork); p2PService.addHashSetChangedListener(new HashMapChangedListener() { @Override public void onAdded(Collection<ProtectedStorageEntry> protectedStorageEntries) { protectedStorageEntries.stream() .filter(protectedStorageEntry -> protectedStorageEntry.getProtectedStoragePayload() instanceof Filter) .forEach(protectedStorageEntry -> { Filter filter = (Filter) protectedStorageEntry.getProtectedStoragePayload(); onFilterAddedFromNetwork(filter); }); } @Override public void onRemoved(Collection<ProtectedStorageEntry> protectedStorageEntries) { protectedStorageEntries.stream() .filter(protectedStorageEntry -> protectedStorageEntry.getProtectedStoragePayload() instanceof Filter) .forEach(protectedStorageEntry -> { Filter filter = (Filter) protectedStorageEntry.getProtectedStoragePayload(); onFilterRemovedFromNetwork(filter); }); } }); p2PService.addP2PServiceListener(new P2PServiceListener() { @Override public void onDataReceived() { } @Override public void onNoSeedNodeAvailable() { } @Override public void onNoPeersAvailable() { } @Override public void onUpdatedDataReceived() { // We should have received all data at that point and if the filters were not set we // clean up the persisted banned nodes in the options file as it might be that we missed the filter // remove message if we have not been online. if (filterProperty.get() == null) { clearBannedNodes(); } } @Override public void onTorNodeReady() { } @Override public void onHiddenServicePublished() { } @Override public void onSetupFailed(Throwable throwable) { } @Override public void onRequestCustomBridges() { } }); } public void setFilterWarningHandler(Consumer<String> filterWarningHandler) { addListener(filter -> { if (filter != null && filterWarningHandler != null) { if (filter.getSeedNodes() != null && !filter.getSeedNodes().isEmpty()) { log.info("One of the seed nodes got banned. {}", filter.getSeedNodes()); // Let's keep that more silent. Might be used in case a node is unstable and we don't want to confuse users. // filterWarningHandler.accept(Res.get("popup.warning.nodeBanned", Res.get("popup.warning.seed"))); } if (filter.getPriceRelayNodes() != null && !filter.getPriceRelayNodes().isEmpty()) { log.info("One of the price relay nodes got banned. {}", filter.getPriceRelayNodes()); // Let's keep that more silent. Might be used in case a node is unstable and we don't want to confuse users. // filterWarningHandler.accept(Res.get("popup.warning.nodeBanned", Res.get("popup.warning.priceRelay"))); } if (requireUpdateToNewVersionForTrading()) { filterWarningHandler.accept(Res.get("popup.warning.mandatoryUpdate.trading")); } if (requireUpdateToNewVersionForDAO()) { filterWarningHandler.accept(Res.get("popup.warning.mandatoryUpdate.dao")); } if (filter.isDisableDao()) { filterWarningHandler.accept(Res.get("popup.warning.disable.dao")); } } }); } public boolean isPrivilegedDevPubKeyBanned(String pubKeyAsHex) { Filter filter = getFilter(); if (filter == null) { return false; } return filter.getBannedPrivilegedDevPubKeys().contains(pubKeyAsHex); } public boolean canAddDevFilter(String privKeyString) { if (privKeyString == null || privKeyString.isEmpty()) { return false; } if (!isValidDevPrivilegeKey(privKeyString)) { log.warn("Key in invalid"); return false; } ECKey ecKeyFromPrivate = toECKey(privKeyString); String pubKeyAsHex = getPubKeyAsHex(ecKeyFromPrivate); if (isPrivilegedDevPubKeyBanned(pubKeyAsHex)) { log.warn("Pub key is banned."); return false; } return true; } public String getSignerPubKeyAsHex(String privKeyString) { ECKey ecKey = toECKey(privKeyString); return getPubKeyAsHex(ecKey); } public void addDevFilter(Filter filterWithoutSig, String privKeyString) { setFilterSigningKey(privKeyString); String signatureAsBase64 = getSignature(filterWithoutSig); Filter filterWithSig = Filter.cloneWithSig(filterWithoutSig, signatureAsBase64); user.setDevelopersFilter(filterWithSig); p2PService.addProtectedStorageEntry(filterWithSig); // Cleanup potential old filters created in the past with same priv key invalidFilters.forEach(filter -> { removeInvalidFilters(filter, privKeyString); }); } public void addToInvalidFilters(Filter filter) { invalidFilters.add(filter); } public void removeInvalidFilters(Filter filter, String privKeyString) { log.info("Remove invalid filter {}", filter); setFilterSigningKey(privKeyString); String signatureAsBase64 = getSignature(Filter.cloneWithoutSig(filter)); Filter filterWithSig = Filter.cloneWithSig(filter, signatureAsBase64); boolean result = p2PService.removeData(filterWithSig); if (!result) { log.warn("Could not remove filter {}", filter); } } public boolean canRemoveDevFilter(String privKeyString) { if (privKeyString == null || privKeyString.isEmpty()) { return false; } Filter developersFilter = getDevFilter(); if (developersFilter == null) { log.warn("There is no persisted dev filter to be removed."); return false; } if (!isValidDevPrivilegeKey(privKeyString)) { log.warn("Key in invalid."); return false; } ECKey ecKeyFromPrivate = toECKey(privKeyString); String pubKeyAsHex = getPubKeyAsHex(ecKeyFromPrivate); if (!developersFilter.getSignerPubKeyAsHex().equals(pubKeyAsHex)) { log.warn("pubKeyAsHex derived from private key does not match filterSignerPubKey. " + "filterSignerPubKey={}, pubKeyAsHex derived from private key={}", developersFilter.getSignerPubKeyAsHex(), pubKeyAsHex); return false; } if (isPrivilegedDevPubKeyBanned(pubKeyAsHex)) { log.warn("Pub key is banned."); return false; } return true; } public void removeDevFilter(String privKeyString) { setFilterSigningKey(privKeyString); Filter filterWithSig = user.getDevelopersFilter(); if (filterWithSig == null) { // Should not happen as UI button is deactivated in that case return; } if (p2PService.removeData(filterWithSig)) { user.setDevelopersFilter(null); } else { log.warn("Removing dev filter from network failed"); } } public void addListener(Listener listener) { listeners.add(listener); } public ObjectProperty<Filter> filterProperty() { return filterProperty; } @Nullable public Filter getFilter() { return filterProperty.get(); } @Nullable public Filter getDevFilter() { return user.getDevelopersFilter(); } public PublicKey getOwnerPubKey() { return keyRing.getSignatureKeyPair().getPublic(); } public boolean isCurrencyBanned(String currencyCode) { return getFilter() != null && getFilter().getBannedCurrencies() != null && getFilter().getBannedCurrencies().stream() .anyMatch(e -> e.equals(currencyCode)); } public boolean isPaymentMethodBanned(PaymentMethod paymentMethod) { return getFilter() != null && getFilter().getBannedPaymentMethods() != null && getFilter().getBannedPaymentMethods().stream() .anyMatch(e -> e.equals(paymentMethod.getId())); } public boolean isOfferIdBanned(String offerId) { return getFilter() != null && getFilter().getBannedOfferIds().stream() .anyMatch(e -> e.equals(offerId)); } public boolean isNodeAddressBanned(NodeAddress nodeAddress) { return getFilter() != null && getFilter().getBannedNodeAddress().stream() .anyMatch(e -> e.equals(nodeAddress.getFullAddress())); } public boolean isAutoConfExplorerBanned(String address) { return getFilter() != null && getFilter().getBannedAutoConfExplorers().stream() .anyMatch(e -> e.equals(address)); } public boolean requireUpdateToNewVersionForTrading() { if (getFilter() == null) { return false; } boolean requireUpdateToNewVersion = false; String getDisableTradeBelowVersion = getFilter().getDisableTradeBelowVersion(); if (getDisableTradeBelowVersion != null && !getDisableTradeBelowVersion.isEmpty()) { requireUpdateToNewVersion = Version.isNewVersion(getDisableTradeBelowVersion); } return requireUpdateToNewVersion; } public boolean requireUpdateToNewVersionForDAO() { if (getFilter() == null) { return false; } boolean requireUpdateToNewVersion = false; String disableDaoBelowVersion = getFilter().getDisableDaoBelowVersion(); if (disableDaoBelowVersion != null && !disableDaoBelowVersion.isEmpty()) { requireUpdateToNewVersion = Version.isNewVersion(disableDaoBelowVersion); } return requireUpdateToNewVersion; } public boolean arePeersPaymentAccountDataBanned(PaymentAccountPayload paymentAccountPayload) { return getFilter() != null && getFilter().getBannedPaymentAccounts().stream() .filter(paymentAccountFilter -> paymentAccountFilter.getPaymentMethodId().equals( paymentAccountPayload.getPaymentMethodId())) .anyMatch(paymentAccountFilter -> { try { Method method = paymentAccountPayload.getClass().getMethod(paymentAccountFilter.getGetMethodName()); // We invoke getter methods (no args), e.g. getHolderName String valueFromInvoke = (String) method.invoke(paymentAccountPayload); return valueFromInvoke.equalsIgnoreCase(paymentAccountFilter.getValue()); } catch (Throwable e) { log.error(e.getMessage()); return false; } }); } public boolean isWitnessSignerPubKeyBanned(String witnessSignerPubKeyAsHex) { return getFilter() != null && getFilter().getBannedAccountWitnessSignerPubKeys() != null && getFilter().getBannedAccountWitnessSignerPubKeys().stream() .anyMatch(e -> e.equals(witnessSignerPubKeyAsHex)); } /////////////////////////////////////////////////////////////////////////////////////////// // Private /////////////////////////////////////////////////////////////////////////////////////////// private void onFilterAddedFromNetwork(Filter newFilter) { Filter currentFilter = getFilter(); if (!isFilterPublicKeyInList(newFilter)) { if (newFilter.getSignerPubKeyAsHex() != null && !newFilter.getSignerPubKeyAsHex().isEmpty()) { log.warn("isFilterPublicKeyInList failed. Filter.getSignerPubKeyAsHex={}", newFilter.getSignerPubKeyAsHex()); } else { log.info("isFilterPublicKeyInList failed. Filter.getSignerPubKeyAsHex not set (expected case for pre v1.3.9 filter)"); } return; } if (!isSignatureValid(newFilter)) { log.warn("verifySignature failed. Filter={}", newFilter); return; } if (currentFilter != null) { if (currentFilter.getCreationDate() > newFilter.getCreationDate()) { log.warn("We received a new filter from the network but the creation date is older than the " + "filter we have already. We ignore the new filter.\n" + "New filer={}\n" + "Old filter={}", newFilter, filterProperty.get()); addToInvalidFilters(newFilter); return; } else { log.warn("We received a new filter from the network and the creation date is newer than the " + "filter we have already. We ignore the old filter.\n" + "New filer={}\n" + "Old filter={}", newFilter, filterProperty.get()); addToInvalidFilters(currentFilter); } if (isPrivilegedDevPubKeyBanned(newFilter.getSignerPubKeyAsHex())) { log.warn("Pub key of filter is banned. currentFilter={}, newFilter={}", currentFilter, newFilter); return; } } // Our new filter is newer so we apply it. // We do not require strict guarantees here (e.g. clocks not synced) as only trusted developers have the key // for deploying filters and this is only in place to avoid unintended situations of multiple filters // from multiple devs or if same dev publishes new filter from different app without the persisted devFilter. filterProperty.set(newFilter); // Seed nodes are requested at startup before we get the filter so we only apply the banned // nodes at the next startup and don't update the list in the P2P network domain. // We persist it to the property file which is read before any other initialisation. saveBannedNodes(BANNED_SEED_NODES, newFilter.getSeedNodes()); saveBannedNodes(BANNED_BTC_NODES, newFilter.getBtcNodes()); // Banned price relay nodes we can apply at runtime List<String> priceRelayNodes = newFilter.getPriceRelayNodes(); saveBannedNodes(BANNED_PRICE_RELAY_NODES, priceRelayNodes); //TODO should be moved to client with listening on onFilterAdded providersRepository.applyBannedNodes(priceRelayNodes); //TODO should be moved to client with listening on onFilterAdded if (newFilter.isPreventPublicBtcNetwork() && preferences.getBitcoinNodesOptionOrdinal() == BtcNodes.BitcoinNodesOption.PUBLIC.ordinal()) { preferences.setBitcoinNodesOptionOrdinal(BtcNodes.BitcoinNodesOption.PROVIDED.ordinal()); } listeners.forEach(e -> e.onFilterAdded(newFilter)); } private void onFilterRemovedFromNetwork(Filter filter) { if (!isFilterPublicKeyInList(filter)) { log.warn("isFilterPublicKeyInList failed. Filter={}", filter); return; } if (!isSignatureValid(filter)) { log.warn("verifySignature failed. Filter={}", filter); return; } // We don't check for banned filter as we want to remove a banned filter anyway. if (!filterProperty.get().equals(filter)) { return; } clearBannedNodes(); if (filter.equals(user.getDevelopersFilter())) { user.setDevelopersFilter(null); } filterProperty.set(null); } // Clears options files from banned nodes private void clearBannedNodes() { saveBannedNodes(BANNED_BTC_NODES, null); saveBannedNodes(BANNED_SEED_NODES, null); saveBannedNodes(BANNED_PRICE_RELAY_NODES, null); if (providersRepository.getBannedNodes() != null) { providersRepository.applyBannedNodes(null); } } private void saveBannedNodes(String optionName, List<String> bannedNodes) { if (bannedNodes != null) configFileEditor.setOption(optionName, String.join(",", bannedNodes)); else configFileEditor.clearOption(optionName); } private boolean isValidDevPrivilegeKey(String privKeyString) { try { ECKey filterSigningKey = toECKey(privKeyString); String pubKeyAsHex = getPubKeyAsHex(filterSigningKey); return isPublicKeyInList(pubKeyAsHex); } catch (Throwable t) { return false; } } private void setFilterSigningKey(String privKeyString) { this.filterSigningKey = toECKey(privKeyString); } private String getSignature(Filter filterWithoutSig) { Sha256Hash hash = getSha256Hash(filterWithoutSig); ECKey.ECDSASignature ecdsaSignature = filterSigningKey.sign(hash); byte[] encodeToDER = ecdsaSignature.encodeToDER(); return new String(Base64.encode(encodeToDER), StandardCharsets.UTF_8); } private boolean isFilterPublicKeyInList(Filter filter) { String signerPubKeyAsHex = filter.getSignerPubKeyAsHex(); if (!isPublicKeyInList(signerPubKeyAsHex)) { log.info("Invalid filter (expected case for pre v1.3.9 filter as we still keep that in the network " + "but the new version does not recognize it as valid filter): " + "signerPubKeyAsHex from filter is not part of our pub key list. " + "signerPubKeyAsHex={}, publicKeys={}, filterCreationDate={}", signerPubKeyAsHex, publicKeys, new Date(filter.getCreationDate())); return false; } return true; } private boolean isPublicKeyInList(String pubKeyAsHex) { boolean isPublicKeyInList = publicKeys.contains(pubKeyAsHex); if (!isPublicKeyInList) { log.info("pubKeyAsHex is not part of our pub key list (expected case for pre v1.3.9 filter). pubKeyAsHex={}, publicKeys={}", pubKeyAsHex, publicKeys); } return isPublicKeyInList; } private boolean isSignatureValid(Filter filter) { try { Filter filterForSigVerification = Filter.cloneWithoutSig(filter); Sha256Hash hash = getSha256Hash(filterForSigVerification); checkNotNull(filter.getSignatureAsBase64(), "filter.getSignatureAsBase64() must not be null"); byte[] sigData = Base64.decode(filter.getSignatureAsBase64()); ECKey.ECDSASignature ecdsaSignature = ECKey.ECDSASignature.decodeFromDER(sigData); String signerPubKeyAsHex = filter.getSignerPubKeyAsHex(); byte[] decode = HEX.decode(signerPubKeyAsHex); ECKey ecPubKey = ECKey.fromPublicOnly(decode); return ecPubKey.verify(hash, ecdsaSignature); } catch (Throwable e) { log.warn("verifySignature failed. filter={}", filter); return false; } } private ECKey toECKey(String privKeyString) { return ECKey.fromPrivate(new BigInteger(1, HEX.decode(privKeyString))); } private Sha256Hash getSha256Hash(Filter filter) { byte[] filterData = filter.toProtoMessage().toByteArray(); return Sha256Hash.of(filterData); } private String getPubKeyAsHex(ECKey ecKey) { return HEX.encode(ecKey.getPubKey()); } }
core/src/main/java/bisq/core/filter/FilterManager.java
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.core.filter; import bisq.core.btc.nodes.BtcNodes; import bisq.core.locale.Res; import bisq.core.payment.payload.PaymentAccountPayload; import bisq.core.payment.payload.PaymentMethod; import bisq.core.provider.ProvidersRepository; import bisq.core.user.Preferences; import bisq.core.user.User; import bisq.network.p2p.NodeAddress; import bisq.network.p2p.P2PService; import bisq.network.p2p.P2PServiceListener; import bisq.network.p2p.storage.HashMapChangedListener; import bisq.network.p2p.storage.payload.ProtectedStorageEntry; import bisq.common.app.DevEnv; import bisq.common.app.Version; import bisq.common.config.Config; import bisq.common.config.ConfigFileEditor; import bisq.common.crypto.KeyRing; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.Sha256Hash; import javax.inject.Inject; import javax.inject.Named; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import org.bouncycastle.util.encoders.Base64; import java.security.PublicKey; import java.nio.charset.StandardCharsets; import java.math.BigInteger; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Consumer; import java.lang.reflect.Method; import lombok.extern.slf4j.Slf4j; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkNotNull; import static org.bitcoinj.core.Utils.HEX; /** * We only support one active filter, if we receive multiple we use the one with the more recent creationDate. */ @Slf4j public class FilterManager { private static final String BANNED_PRICE_RELAY_NODES = "bannedPriceRelayNodes"; private static final String BANNED_SEED_NODES = "bannedSeedNodes"; private static final String BANNED_BTC_NODES = "bannedBtcNodes"; /////////////////////////////////////////////////////////////////////////////////////////// // Listener /////////////////////////////////////////////////////////////////////////////////////////// public interface Listener { void onFilterAdded(Filter filter); } private final P2PService p2PService; private final KeyRing keyRing; private final User user; private final Preferences preferences; private final ConfigFileEditor configFileEditor; private final ProvidersRepository providersRepository; private final boolean ignoreDevMsg; private final ObjectProperty<Filter> filterProperty = new SimpleObjectProperty<>(); private final List<Listener> listeners = new CopyOnWriteArrayList<>(); private final List<String> publicKeys; private ECKey filterSigningKey; private final Set<Filter> invalidFilters = new HashSet<>(); /////////////////////////////////////////////////////////////////////////////////////////// // Constructor /////////////////////////////////////////////////////////////////////////////////////////// @Inject public FilterManager(P2PService p2PService, KeyRing keyRing, User user, Preferences preferences, Config config, ProvidersRepository providersRepository, @Named(Config.IGNORE_DEV_MSG) boolean ignoreDevMsg, @Named(Config.USE_DEV_PRIVILEGE_KEYS) boolean useDevPrivilegeKeys) { this.p2PService = p2PService; this.keyRing = keyRing; this.user = user; this.preferences = preferences; this.configFileEditor = new ConfigFileEditor(config.configFile); this.providersRepository = providersRepository; this.ignoreDevMsg = ignoreDevMsg; publicKeys = useDevPrivilegeKeys ? Collections.singletonList(DevEnv.DEV_PRIVILEGE_PUB_KEY) : List.of("0358d47858acdc41910325fce266571540681ef83a0d6fedce312bef9810793a27", "029340c3e7d4bb0f9e651b5f590b434fecb6175aeaa57145c7804ff05d210e534f", "034dc7530bf66ffd9580aa98031ea9a18ac2d269f7c56c0e71eca06105b9ed69f9"); } /////////////////////////////////////////////////////////////////////////////////////////// // API /////////////////////////////////////////////////////////////////////////////////////////// public void onAllServicesInitialized() { if (ignoreDevMsg) { return; } p2PService.getP2PDataStorage().getMap().values().stream() .map(ProtectedStorageEntry::getProtectedStoragePayload) .filter(protectedStoragePayload -> protectedStoragePayload instanceof Filter) .map(protectedStoragePayload -> (Filter) protectedStoragePayload) .forEach(this::onFilterAddedFromNetwork); p2PService.addHashSetChangedListener(new HashMapChangedListener() { @Override public void onAdded(Collection<ProtectedStorageEntry> protectedStorageEntries) { protectedStorageEntries.stream() .filter(protectedStorageEntry -> protectedStorageEntry.getProtectedStoragePayload() instanceof Filter) .forEach(protectedStorageEntry -> { Filter filter = (Filter) protectedStorageEntry.getProtectedStoragePayload(); onFilterAddedFromNetwork(filter); }); } @Override public void onRemoved(Collection<ProtectedStorageEntry> protectedStorageEntries) { protectedStorageEntries.stream() .filter(protectedStorageEntry -> protectedStorageEntry.getProtectedStoragePayload() instanceof Filter) .forEach(protectedStorageEntry -> { Filter filter = (Filter) protectedStorageEntry.getProtectedStoragePayload(); onFilterRemovedFromNetwork(filter); }); } }); p2PService.addP2PServiceListener(new P2PServiceListener() { @Override public void onDataReceived() { } @Override public void onNoSeedNodeAvailable() { } @Override public void onNoPeersAvailable() { } @Override public void onUpdatedDataReceived() { // We should have received all data at that point and if the filters were not set we // clean up the persisted banned nodes in the options file as it might be that we missed the filter // remove message if we have not been online. if (filterProperty.get() == null) { clearBannedNodes(); } } @Override public void onTorNodeReady() { } @Override public void onHiddenServicePublished() { } @Override public void onSetupFailed(Throwable throwable) { } @Override public void onRequestCustomBridges() { } }); } public void setFilterWarningHandler(Consumer<String> filterWarningHandler) { addListener(filter -> { if (filter != null && filterWarningHandler != null) { if (filter.getSeedNodes() != null && !filter.getSeedNodes().isEmpty()) { log.info("One of the seed nodes got banned. {}", filter.getSeedNodes()); // Let's keep that more silent. Might be used in case a node is unstable and we don't want to confuse users. // filterWarningHandler.accept(Res.get("popup.warning.nodeBanned", Res.get("popup.warning.seed"))); } if (filter.getPriceRelayNodes() != null && !filter.getPriceRelayNodes().isEmpty()) { log.info("One of the price relay nodes got banned. {}", filter.getPriceRelayNodes()); // Let's keep that more silent. Might be used in case a node is unstable and we don't want to confuse users. // filterWarningHandler.accept(Res.get("popup.warning.nodeBanned", Res.get("popup.warning.priceRelay"))); } if (requireUpdateToNewVersionForTrading()) { filterWarningHandler.accept(Res.get("popup.warning.mandatoryUpdate.trading")); } if (requireUpdateToNewVersionForDAO()) { filterWarningHandler.accept(Res.get("popup.warning.mandatoryUpdate.dao")); } if (filter.isDisableDao()) { filterWarningHandler.accept(Res.get("popup.warning.disable.dao")); } } }); } public boolean isPrivilegedDevPubKeyBanned(String pubKeyAsHex) { Filter filter = getFilter(); if (filter == null) { return false; } return filter.getBannedPrivilegedDevPubKeys().contains(pubKeyAsHex); } public boolean canAddDevFilter(String privKeyString) { if (privKeyString == null || privKeyString.isEmpty()) { return false; } if (!isValidDevPrivilegeKey(privKeyString)) { log.warn("Key in invalid"); return false; } ECKey ecKeyFromPrivate = toECKey(privKeyString); String pubKeyAsHex = getPubKeyAsHex(ecKeyFromPrivate); if (isPrivilegedDevPubKeyBanned(pubKeyAsHex)) { log.warn("Pub key is banned."); return false; } return true; } public String getSignerPubKeyAsHex(String privKeyString) { ECKey ecKey = toECKey(privKeyString); return getPubKeyAsHex(ecKey); } public void addDevFilter(Filter filterWithoutSig, String privKeyString) { setFilterSigningKey(privKeyString); String signatureAsBase64 = getSignature(filterWithoutSig); Filter filterWithSig = Filter.cloneWithSig(filterWithoutSig, signatureAsBase64); user.setDevelopersFilter(filterWithSig); p2PService.addProtectedStorageEntry(filterWithSig); // Cleanup potential old filters created in the past with same priv key invalidFilters.forEach(filter -> { removeInvalidFilters(filter, privKeyString); }); } public void addToInvalidFilters(Filter filter) { invalidFilters.add(filter); } public void removeInvalidFilters(Filter filter, String privKeyString) { log.info("Remove invalid filter {}", filter); setFilterSigningKey(privKeyString); String signatureAsBase64 = getSignature(Filter.cloneWithoutSig(filter)); Filter filterWithSig = Filter.cloneWithSig(filter, signatureAsBase64); boolean result = p2PService.removeData(filterWithSig); if (!result) { log.warn("Could not remove filter {}", filter); } } public boolean canRemoveDevFilter(String privKeyString) { if (privKeyString == null || privKeyString.isEmpty()) { return false; } Filter developersFilter = getDevFilter(); if (developersFilter == null) { log.warn("There is no persisted dev filter to be removed."); return false; } if (!isValidDevPrivilegeKey(privKeyString)) { log.warn("Key in invalid."); return false; } ECKey ecKeyFromPrivate = toECKey(privKeyString); String pubKeyAsHex = getPubKeyAsHex(ecKeyFromPrivate); if (!developersFilter.getSignerPubKeyAsHex().equals(pubKeyAsHex)) { log.warn("pubKeyAsHex derived from private key does not match filterSignerPubKey. " + "filterSignerPubKey={}, pubKeyAsHex derived from private key={}", developersFilter.getSignerPubKeyAsHex(), pubKeyAsHex); return false; } if (isPrivilegedDevPubKeyBanned(pubKeyAsHex)) { log.warn("Pub key is banned."); return false; } return true; } public void removeDevFilter(String privKeyString) { setFilterSigningKey(privKeyString); Filter filterWithSig = user.getDevelopersFilter(); if (filterWithSig == null) { // Should not happen as UI button is deactivated in that case return; } if (p2PService.removeData(filterWithSig)) { user.setDevelopersFilter(null); } else { log.warn("Removing dev filter from network failed"); } } public void addListener(Listener listener) { listeners.add(listener); } public ObjectProperty<Filter> filterProperty() { return filterProperty; } @Nullable public Filter getFilter() { return filterProperty.get(); } @Nullable public Filter getDevFilter() { return user.getDevelopersFilter(); } public PublicKey getOwnerPubKey() { return keyRing.getSignatureKeyPair().getPublic(); } public boolean isCurrencyBanned(String currencyCode) { return getFilter() != null && getFilter().getBannedCurrencies() != null && getFilter().getBannedCurrencies().stream() .anyMatch(e -> e.equals(currencyCode)); } public boolean isPaymentMethodBanned(PaymentMethod paymentMethod) { return getFilter() != null && getFilter().getBannedPaymentMethods() != null && getFilter().getBannedPaymentMethods().stream() .anyMatch(e -> e.equals(paymentMethod.getId())); } public boolean isOfferIdBanned(String offerId) { return getFilter() != null && getFilter().getBannedOfferIds().stream() .anyMatch(e -> e.equals(offerId)); } public boolean isNodeAddressBanned(NodeAddress nodeAddress) { return getFilter() != null && getFilter().getBannedNodeAddress().stream() .anyMatch(e -> e.equals(nodeAddress.getFullAddress())); } public boolean isAutoConfExplorerBanned(String address) { return getFilter() != null && getFilter().getBannedAutoConfExplorers().stream() .anyMatch(e -> e.equals(address)); } public boolean requireUpdateToNewVersionForTrading() { if (getFilter() == null) { return false; } boolean requireUpdateToNewVersion = false; String getDisableTradeBelowVersion = getFilter().getDisableTradeBelowVersion(); if (getDisableTradeBelowVersion != null && !getDisableTradeBelowVersion.isEmpty()) { requireUpdateToNewVersion = Version.isNewVersion(getDisableTradeBelowVersion); } return requireUpdateToNewVersion; } public boolean requireUpdateToNewVersionForDAO() { if (getFilter() == null) { return false; } boolean requireUpdateToNewVersion = false; String disableDaoBelowVersion = getFilter().getDisableDaoBelowVersion(); if (disableDaoBelowVersion != null && !disableDaoBelowVersion.isEmpty()) { requireUpdateToNewVersion = Version.isNewVersion(disableDaoBelowVersion); } return requireUpdateToNewVersion; } public boolean arePeersPaymentAccountDataBanned(PaymentAccountPayload paymentAccountPayload) { return getFilter() != null && getFilter().getBannedPaymentAccounts().stream() .filter(paymentAccountFilter -> paymentAccountFilter.getPaymentMethodId().equals( paymentAccountPayload.getPaymentMethodId())) .anyMatch(paymentAccountFilter -> { try { Method method = paymentAccountPayload.getClass().getMethod(paymentAccountFilter.getGetMethodName()); // We invoke getter methods (no args), e.g. getHolderName String valueFromInvoke = (String) method.invoke(paymentAccountPayload); return valueFromInvoke.equalsIgnoreCase(paymentAccountFilter.getValue()); } catch (Throwable e) { log.error(e.getMessage()); return false; } }); } public boolean isWitnessSignerPubKeyBanned(String witnessSignerPubKeyAsHex) { return getFilter() != null && getFilter().getBannedAccountWitnessSignerPubKeys() != null && getFilter().getBannedAccountWitnessSignerPubKeys().stream() .anyMatch(e -> e.equals(witnessSignerPubKeyAsHex)); } /////////////////////////////////////////////////////////////////////////////////////////// // Private /////////////////////////////////////////////////////////////////////////////////////////// private void onFilterAddedFromNetwork(Filter newFilter) { Filter currentFilter = getFilter(); if (!isFilterPublicKeyInList(newFilter)) { if (newFilter.getSignerPubKeyAsHex() != null && !newFilter.getSignerPubKeyAsHex().isEmpty()) { log.warn("isFilterPublicKeyInList failed. Filter.getSignerPubKeyAsHex={}", newFilter.getSignerPubKeyAsHex()); } else { log.info("isFilterPublicKeyInList failed. Filter.getSignerPubKeyAsHex not set (expected case for pre v1.3.9 filter)"); } return; } if (!isSignatureValid(newFilter)) { log.warn("verifySignature failed. Filter={}", newFilter); return; } if (currentFilter != null) { if (currentFilter.getCreationDate() > newFilter.getCreationDate()) { log.warn("We received a new filter from the network but the creation date is older than the " + "filter we have already. We ignore the new filter.\n" + "New filer={}\n" + "Old filter={}", newFilter, filterProperty.get()); addToInvalidFilters(newFilter); return; } else { log.warn("We received a new filter from the network and the creation date is newer than the " + "filter we have already. We ignore the old filter.\n" + "New filer={}\n" + "Old filter={}", newFilter, filterProperty.get()); addToInvalidFilters(currentFilter); } if (isPrivilegedDevPubKeyBanned(newFilter.getSignerPubKeyAsHex())) { log.warn("Pub key of filter is banned. currentFilter={}, newFilter={}", currentFilter, newFilter); return; } } // Our new filter is newer so we apply it. // We do not require strict guarantees here (e.g. clocks not synced) as only trusted developers have the key // for deploying filters and this is only in place to avoid unintended situations of multiple filters // from multiple devs or if same dev publishes new filter from different app without the persisted devFilter. filterProperty.set(newFilter); // Seed nodes are requested at startup before we get the filter so we only apply the banned // nodes at the next startup and don't update the list in the P2P network domain. // We persist it to the property file which is read before any other initialisation. saveBannedNodes(BANNED_SEED_NODES, newFilter.getSeedNodes()); saveBannedNodes(BANNED_BTC_NODES, newFilter.getBtcNodes()); // Banned price relay nodes we can apply at runtime List<String> priceRelayNodes = newFilter.getPriceRelayNodes(); saveBannedNodes(BANNED_PRICE_RELAY_NODES, priceRelayNodes); //TODO should be moved to client with listening on onFilterAdded providersRepository.applyBannedNodes(priceRelayNodes); //TODO should be moved to client with listening on onFilterAdded if (newFilter.isPreventPublicBtcNetwork() && preferences.getBitcoinNodesOptionOrdinal() == BtcNodes.BitcoinNodesOption.PUBLIC.ordinal()) { preferences.setBitcoinNodesOptionOrdinal(BtcNodes.BitcoinNodesOption.PROVIDED.ordinal()); } listeners.forEach(e -> e.onFilterAdded(newFilter)); } private void onFilterRemovedFromNetwork(Filter filter) { if (!isFilterPublicKeyInList(filter)) { log.warn("isFilterPublicKeyInList failed. Filter={}", filter); return; } if (!isSignatureValid(filter)) { log.warn("verifySignature failed. Filter={}", filter); return; } // We don't check for banned filter as we want to remove a banned filter anyway. if (!filterProperty.get().equals(filter)) { return; } clearBannedNodes(); if (filter.equals(user.getDevelopersFilter())) { user.setDevelopersFilter(null); } filterProperty.set(null); } // Clears options files from banned nodes private void clearBannedNodes() { saveBannedNodes(BANNED_BTC_NODES, null); saveBannedNodes(BANNED_SEED_NODES, null); saveBannedNodes(BANNED_PRICE_RELAY_NODES, null); if (providersRepository.getBannedNodes() != null) { providersRepository.applyBannedNodes(null); } } private void saveBannedNodes(String optionName, List<String> bannedNodes) { if (bannedNodes != null) configFileEditor.setOption(optionName, String.join(",", bannedNodes)); else configFileEditor.clearOption(optionName); } private boolean isValidDevPrivilegeKey(String privKeyString) { try { ECKey filterSigningKey = toECKey(privKeyString); String pubKeyAsHex = getPubKeyAsHex(filterSigningKey); return isPublicKeyInList(pubKeyAsHex); } catch (Throwable t) { return false; } } private void setFilterSigningKey(String privKeyString) { this.filterSigningKey = toECKey(privKeyString); } private String getSignature(Filter filterWithoutSig) { Sha256Hash hash = getSha256Hash(filterWithoutSig); ECKey.ECDSASignature ecdsaSignature = filterSigningKey.sign(hash); byte[] encodeToDER = ecdsaSignature.encodeToDER(); return new String(Base64.encode(encodeToDER), StandardCharsets.UTF_8); } private boolean isFilterPublicKeyInList(Filter filter) { String signerPubKeyAsHex = filter.getSignerPubKeyAsHex(); if (!isPublicKeyInList(signerPubKeyAsHex)) { log.warn("Invalid filter (expected case for pre v1.3.9 filter as we still keep that in the network " + "but the new version does not recognize it as valid filter): " + "signerPubKeyAsHex from filter is not part of our pub key list. " + "signerPubKeyAsHex={}, publicKeys={}, filterCreationDate={}", signerPubKeyAsHex, publicKeys, new Date(filter.getCreationDate())); return false; } return true; } private boolean isPublicKeyInList(String pubKeyAsHex) { boolean isPublicKeyInList = publicKeys.contains(pubKeyAsHex); if (!isPublicKeyInList) { log.warn("pubKeyAsHex is not part of our pub key list. pubKeyAsHex={}, publicKeys={}", pubKeyAsHex, publicKeys); } return isPublicKeyInList; } private boolean isSignatureValid(Filter filter) { try { Filter filterForSigVerification = Filter.cloneWithoutSig(filter); Sha256Hash hash = getSha256Hash(filterForSigVerification); checkNotNull(filter.getSignatureAsBase64(), "filter.getSignatureAsBase64() must not be null"); byte[] sigData = Base64.decode(filter.getSignatureAsBase64()); ECKey.ECDSASignature ecdsaSignature = ECKey.ECDSASignature.decodeFromDER(sigData); String signerPubKeyAsHex = filter.getSignerPubKeyAsHex(); byte[] decode = HEX.decode(signerPubKeyAsHex); ECKey ecPubKey = ECKey.fromPublicOnly(decode); return ecPubKey.verify(hash, ecdsaSignature); } catch (Throwable e) { log.warn("verifySignature failed. filter={}", filter); return false; } } private ECKey toECKey(String privKeyString) { return ECKey.fromPrivate(new BigInteger(1, HEX.decode(privKeyString))); } private Sha256Hash getSha256Hash(Filter filter) { byte[] filterData = filter.toProtoMessage().toByteArray(); return Sha256Hash.of(filterData); } private String getPubKeyAsHex(ECKey ecKey) { return HEX.encode(ecKey.getPubKey()); } }
Change warnings of banned filter to info level
core/src/main/java/bisq/core/filter/FilterManager.java
Change warnings of banned filter to info level
Java
lgpl-2.1
1d82dd252c73ef9fafc51ccca57f0c8ecb9a1fe3
0
OPENDAP/olfs,OPENDAP/olfs,OPENDAP/olfs,OPENDAP/olfs,OPENDAP/olfs,OPENDAP/olfs
package opendap.semantics.IRISail; import opendap.wcs.v1_1_2.*; import org.jdom.Element; import org.jdom.filter.ElementFilter; import org.jdom.output.XMLOutputter; import org.jdom.output.Format; import org.slf4j.Logger; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.ConcurrentHashMap; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import org.openrdf.model.Resource; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.model.impl.URIImpl; import org.openrdf.query.BindingSet; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.QueryLanguage; import org.openrdf.query.TupleQuery; import org.openrdf.query.TupleQueryResult; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.RepositoryResult; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFParseException; import org.openrdf.rio.ntriples.NTriplesWriter; import com.ontotext.trree.owlim_ext.SailImpl; /** * A colon of LocalFileCatalog */ public class StaticRDFCatalog implements WcsCatalog, Runnable { private Logger log; // = LoggerFactory.getLogger(StaticRDFCatalog.class); private AtomicBoolean repositoryUpdateActive; private ReentrantReadWriteLock _repositoryLock; private IRISailRepository owlse2; private XMLfromRDF buildDoc; //private static boolean _useMemoryCache; //private Date _cacheTime; private long _lastModified; private ConcurrentHashMap<String, CoverageDescription> coverages; private ReentrantReadWriteLock _catalogLock; private Thread catalogUpdateThread; private long firstUpdateDelay; private long catalogUpdateInterval; private long timeOfLastUpdate; private boolean stopWorking = false; private Element _config; private String catalogCacheDirectory; private String owlim_storage_folder; private String resourcePath; private boolean backgroundUpdates; private HashMap<String, Vector<String> > coverageIDServer; private ConcurrentHashMap<String, String> serviceIDs = new ConcurrentHashMap<String,String>(); private ConcurrentHashMap<String, String> wcsIDs = new ConcurrentHashMap<String,String>(); private boolean initialized; public StaticRDFCatalog() { log = org.slf4j.LoggerFactory.getLogger(this.getClass()); catalogUpdateInterval = 20 * 60 * 1000; // 20 minutes worth of milliseconds firstUpdateDelay = 5 * 1000; // 5 second worth of milliseconds timeOfLastUpdate = 0; stopWorking = false; _catalogLock = new ReentrantReadWriteLock(); coverages = new ConcurrentHashMap<String, CoverageDescription>(); _repositoryLock = new ReentrantReadWriteLock(); repositoryUpdateActive = new AtomicBoolean(); repositoryUpdateActive.set(false); backgroundUpdates = false; owlse2 = null; buildDoc = null; _lastModified = -1; _config = null; catalogCacheDirectory = null; owlim_storage_folder ="owlim-storage"; resourcePath = null; initialized = false; } public static void main(String[] args) { long startTime, endTime; double elapsedTime; StaticRDFCatalog catalog = new StaticRDFCatalog(); try { Map<String,String> env = System.getenv(); catalog.resourcePath = "."; catalog.catalogCacheDirectory = "."; String configFileName; configFileName = "file:///data/haibo/workspace/ioos/wcs_service.xml"; if(args.length>0) configFileName = args[0]; catalog.log.debug("main() using config file: "+configFileName); Element olfsConfig = opendap.xml.Util.getDocumentRoot(configFileName); catalog._config = (Element)olfsConfig.getDescendants(new ElementFilter("WcsCatalog")).next(); catalog.processConfig(catalog._config, catalog.catalogCacheDirectory, catalog.resourcePath); boolean done = false; catalog.setupRepository(); catalog.extractCoverageDescrptionsFromRepository(); catalog.updateCatalogCache(); catalog.shutdownRepository(); for(int i=0; i<1 ;i++){ startTime = new Date().getTime(); //catalog.setupRepository(); catalog.updateCatalog(); //catalog.destroy(); endTime = new Date().getTime(); elapsedTime = (endTime - startTime)/1000.0; catalog.log.debug("Completed catalog update in "+elapsedTime+ " seconds."); catalog.log.debug("########################################################################################"); catalog.log.debug("########################################################################################"); catalog.log.debug("########################################################################################"); catalog.setStopFlag(false); Thread.sleep(5000); } } catch (Exception e) { e.printStackTrace(); } finally { catalog.destroy(); } } public void init(Element config, String defaultCacheDirectory, String defaultResourcePath) throws Exception { if (initialized) return; backgroundUpdates = false; _config = config; processConfig(_config,defaultCacheDirectory, defaultResourcePath ); setupRepository(); extractCoverageDescrptionsFromRepository(); updateCatalogCache(); shutdownRepository(); if (backgroundUpdates) { catalogUpdateThread = new Thread(this); catalogUpdateThread.start(); } else { updateCatalog(); } initialized = true; } private void processConfig(Element config,String defaultCacheDirectory, String defaultResourcePath){ Element e; File file; /** ######################################################## * Process configuration. */ catalogCacheDirectory = defaultCacheDirectory; e = config.getChild("CacheDirectory"); if (e != null) catalogCacheDirectory = e.getTextTrim(); if (catalogCacheDirectory != null && catalogCacheDirectory.length() > 0 && !catalogCacheDirectory.endsWith("/")) catalogCacheDirectory += "/"; file = new File(catalogCacheDirectory); if (!file.exists()) { if (!file.mkdirs()) { log.error("Unable to create cache directory: " + catalogCacheDirectory); if(!catalogCacheDirectory.equals(defaultCacheDirectory)){ file = new File(defaultCacheDirectory); if (!file.exists()) { if (!file.mkdirs()) { log.error("Unable to create cache directory: " + defaultCacheDirectory); log.error("Process probably doomed..."); } } } else { log.error("Process probably doomed..."); } } } log.info("Using catalogCacheDirectory: "+ catalogCacheDirectory); resourcePath = defaultResourcePath; e = config.getChild("ResourcePath"); if (e != null) resourcePath = e.getTextTrim(); if (resourcePath != null && resourcePath.length() > 0 && !resourcePath.endsWith("/")) resourcePath += "/"; file = new File(this.resourcePath); if (!file.exists()) { log.error("Unable to locate resource directory: " + resourcePath); file = new File(defaultResourcePath); if (!file.exists()) { log.error("Unable to locate default resource directory: " + defaultResourcePath); log.error("Process probably doomed..."); } } log.info("Using resourcePath: "+resourcePath); e = config.getChild("useUpdateCatalogThread"); if(e != null){ backgroundUpdates = true; String s = e.getAttributeValue("updateInterval"); if (s != null){ catalogUpdateInterval = Long.parseLong(s) * 1000; } s = e.getAttributeValue("firstUpdateDelay"); if (s != null){ firstUpdateDelay = Long.parseLong(s) * 1000; } } log.info("backgroundUpdates: "+backgroundUpdates); log.info("Catalog update interval: "+catalogUpdateInterval+"ms"); log.info("First update delay: "+firstUpdateDelay+"ms"); } private void shutdownRepository() throws RepositoryException, InterruptedException { log.debug("Shutting down Repository..."); owlse2.shutDown(); log.debug("Repository shutdown complete."); } private void setupRepository() throws RepositoryException, InterruptedException { log.info("Setting up Semantic Repository."); //OWLIM Sail Repository (inferencing makes this somewhat slow) SailImpl owlimSail = new com.ontotext.trree.owlim_ext.SailImpl(); owlse2 = new IRISailRepository(owlimSail, resourcePath, catalogCacheDirectory); //owlim inferencing //owlse2 = new IRISailRepository(new MemoryStore()); //memory store log.info("Configuring Semantic Repository."); File storageDir = new File(catalogCacheDirectory); //define local copy of repository owlimSail.setDataDir(storageDir); log.debug("Semantic Repository Data directory set to: "+ catalogCacheDirectory); // prepare config owlimSail.setParameter("storage-folder", owlim_storage_folder); log.debug("Semantic Repository 'storage-folder' set to: "+owlim_storage_folder); // Choose the operational ruleset String ruleset; ruleset = "owl-horst"; //ruleset = "owl-max"; owlimSail.setParameter("ruleset", ruleset); //owlimSail.setParameter("ruleset", "owl-max"); //owlimSail.setParameter("partialRDFs", "false"); log.debug("Semantic Repository 'ruleset' set to: "+ ruleset); log.info("Intializing Semantic Repository."); // Initialize repository owlse2.initialize(); //needed log.info("Semantic Repository Ready."); if(Thread.currentThread().isInterrupted()) throw new InterruptedException("Thread.currentThread.isInterrupted() returned 'true'."); } private void updateSemanticRepository(RepositoryConnection con, Vector<String> importURLs) throws InterruptedException, RepositoryException { URI uriaddress; URL inUrl; Thread thread = Thread.currentThread(); Date startTime = new Date(); log.info("Evaluating importURLs for updateCatalog... "); for (String importURL : importURLs) { try { // log.info("Importing "+importURL); inUrl = new URL(importURL); uriaddress = new URIImpl(importURL); // owlse2.printLTMODContext(importURL); if (owlse2.olderContext(importURL)) {// if new updateCatalog // available delete old // one if (owlse2.hasContext(uriaddress, con)) { log.info("Removing URL: " + importURL); con.clear((Resource) uriaddress); log.info("Finished removing URL: " + importURL); if (thread.isInterrupted()) { log .warn("updateSemanticRepository(): WARNING! Thread " + thread.getName() + " was interrupted!"); return; } log.info("Removing last_modified_time of URL: " + importURL); owlse2.deleteLTMODContext(importURL, con); // deleteIsContainedBy(importURL, CollectionURL); //need // some work here!!! log .info("Finished removing last_modified_time of URL: " + importURL); if (thread.isInterrupted()) { log .warn("updateSemanticRepository(): WARNING! Thread " + thread.getName() + " was interrupted!"); return; } } log.info("Importing URL: " + inUrl); con.add(inUrl, importURL, RDFFormat.RDFXML, (Resource) uriaddress); log.info("Finished Importing URL: " + inUrl); if (thread.isInterrupted()) { log.warn("updateSemanticRepository(): WARNING! Thread " + thread.getName() + " was interrupted!"); return; } log.info("Setting last modified time for context: " + inUrl); owlse2.setLTMODContext(importURL, con); // set last modified // time for the // context log.info("Finished setting last modified time for context: " + inUrl); if (thread.isInterrupted()) { log.warn("updateSemanticRepository(): WARNING! Thread " + thread.getName() + " was interrupted!"); return; } // setIsContainedBy(importURL, CollectionURL); //need some work here!!! log.info("Adding last_modified_time of URL: " + importURL); owlse2.imports.add(importURL); // track what is added in // the repository log.info("Finished Adding last_modified_time of URL: " + importURL); if (thread.isInterrupted()) { log.warn("updateSemanticRepository(): WARNING! Thread " + thread.getName() + " was interrupted!"); return; } } else { if (!owlse2.imports.contains(importURL)) { owlse2.imports.add(importURL); // track what is added // in the repository } log.info("Skip import: " + inUrl); } } catch (MalformedURLException e) { log.error("Failed to import " + importURL + " MalformedURLException message: " + e.getMessage()); } catch (IOException e) { log.error("Failed to import " + importURL + " IOException message: " + e.getMessage()); } catch (RDFParseException e) { log.error("Failed to import " + importURL + " RDFParseException message: " + e.getMessage()); } catch (RepositoryException e) { log.error("Failed to import " + importURL + " RepositoryException message: " + e.getMessage()); } } long elapsedTime = new Date().getTime() - startTime.getTime(); log.info("Imports Evaluated. Elapsed time: " + elapsedTime + "ms"); log .debug("**********************************************************************************!"); log.info("Updating repository!"); Boolean updated = owlse2.update(); /***************************************************** * ingest swrl rules *****************************************************/ ingestSwrlRules(); log.info("Repository updateCatalog =" + updated); log.info("RDF import complete."); } private void ingestSwrlRules() throws RepositoryException{ log.info("Running runConstruct .."); owlse2.runConstruct(); log.info("Complete running runConstruct .."); } private void updateRepository(Vector<String> importURLs) throws RepositoryException,InterruptedException { RepositoryConnection con = owlse2.getConnection(); log.info("Repository connection has been opened."); updateSemanticRepository(con, importURLs); log.info("Closing repository connection."); con.close(); //close connection first } public void dumpRepository(RepositoryConnection con, String filename) { //export repository to an n-triple file File outrps = new File(filename); //hard copy of repository try { FileOutputStream myFileOutputStream = new FileOutputStream(outrps); NTriplesWriter myNTRiplesWriter = new NTriplesWriter(myFileOutputStream); //log.info("Dumping explicit statements (as Ntriples) to: " + outrps.getAbsoluteFile()); myNTRiplesWriter.startRDF(); myNTRiplesWriter.endRDF(); con.export(myNTRiplesWriter); log.info("Completed dumping explicit statements"); } catch (Throwable e) { log.warn(e.getMessage()); } } public void dumpRepository(String filename) throws RepositoryException { RepositoryConnection con = owlse2.getConnection(); log.info("Repository connection has been opened."); dumpRepository(con, filename); log.info("Closing repository connection."); con.close(); //close connection first } private void processContexts() throws RepositoryException { RepositoryConnection con = owlse2.getConnection(); log.info("Repository connection has been opened."); processContexts(con); log.info("Closing repository connection."); con.close(); //close connection first } private void processContexts(RepositoryConnection con) throws RepositoryException { /* ################################################### Looking at the code I concluded that this block was diagnostic cruft that seemed to be pretty useless. So I commented it out. We can put it back if needed. (ndp)*/ //retrieve context RepositoryResult<Resource> contextID = con.getContextIDs(); int contextTol = 0; if (!contextID.hasNext()) { log.warn("No Contexts found!"); } else { while (contextID.hasNext()) { String ctstr = contextID.next().toString(); log.info("Context: " + ctstr); owlse2.printLTMODContext(ctstr); contextTol++; } } contextID.close(); //needed to release resources log.info("Found " + contextTol + " Contexts"); /*########################################################*/ } private void extractCoverageDescrptionsFromRepository() throws RepositoryException { RepositoryConnection con = owlse2.getConnection(); log.info("Repository connection has been opened."); extractCoverageDescrptionsFromRepository(con); log.info("Closing repository connection."); con.close(); //close connection first } private void extractCoverageDescrptionsFromRepository(RepositoryConnection con) { //retrieve XML from the RDF store. log.info("Extracting CoverageDescriptions from repository."); buildDoc = new XMLfromRDF(con, "CoverageDescriptions", "http://www.opengis.net/wcs/1.1#CoverageDescription"); buildDoc.getXMLfromRDF("http://www.opengis.net/wcs/1.1#CoverageDescription"); //build a JDOM doc by querying against the RDF store } private void dumpCoverageDescriptionsDocument(String filename) { //print out the XML XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); /* ##################################################### Why is this being written out? Is this a diagnostic? purely for diagnostic purposes (HB Dec032009) Or is this file used later by some other part of the software? No. (HB Dec032009) Can we remove this??? Yes, once we are happy with the JDom Doc retrieval (HB Dec032009) */ try { File destinationFile = new File(filename); FileOutputStream fos = new FileOutputStream(destinationFile); outputter.output(buildDoc.getDoc(), fos); } catch (IOException e1) { e1.printStackTrace(); } /* ############################################## */ } public void destroy() { log.debug("destroy(): Attempting to aquire WriteLock from _catalogLock and _repositoryLock."); ReentrantReadWriteLock.WriteLock catLock = _catalogLock.writeLock(); ReentrantReadWriteLock.WriteLock reposLock = _repositoryLock.writeLock(); try { catLock.lock(); reposLock.lock(); log.debug("destroy(): WriteLocks Aquired."); setStopFlag(true); if(catalogUpdateThread!=null){ log.debug("Current thread '"+Thread.currentThread().getName()+"' Interrupting thread '"+catalogUpdateThread+"'"); catalogUpdateThread.interrupt(); } log.info("Shutting Down Semantic Repository."); owlse2.shutDown(); log.info("Semantic Repository Has Been Shutdown."); } catch (RepositoryException e) { log.error("destroy(): Failed to shutdown Semantic Repository."); } finally{ catLock.unlock(); reposLock.unlock(); log.debug("destroy(): Released WriteLock for _catalogLock and _repositoryLock."); } } private Vector<String> getRdfImports(Element config) { Vector<String> rdfImports = new Vector<String>(); Element e; String s; /** * Load individual dataset references */ Iterator i = config.getChildren("dataset").iterator(); String datasetURL; while (i.hasNext()) { e = (Element) i.next(); datasetURL = e.getTextNormalize(); if (!datasetURL.endsWith(".rdf")) { if (datasetURL.endsWith(".ddx") | datasetURL.endsWith(".dds") | datasetURL.endsWith(".das") ) { datasetURL = datasetURL.substring(0, datasetURL.lastIndexOf(".")); } datasetURL += ".rdf"; } rdfImports.add(datasetURL); log.info("Added dataset reference " + datasetURL + " to RDF imports list."); log.debug("<wcs:Identifier>"+this.getWcsIdString(datasetURL)+"</wcs:Identifier>"); } /** * Load THREDDS Catalog references. */ i = config.getChildren("ThreddsCatalog").iterator(); String catalogURL; boolean recurse; while (i.hasNext()) { e = (Element) i.next(); catalogURL = e.getTextNormalize(); recurse = false; s = e.getAttributeValue("recurse"); if (s != null && s.equalsIgnoreCase("true")) recurse = true; ThreddsCatalogUtil tcu = null; try { // Passing false means no caching but also no exception. // Maybe there's a better way to code the TCU ctor? tcu = new ThreddsCatalogUtil(); } catch (Exception e1) { log.debug("ThreddsCatalogUtil exception: " + e1.getMessage()); } Vector<String> datasetURLs = tcu.getDataAccessURLs(catalogURL, ThreddsCatalogUtil.SERVICE.OPeNDAP, recurse); for (String dataset : datasetURLs) { dataset += ".rdf"; rdfImports.add(dataset); log.info("Added dataset reference " + dataset + " to RDF imports list."); } } /** * Load RDF Imports */ i = config.getChildren("RdfImport").iterator(); while (i.hasNext()) { e = (Element) i.next(); s = e.getTextNormalize(); rdfImports.add(s); log.info("Added reference " + s + " to RDF imports list."); } return rdfImports; } private void ingestCatalog() throws Exception { log.info("Ingesting catalog from CoverageDescriptions Document built by the XMLFromRDF object..."); List<Element> cd = buildDoc.getDoc().getRootElement().getChildren(); Iterator<Element> i = cd.iterator(); HashMap<String, String> idltm = owlse2.getLMT(); String lastMDT = "nolastMDT"; while (i.hasNext()) { Element e = i.next(); List<Element> elist = e.getChildren(); Iterator<Element> j = elist.iterator(); while (j.hasNext()) { Element eID = j.next(); String idstr = eID.getName(); if (idstr.equalsIgnoreCase("Identifier")) { lastMDT = idltm.get(eID.getText()); String datetime = lastMDT.substring(0, 10) + " " + lastMDT.substring(11, 19) + " +0000"; DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); Date date = sdf.parse(datetime); log.debug("Date and Time: " + date.getTime()); ingestCoverageDescription(e, date.getTime()); //log.debug("element: "+ eID.getText()); //log.debug("lastMDT = "+ lastMDT); log.debug("Add element " + e.getName()); } } }//while(i.hasNext() _lastModified = -1; } public void ingestCoverageDescription(URL server, Element cde, long lastModified) throws Exception { } public void ingestCoverageDescription(Element cde, long lastModified) { CoverageDescription cd; try { cd = new CoverageDescription(cde, lastModified); coverages.put(cd.getIdentifier(), cd); log.info("Ingested CoverageDescription: " + cd.getIdentifier()); } catch (WcsException e) { XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat()); String wcseElem = xmlo.outputString(e.getExceptionElement()); String cvgDesc = xmlo.outputString(cde); log.error("Failed to ingest CoverageDescription!\n" + "WcsException: \n"+wcseElem+"\n"+ "Bad CoverageDescription:\n"+cvgDesc ); } } public boolean hasCoverage(String id) { log.debug("Looking for a coverage with ID: " + id); ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock(); try { lock.lock(); log.debug("_catalogLock ReadLock Acquired."); return coverages.containsKey(id); } finally { lock.unlock(); log.debug("_catalogLock ReadLock Released."); } } public Element getCoverageDescriptionElement(String id) { ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock(); try { lock.lock(); log.debug("_catalogLock ReadLock Acquired."); CoverageDescription cd = coverages.get(id); if(cd==null) return null; return cd.getElement(); } finally { lock.unlock(); log.debug("_catalogLock ReadLock Released."); } } public List<Element> getCoverageDescriptionElements() throws WcsException { throw new WcsException("getCoverageDescriptionElements() method Not Implemented", WcsException.NO_APPLICABLE_CODE); } public CoverageDescription getCoverageDescription(String id) { ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock(); try { lock.lock(); log.debug("_catalogLock ReadLock Acquired."); return coverages.get(id); } finally { lock.unlock(); log.debug("_catalogLock ReadLock Released."); } } public Element getCoverageSummaryElement(String id) throws WcsException { ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock(); try { lock.lock(); log.debug("_catalogLock ReadLock Acquired."); return coverages.get(id).getCoverageSummary(); } finally { lock.unlock(); log.debug("_catalogLock ReadLock Released."); } } public List<Element> getCoverageSummaryElements() throws WcsException { ArrayList<Element> coverageSummaries = new ArrayList<Element>(); Enumeration e; CoverageDescription cd; ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock(); try { lock.lock(); log.debug("_catalogLock ReadLock Acquired."); // Get all of the unique formats. e = coverages.elements(); while (e.hasMoreElements()) { cd = (CoverageDescription) e.nextElement(); coverageSummaries.add(cd.getCoverageSummary()); } } finally { lock.unlock(); log.debug("_catalogLock ReadLock Released."); } return coverageSummaries; } public List<Element> getSupportedFormatElements() { ArrayList<Element> supportedFormats = new ArrayList<Element>(); HashMap<String, Element> uniqueFormats = new HashMap<String, Element>(); Enumeration enm; Element e; Iterator i; CoverageDescription cd; ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock(); try { lock.lock(); log.debug("_catalogLock ReadLock Acquired."); // Get all of the unique formats. enm = coverages.elements(); while (enm.hasMoreElements()) { cd = (CoverageDescription) enm.nextElement(); i = cd.getSupportedFormatElements().iterator(); while (i.hasNext()) { e = (Element) i.next(); uniqueFormats.put(e.getTextTrim(), e); } } i = uniqueFormats.values().iterator(); while (i.hasNext()) { supportedFormats.add((Element) i.next()); } } finally { lock.unlock(); log.debug("_catalogLock ReadLock Released."); } return supportedFormats; } public List<Element> getSupportedCrsElements() { ArrayList<Element> supportedCRSs = new ArrayList<Element>(); HashMap<String, Element> uniqueCRSs = new HashMap<String, Element>(); Enumeration enm; Element e; Iterator i; CoverageDescription cd; ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock(); try { lock.lock(); log.debug("_catalogLock ReadLock Acquired."); // Get all of the unique formats. enm = coverages.elements(); while (enm.hasMoreElements()) { cd = (CoverageDescription) enm.nextElement(); i = cd.getSupportedCrsElements().iterator(); while (i.hasNext()) { e = (Element) i.next(); uniqueCRSs.put(e.getTextTrim(), e); } } i = uniqueCRSs.values().iterator(); while (i.hasNext()) { supportedCRSs.add((Element) i.next()); } } finally { lock.unlock(); log.debug("_catalogLock ReadLock Released."); } return supportedCRSs; } public String getLatitudeCoordinateDapId(String coverageId) { return null; } public String getLongitudeCoordinateDapId(String coverageId) { return null; } public String getElevationCoordinateDapId(String coverageId) { return null; } public String getTimeCoordinateDapId(String coverageId) { return null; } public long getLastModified() { return _lastModified; } public void setStopFlag(boolean flag){ stopWorking = flag; } public void updateCatalogCache() throws InterruptedException{ Thread thread = Thread.currentThread(); int biffCount = 0; if (!stopWorking && !thread.isInterrupted() ) { ReentrantReadWriteLock.WriteLock catlock = _catalogLock.writeLock(); ReentrantReadWriteLock.ReadLock repLock = _repositoryLock.readLock(); try { repLock.lock(); catlock.lock(); log.debug("_catalogLock WriteLock Acquired."); if (!stopWorking && !thread.isInterrupted()) { log.debug("Updating Catalog Cache."); try { coverageIDServer = getCoverageIDServerURL(); // for (String covID :coverageIDServer.keySet()){ //print all coverageID and server // log.info("CoverageID: " +covID); // Vector <String> covURLs=coverageIDServer.get(covID); // for (int i =0; i <covURLs.size(); i++) { // log.info("CoverageURL ("+i+"): " +covURLs.get(i)); // } // } } catch (RepositoryException e) { log.error("Caught RepositoryException in getCoverageIDServerURL: " + e.getMessage()); } catch (MalformedQueryException e) { log.error("Caught MalformedQueryException in getCoverageIDServerURL: " + e.getMessage()); } catch (QueryEvaluationException e) { log.error("Caught QueryEvaluationException in getCoverageIDServerURL: " + e.getMessage()); } addSupportedFormats(buildDoc.getRootElement()); ingestCatalog(); timeOfLastUpdate = new Date().getTime(); log.debug("Catalog Cache updated at "+ new Date(timeOfLastUpdate)); } } catch (Exception e) { log.error("updateCatalog() has a problem: " + e.getMessage() + " biffCount: " + (++biffCount)); e.printStackTrace(); } finally { catlock.unlock(); repLock.unlock(); log.debug("_catalogLock WriteLock Released."); } } if(thread.isInterrupted()) { log.warn("updateCatalog(): WARNING! Thread "+thread.getName()+" was interrupted!"); throw new InterruptedException(); } } public void updateCatalog() throws RepositoryException, InterruptedException{ setupRepository(); try { if (updateRepository()) updateCatalogCache(); } finally { shutdownRepository(); } } /** * * @return * @throws RepositoryException * @throws MalformedQueryException * @throws QueryEvaluationException */ private HashMap<String, Vector<String>> getCoverageIDServerURL() throws RepositoryException, MalformedQueryException, QueryEvaluationException { TupleQueryResult result = null; HashMap<String, Vector<String>> coverageIDServer = new HashMap<String, Vector<String>>(); String queryString = "SELECT coverageurl,coverageid " + "FROM " + "{} wcs:CoverageDescription {coverageurl} wcs:Identifier {coverageid} " + "USING NAMESPACE " + "wcs = <http://www.opengis.net/wcs/1.1#>"; RepositoryConnection con = owlse2.getConnection(); log.debug("query coverage ID and server URL: \n" + queryString); TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SERQL, queryString); result = tupleQuery.evaluate(); log.debug("Qresult: " + result.hasNext()); List<String> bindingNames = result.getBindingNames(); //log.debug(bindingNames.probeServletContext()); while (result.hasNext()) { BindingSet bindingSet = (BindingSet) result.next(); // log.debug(bindingSet.probeServletContext()); Vector<String> coverageURL = new Vector<String>(); if (bindingSet.getValue("coverageid") != null && bindingSet.getValue("coverageurl") != null) { Value valueOfcoverageid = (Value) bindingSet.getValue("coverageid"); Value valueOfcoverageurl = (Value) bindingSet.getValue("coverageurl"); coverageURL.addElement(valueOfcoverageurl.stringValue()); //log.debug("coverageid:"); //log.debug(valueOfcoverageid.stringValue()); //log.debug("coverageurl:"); log.debug(valueOfcoverageurl.stringValue()); if (coverageIDServer.containsKey(valueOfcoverageid.stringValue())) coverageIDServer.get(valueOfcoverageid.stringValue()).addElement(valueOfcoverageurl.stringValue()); else coverageIDServer.put(valueOfcoverageid.stringValue(), coverageURL); } } con.close(); return coverageIDServer; } public long getCatalogAge() { Date now = new Date(); return now.getTime() - timeOfLastUpdate; } public boolean updateRepository() throws InterruptedException { boolean success = false; int biffCount = 0; Thread thread = Thread.currentThread(); if (!stopWorking && !thread.isInterrupted() ) { ReentrantReadWriteLock.WriteLock lock = _repositoryLock.writeLock(); try { lock.lock(); repositoryUpdateActive.set(true); log.debug("_repositoryLock WriteLock Acquired."); if (!stopWorking && !thread.isInterrupted()) { log.debug("updateRepository(): Updating Semantic Repository."); log.debug("updateRepository(): Connecting to Repository..."); RepositoryConnection con = owlse2.getConnection(); log.info("updateRepository(): Repository connection has been opened."); if(thread.isInterrupted() || stopWorking ){ log.warn("updateRepository(): WARNING! Thread "+thread.getName()+" was interrupted!"); throw new InterruptedException("Thread.currentThread.isInterrupted() returned 'true'."); } log.debug("updateRepository(): Getting RDF imports."); Vector<String> importURLs = getRdfImports(_config); if(thread.isInterrupted() || stopWorking){ log.warn("updateRepository(): WARNING! Thread "+thread.getName()+" was interrupted!"); throw new InterruptedException("Thread.currentThread.isInterrupted() returned 'true'."); } log.debug("updateRepository(): Updating semantic repository."); updateSemanticRepository(con, importURLs); if(thread.isInterrupted() || stopWorking){ log.warn("updateRepository(): WARNING! Thread "+thread.getName()+" was interrupted!"); throw new InterruptedException("Thread.currentThread.isInterrupted() returned 'true'."); } String filename = catalogCacheDirectory + "daprepository2"; log.debug("updateRepository(): Dumping Semantic Repository to: "+filename); dumpRepository(con, filename); if(thread.isInterrupted() || stopWorking){ log.warn("updateRepository(): WARNING! Thread "+thread.getName()+" was interrupted!"); throw new InterruptedException("Thread.currentThread.isInterrupted() returned 'true'."); } /* log.debug("updateRepository(): Processing Contexts..."); processContexts(con); if(thread.isInterrupted() || stopWorking){ log.warn("updateRepository(): WARNING! Thread "+thread.getName()+" was interrupted!"); throw new InterruptedException("Thread.currentThread.isInterrupted() returned 'true'."); } */ log.debug("Extracting CoverageDescriptions from the Repository."); extractCoverageDescrptionsFromRepository(con); if(thread.isInterrupted() || stopWorking){ log.warn("updateRepository(): WARNING! Thread "+thread.getName()+" was interrupted!"); throw new InterruptedException("Thread.currentThread.isInterrupted() returned 'true'."); } filename = catalogCacheDirectory + "coverageXMLfromRDF.xml"; log.debug("updateRepository(): Dumping CoverageDescriptions Document to: "+filename); dumpCoverageDescriptionsDocument(filename); if(thread.isInterrupted() || stopWorking){ log.warn("updateRepository(): WARNING! Thread "+thread.getName()+" was interrupted!"); throw new InterruptedException("Thread.currentThread.isInterrupted() returned 'true'."); } log.info("updateRepository(): Closing repository!"); con.close(); //close connection first if(thread.isInterrupted() || stopWorking){ log.warn("updateRepository(): WARNING! Thread "+thread.getName()+" was interrupted!"); throw new InterruptedException("Thread.currentThread.isInterrupted() returned 'true'."); } success = true; repositoryUpdateActive.set(false); } } catch (InterruptedException e){ throw e; } catch (Exception e) { log.error("updateRepository() has a problem. Error Message: '" + e.getMessage() + "' biffCount: " + (++biffCount)); } finally { lock.unlock(); log.debug("_repositoryLock.WriteLock Released."); if(thread.isInterrupted()) throw new InterruptedException(); } } if(thread.isInterrupted()){ log.warn("updateRepository(): WARNING! Thread "+thread.getName()+" was interrupted!"); throw new InterruptedException(); } log.debug("updateRepository() returning: " + success); return success; } public void run() { try { log.info("************* STARTING CATALOG UPDATE THREAD."); try { log.info("************* CATALOG UPDATE THREAD sleeping for " + firstUpdateDelay / 1000.0 + " seconds."); Thread.sleep(firstUpdateDelay); } catch (InterruptedException e) { log.warn("Caught Interrupted Exception."); stopWorking = true; } int updateCounter = 0; long startTime, endTime; long elapsedTime, sleepTime; stopWorking = false; Thread thread = Thread.currentThread(); while (!stopWorking) { try { startTime = new Date().getTime(); try { updateCatalog(); } catch (RepositoryException e) { log.error("Problem using Repository! msg: "+e.getMessage()); } endTime = new Date().getTime(); elapsedTime = (endTime - startTime); updateCounter++; log.debug("Completed catalog update " + updateCounter + " in " + elapsedTime / 1000.0 + " seconds."); sleepTime = catalogUpdateInterval - elapsedTime; stopWorking = thread.isInterrupted(); if (!stopWorking && sleepTime > 0) { log.debug("Catalog Update thread sleeping for " + sleepTime / 1000.0 + " seconds."); Thread.sleep(sleepTime); } } catch (InterruptedException e) { log.warn("Caught Interrupted Exception."); stopWorking = true; } } } finally { destroy(); } log.info("************* EXITING CATALOG UPDATE THREAD."); } private void addSupportedFormats(Element coverages) throws MalformedURLException { XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat()); Element coverageDescription; Element identifierElem; Iterator i; String coverageID; String msg; Vector<String> servers; i = coverages.getChildren().iterator(); while(i.hasNext()){ coverageDescription = (Element)i.next(); identifierElem = coverageDescription.getChild("Identifier",WCS.WCS_NS); coverageID = identifierElem.getTextTrim(); servers = coverageIDServer.get(coverageID); Vector<Element> supportedFormats = getWcsSupportedFormatElements(new URL(servers.get(0))); coverageDescription.addContent(supportedFormats); msg = "Adding supported formats to coverage "+coverageID+ "\n"+ "CoverageDescription Element: \n "+xmlo.outputString(coverageDescription)+"\n"+ "Coverage "+coverageID+" held at: \n"; for(String s: servers){ msg += " "+s+"\n"; } log.debug(msg); } } private Vector<Element> getWcsSupportedFormatElements(URL dapServerUrl){ Vector<Element> sfEs = new Vector<Element>(); String[] formats = ServerCapabilities.getSupportedFormatStrings(dapServerUrl); Element sf; for(String format: formats){ sf = new Element("SupportedFormat",WCS.WCS_NS); sf.setText(format); sfEs.add(sf); } return sfEs; } /** * Build a wcs:Identifier for the coverage dataset described by the datasetUrl. * * @param datasetUrl * @return A valid and unique to this service wcs:Identifier String for the coverage dataset */ public String getWcsIdString(String datasetUrl) { String wcsID="FAILED_TO_BUILD_WCS_ID"; try { int i; String serverURL, serverPrefix; URL dsu = new URL(datasetUrl); serverURL = getServerUrlString(dsu); if(serviceIDs.containsKey(serverURL)){ // get server prefix serverPrefix = serviceIDs.get(serverURL); } else { serverPrefix = "S"+ (serviceIDs.size()+1) + ""; // Generate service prefix // Store service prefix. serviceIDs.put(serverURL,serverPrefix); } // Build wcsID wcsID = serverPrefix + datasetUrl.substring(serverURL.length(),datasetUrl.length()); log.debug("wcsID: "+wcsID); if(!wcsIDs.containsKey(datasetUrl)){ // add wcs:Identifier to MAP wcsIDs.put(datasetUrl,wcsID); } } catch (MalformedURLException e) { log.error("Cannot Build wcs:Identifier from URL "+datasetUrl+" error msg: "+e.getMessage()); } return wcsID; } private String getServerUrlString(URL url) { String baseURL = null; String protocol = url.getProtocol(); if (protocol.equalsIgnoreCase("file")) { log.debug("Protocol is FILE."); } else if (protocol.equalsIgnoreCase("http")) { log.debug("Protocol is HTTP."); String host = url.getHost(); String path = url.getPath(); int port = url.getPort(); baseURL = protocol + "://" + host; if (port != -1) baseURL += ":" + port; } log.debug("ServerURL: " + baseURL); return baseURL; } }
src/opendap/semantics/IRISail/StaticRDFCatalog.java
package opendap.semantics.IRISail; import opendap.wcs.v1_1_2.*; import org.jdom.Element; import org.jdom.filter.ElementFilter; import org.jdom.output.XMLOutputter; import org.jdom.output.Format; import org.slf4j.Logger; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.ConcurrentHashMap; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import org.openrdf.model.Resource; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.model.impl.URIImpl; import org.openrdf.query.BindingSet; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.QueryLanguage; import org.openrdf.query.TupleQuery; import org.openrdf.query.TupleQueryResult; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.RepositoryResult; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFParseException; import org.openrdf.rio.ntriples.NTriplesWriter; import com.ontotext.trree.owlim_ext.SailImpl; /** * A colon of LocalFileCatalog */ public class StaticRDFCatalog implements WcsCatalog, Runnable { private Logger log; // = LoggerFactory.getLogger(StaticRDFCatalog.class); private AtomicBoolean repositoryUpdateActive; private ReentrantReadWriteLock _repositoryLock; private IRISailRepository owlse2; private XMLfromRDF buildDoc; //private static boolean _useMemoryCache; //private Date _cacheTime; private long _lastModified; private ConcurrentHashMap<String, CoverageDescription> coverages; private ReentrantReadWriteLock _catalogLock; private Thread catalogUpdateThread; private long firstUpdateDelay; private long catalogUpdateInterval; private long timeOfLastUpdate; private boolean stopWorking = false; private Element _config; private String cacheDirectory; private String resourcePath; private boolean backgroundUpdates; private HashMap<String, Vector<String> > coverageIDServer; private ConcurrentHashMap<String, String> serviceIDs = new ConcurrentHashMap<String,String>(); private ConcurrentHashMap<String, String> wcsIDs = new ConcurrentHashMap<String,String>(); private boolean initialized; public StaticRDFCatalog() { log = org.slf4j.LoggerFactory.getLogger(this.getClass()); catalogUpdateInterval = 20 * 60 * 1000; // 20 minutes worth of milliseconds firstUpdateDelay = 5 * 1000; // 5 second worth of milliseconds timeOfLastUpdate = 0; stopWorking = false; _catalogLock = new ReentrantReadWriteLock(); coverages = new ConcurrentHashMap<String, CoverageDescription>(); _repositoryLock = new ReentrantReadWriteLock(); repositoryUpdateActive = new AtomicBoolean(); repositoryUpdateActive.set(false); backgroundUpdates = false; owlse2 = null; buildDoc = null; _lastModified = -1; _config = null; cacheDirectory = null; resourcePath = null; initialized = false; } public static void main(String[] args) { long startTime, endTime; double elapsedTime; StaticRDFCatalog catalog = new StaticRDFCatalog(); try { Map<String,String> env = System.getenv(); catalog.resourcePath = "."; catalog.cacheDirectory = "."; String configFileName; configFileName = "file:///data/haibo/workspace/ioos/wcs_service.xml"; if(args.length>0) configFileName = args[0]; catalog.log.debug("main() using config file: "+configFileName); Element olfsConfig = opendap.xml.Util.getDocumentRoot(configFileName); catalog._config = (Element)olfsConfig.getDescendants(new ElementFilter("WcsCatalog")).next(); catalog.processConfig(catalog._config, catalog.cacheDirectory, catalog.resourcePath); boolean done = false; catalog.setupRepository(); catalog.extractCoverageDescrptionsFromRepository(); catalog.updateCatalogCache(); for(int i=0; i<1 ;i++){ startTime = new Date().getTime(); //catalog.setupRepository(); catalog.updateCatalog(); //catalog.destroy(); endTime = new Date().getTime(); elapsedTime = (endTime - startTime)/1000.0; catalog.log.debug("Completed catalog update in "+elapsedTime+ " seconds."); catalog.log.debug("########################################################################################"); catalog.log.debug("########################################################################################"); catalog.log.debug("########################################################################################"); catalog.setStopFlag(false); Thread.sleep(5000); } } catch (Exception e) { e.printStackTrace(); } finally { catalog.destroy(); } } public void init(Element config, String defaultCacheDirectory, String defaultResourcePath) throws Exception { if (initialized) return; backgroundUpdates = false; _config = config; processConfig(_config,defaultCacheDirectory, defaultResourcePath ); setupRepository(); extractCoverageDescrptionsFromRepository(); updateCatalogCache(); if (backgroundUpdates) { catalogUpdateThread = new Thread(this); catalogUpdateThread.start(); } else { updateCatalog(); } initialized = true; } private void processConfig(Element config,String defaultCacheDirectory, String defaultResourcePath){ Element e; File file; /** ######################################################## * Process configuration. */ cacheDirectory = defaultCacheDirectory; e = config.getChild("CacheDirectory"); if (e != null) cacheDirectory = e.getTextTrim(); if (cacheDirectory != null && cacheDirectory.length() > 0 && !cacheDirectory.endsWith("/")) cacheDirectory += "/"; file = new File(cacheDirectory); if (!file.exists()) { if (!file.mkdirs()) { log.error("Unable to create cache directory: " + cacheDirectory); if(!cacheDirectory.equals(defaultCacheDirectory)){ file = new File(defaultCacheDirectory); if (!file.exists()) { if (!file.mkdirs()) { log.error("Unable to create cache directory: " + defaultCacheDirectory); log.error("Process probably doomed..."); } } } else { log.error("Process probably doomed..."); } } } log.info("Using cacheDirectory: "+ cacheDirectory); resourcePath = defaultResourcePath; e = config.getChild("ResourcePath"); if (e != null) resourcePath = e.getTextTrim(); if (resourcePath != null && resourcePath.length() > 0 && !resourcePath.endsWith("/")) resourcePath += "/"; file = new File(this.resourcePath); if (!file.exists()) { log.error("Unable to locate resource directory: " + resourcePath); file = new File(defaultResourcePath); if (!file.exists()) { log.error("Unable to locate default resource directory: " + defaultResourcePath); log.error("Process probably doomed..."); } } log.info("Using resourcePath: "+resourcePath); e = config.getChild("useUpdateCatalogThread"); if(e != null){ backgroundUpdates = true; String s = e.getAttributeValue("updateInterval"); if (s != null){ catalogUpdateInterval = Long.parseLong(s) * 1000; } s = e.getAttributeValue("firstUpdateDelay"); if (s != null){ firstUpdateDelay = Long.parseLong(s) * 1000; } } log.info("backgroundUpdates: "+backgroundUpdates); log.info("Catalog update interval: "+catalogUpdateInterval+"ms"); log.info("First update delay: "+firstUpdateDelay+"ms"); } private void setupRepository() throws RepositoryException, InterruptedException { log.info("Building Semantic Repository."); //OWLIM Sail Repository (inferencing makes this somewhat slow) SailImpl owlimSail = new com.ontotext.trree.owlim_ext.SailImpl(); owlse2 = new IRISailRepository(owlimSail, resourcePath, cacheDirectory); //owlim inferencing //owlse2 = new IRISailRepository(new MemoryStore()); //memory store log.info("Configuring Semantic Repository."); File storageDir = new File(cacheDirectory); //define local copy of repository owlimSail.setDataDir(storageDir); // prepare config owlimSail.setParameter("storage-folder", "owlim-storage"); // Choose the operational ruleset owlimSail.setParameter("ruleset", "owl-horst"); //owlimSail.setParameter("ruleset", "owl-max"); //owlimSail.setParameter("partialRDFs", "false"); log.info("Intializing Semantic Repository."); // Initialize repository owlse2.initialize(); //needed log.info("Semantic Repository Ready."); if(Thread.currentThread().isInterrupted()) throw new InterruptedException("Thread.currentThread.isInterrupted() returned 'true'."); } private void updateSemanticRepository(RepositoryConnection con, Vector<String> importURLs) throws InterruptedException, RepositoryException { URI uriaddress; URL inUrl; Thread thread = Thread.currentThread(); Date startTime = new Date(); log.info("Evaluating importURLs for updateCatalog... "); for (String importURL : importURLs) { try { // log.info("Importing "+importURL); inUrl = new URL(importURL); uriaddress = new URIImpl(importURL); // owlse2.printLTMODContext(importURL); if (owlse2.olderContext(importURL)) {// if new updateCatalog // available delete old // one if (owlse2.hasContext(uriaddress, con)) { log.info("Removing URL: " + importURL); con.clear((Resource) uriaddress); log.info("Finished removing URL: " + importURL); if (thread.isInterrupted()) { log .warn("updateSemanticRepository(): WARNING! Thread " + thread.getName() + " was interrupted!"); return; } log.info("Removing last_modified_time of URL: " + importURL); owlse2.deleteLTMODContext(importURL, con); // deleteIsContainedBy(importURL, CollectionURL); //need // some work here!!! log .info("Finished removing last_modified_time of URL: " + importURL); if (thread.isInterrupted()) { log .warn("updateSemanticRepository(): WARNING! Thread " + thread.getName() + " was interrupted!"); return; } } log.info("Importing URL: " + inUrl); con.add(inUrl, importURL, RDFFormat.RDFXML, (Resource) uriaddress); log.info("Finished Importing URL: " + inUrl); if (thread.isInterrupted()) { log.warn("updateSemanticRepository(): WARNING! Thread " + thread.getName() + " was interrupted!"); return; } log.info("Setting last modified time for context: " + inUrl); owlse2.setLTMODContext(importURL, con); // set last modified // time for the // context log.info("Finished setting last modified time for context: " + inUrl); if (thread.isInterrupted()) { log.warn("updateSemanticRepository(): WARNING! Thread " + thread.getName() + " was interrupted!"); return; } // setIsContainedBy(importURL, CollectionURL); //need some work here!!! log.info("Adding last_modified_time of URL: " + importURL); owlse2.imports.add(importURL); // track what is added in // the repository log.info("Finished Adding last_modified_time of URL: " + importURL); if (thread.isInterrupted()) { log.warn("updateSemanticRepository(): WARNING! Thread " + thread.getName() + " was interrupted!"); return; } } else { if (!owlse2.imports.contains(importURL)) { owlse2.imports.add(importURL); // track what is added // in the repository } log.info("Skip import: " + inUrl); } } catch (MalformedURLException e) { log.error("Failed to import " + importURL + " MalformedURLException message: " + e.getMessage()); } catch (IOException e) { log.error("Failed to import " + importURL + " IOException message: " + e.getMessage()); } catch (RDFParseException e) { log.error("Failed to import " + importURL + " RDFParseException message: " + e.getMessage()); } catch (RepositoryException e) { log.error("Failed to import " + importURL + " RepositoryException message: " + e.getMessage()); } } long elapsedTime = new Date().getTime() - startTime.getTime(); log.info("Imports Evaluated. Elapsed time: " + elapsedTime + "ms"); log .debug("**********************************************************************************!"); log.info("Updating repository!"); Boolean updated = owlse2.update(); /***************************************************** * ingest swrl rules *****************************************************/ ingestSwrlRules(); log.info("Repository updateCatalog =" + updated); log.info("RDF import complete."); } private void ingestSwrlRules() throws RepositoryException{ log.info("Running runConstruct .."); owlse2.runConstruct(); log.info("Complete running runConstruct .."); } private void updateRepository(Vector<String> importURLs) throws RepositoryException,InterruptedException { RepositoryConnection con = owlse2.getConnection(); log.info("Repository connection has been opened."); updateSemanticRepository(con, importURLs); log.info("Closing repository connection."); con.close(); //close connection first } public void dumpRepository(RepositoryConnection con, String filename) { //export repository to an n-triple file File outrps = new File(filename); //hard copy of repository try { FileOutputStream myFileOutputStream = new FileOutputStream(outrps); NTriplesWriter myNTRiplesWriter = new NTriplesWriter(myFileOutputStream); //log.info("Dumping explicit statements (as Ntriples) to: " + outrps.getAbsoluteFile()); myNTRiplesWriter.startRDF(); myNTRiplesWriter.endRDF(); con.export(myNTRiplesWriter); log.info("Completed dumping explicit statements"); } catch (Throwable e) { log.warn(e.getMessage()); } } public void dumpRepository(String filename) throws RepositoryException { RepositoryConnection con = owlse2.getConnection(); log.info("Repository connection has been opened."); dumpRepository(con, filename); log.info("Closing repository connection."); con.close(); //close connection first } private void processContexts() throws RepositoryException { RepositoryConnection con = owlse2.getConnection(); log.info("Repository connection has been opened."); processContexts(con); log.info("Closing repository connection."); con.close(); //close connection first } private void processContexts(RepositoryConnection con) throws RepositoryException { /* ################################################### Looking at the code I concluded that this block was diagnostic cruft that seemed to be pretty useless. So I commented it out. We can put it back if needed. (ndp)*/ //retrieve context RepositoryResult<Resource> contextID = con.getContextIDs(); int contextTol = 0; if (!contextID.hasNext()) { log.warn("No Contexts found!"); } else { while (contextID.hasNext()) { String ctstr = contextID.next().toString(); log.info("Context: " + ctstr); owlse2.printLTMODContext(ctstr); contextTol++; } } contextID.close(); //needed to release resources log.info("Found " + contextTol + " Contexts"); /*########################################################*/ } private void extractCoverageDescrptionsFromRepository() throws RepositoryException { RepositoryConnection con = owlse2.getConnection(); log.info("Repository connection has been opened."); extractCoverageDescrptionsFromRepository(con); log.info("Closing repository connection."); con.close(); //close connection first } private void extractCoverageDescrptionsFromRepository(RepositoryConnection con) { //retrieve XML from the RDF store. log.info("Extracting CoverageDescriptions from repository."); buildDoc = new XMLfromRDF(con, "CoverageDescriptions", "http://www.opengis.net/wcs/1.1#CoverageDescription"); buildDoc.getXMLfromRDF("http://www.opengis.net/wcs/1.1#CoverageDescription"); //build a JDOM doc by querying against the RDF store } private void dumpCoverageDescriptionsDocument(String filename) { //print out the XML XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); /* ##################################################### Why is this being written out? Is this a diagnostic? purely for diagnostic purposes (HB Dec032009) Or is this file used later by some other part of the software? No. (HB Dec032009) Can we remove this??? Yes, once we are happy with the JDom Doc retrieval (HB Dec032009) */ try { File destinationFile = new File(filename); FileOutputStream fos = new FileOutputStream(destinationFile); outputter.output(buildDoc.getDoc(), fos); } catch (IOException e1) { e1.printStackTrace(); } /* ############################################## */ } public void destroy() { log.debug("destroy(): Attempting to aquire WriteLock from _catalogLock and _repositoryLock."); ReentrantReadWriteLock.WriteLock catLock = _catalogLock.writeLock(); ReentrantReadWriteLock.WriteLock reposLock = _repositoryLock.writeLock(); try { catLock.lock(); reposLock.lock(); log.debug("destroy(): WriteLocks Aquired."); setStopFlag(true); if(catalogUpdateThread!=null){ log.debug("Current thread '"+Thread.currentThread().getName()+"' Interrupting thread '"+catalogUpdateThread+"'"); catalogUpdateThread.interrupt(); } log.info("Shutting Down Semantic Repository."); owlse2.shutDown(); log.info("Semantic Repository Has Been Shutdown."); } catch (RepositoryException e) { log.error("destroy(): Failed to shutdown Semantic Repository."); } finally{ catLock.unlock(); reposLock.unlock(); log.debug("destroy(): Released WriteLock for _catalogLock and _repositoryLock."); } } private Vector<String> getRdfImports(Element config) { Vector<String> rdfImports = new Vector<String>(); Element e; String s; /** * Load individual dataset references */ Iterator i = config.getChildren("dataset").iterator(); String datasetURL; while (i.hasNext()) { e = (Element) i.next(); datasetURL = e.getTextNormalize(); if (!datasetURL.endsWith(".rdf")) { if (datasetURL.endsWith(".ddx") | datasetURL.endsWith(".dds") | datasetURL.endsWith(".das") ) { datasetURL = datasetURL.substring(0, datasetURL.lastIndexOf(".")); } datasetURL += ".rdf"; } rdfImports.add(datasetURL); log.info("Added dataset reference " + datasetURL + " to RDF imports list."); log.debug("<wcs:Identifier>"+this.getWcsIdString(datasetURL)+"</wcs:Identifier>"); } /** * Load THREDDS Catalog references. */ i = config.getChildren("ThreddsCatalog").iterator(); String catalogURL; boolean recurse; while (i.hasNext()) { e = (Element) i.next(); catalogURL = e.getTextNormalize(); recurse = false; s = e.getAttributeValue("recurse"); if (s != null && s.equalsIgnoreCase("true")) recurse = true; ThreddsCatalogUtil tcu = null; try { // Passing false means no caching but also no exception. // Maybe there's a better way to code the TCU ctor? tcu = new ThreddsCatalogUtil(); } catch (Exception e1) { log.debug("ThreddsCatalogUtil exception: " + e1.getMessage()); } Vector<String> datasetURLs = tcu.getDataAccessURLs(catalogURL, ThreddsCatalogUtil.SERVICE.OPeNDAP, recurse); for (String dataset : datasetURLs) { dataset += ".rdf"; rdfImports.add(dataset); log.info("Added dataset reference " + dataset + " to RDF imports list."); } } /** * Load RDF Imports */ i = config.getChildren("RdfImport").iterator(); while (i.hasNext()) { e = (Element) i.next(); s = e.getTextNormalize(); rdfImports.add(s); log.info("Added reference " + s + " to RDF imports list."); } return rdfImports; } private void ingestCatalog() throws Exception { log.info("Ingesting catalog from CoverageDescriptions Document built by the XMLFromRDF object..."); List<Element> cd = buildDoc.getDoc().getRootElement().getChildren(); Iterator<Element> i = cd.iterator(); HashMap<String, String> idltm = owlse2.getLMT(); String lastMDT = "nolastMDT"; while (i.hasNext()) { Element e = i.next(); List<Element> elist = e.getChildren(); Iterator<Element> j = elist.iterator(); while (j.hasNext()) { Element eID = j.next(); String idstr = eID.getName(); if (idstr.equalsIgnoreCase("Identifier")) { lastMDT = idltm.get(eID.getText()); String datetime = lastMDT.substring(0, 10) + " " + lastMDT.substring(11, 19) + " +0000"; DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); Date date = sdf.parse(datetime); log.debug("Date and Time: " + date.getTime()); ingestCoverageDescription(e, date.getTime()); //log.debug("element: "+ eID.getText()); //log.debug("lastMDT = "+ lastMDT); log.debug("Add element " + e.getName()); } } }//while(i.hasNext() _lastModified = -1; } public void ingestCoverageDescription(URL server, Element cde, long lastModified) throws Exception { } public void ingestCoverageDescription(Element cde, long lastModified) throws Exception { CoverageDescription cd; cd = new CoverageDescription(cde, lastModified); coverages.put(cd.getIdentifier(), cd); log.info("Ingested CoverageDescription: " + cd.getIdentifier()); } public boolean hasCoverage(String id) { log.debug("Looking for a coverage with ID: " + id); ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock(); try { lock.lock(); log.debug("_catalogLock ReadLock Acquired."); return coverages.containsKey(id); } finally { lock.unlock(); log.debug("_catalogLock ReadLock Released."); } } public Element getCoverageDescriptionElement(String id) { ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock(); try { lock.lock(); log.debug("_catalogLock ReadLock Acquired."); CoverageDescription cd = coverages.get(id); if(cd==null) return null; return cd.getElement(); } finally { lock.unlock(); log.debug("_catalogLock ReadLock Released."); } } public List<Element> getCoverageDescriptionElements() throws WcsException { throw new WcsException("getCoverageDescriptionElements() method Not Implemented", WcsException.NO_APPLICABLE_CODE); } public CoverageDescription getCoverageDescription(String id) { ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock(); try { lock.lock(); log.debug("_catalogLock ReadLock Acquired."); return coverages.get(id); } finally { lock.unlock(); log.debug("_catalogLock ReadLock Released."); } } public Element getCoverageSummaryElement(String id) throws WcsException { ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock(); try { lock.lock(); log.debug("_catalogLock ReadLock Acquired."); return coverages.get(id).getCoverageSummary(); } finally { lock.unlock(); log.debug("_catalogLock ReadLock Released."); } } public List<Element> getCoverageSummaryElements() throws WcsException { ArrayList<Element> coverageSummaries = new ArrayList<Element>(); Enumeration e; CoverageDescription cd; ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock(); try { lock.lock(); log.debug("_catalogLock ReadLock Acquired."); // Get all of the unique formats. e = coverages.elements(); while (e.hasMoreElements()) { cd = (CoverageDescription) e.nextElement(); coverageSummaries.add(cd.getCoverageSummary()); } } finally { lock.unlock(); log.debug("_catalogLock ReadLock Released."); } return coverageSummaries; } public List<Element> getSupportedFormatElements() { ArrayList<Element> supportedFormats = new ArrayList<Element>(); HashMap<String, Element> uniqueFormats = new HashMap<String, Element>(); Enumeration enm; Element e; Iterator i; CoverageDescription cd; ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock(); try { lock.lock(); log.debug("_catalogLock ReadLock Acquired."); // Get all of the unique formats. enm = coverages.elements(); while (enm.hasMoreElements()) { cd = (CoverageDescription) enm.nextElement(); i = cd.getSupportedFormatElements().iterator(); while (i.hasNext()) { e = (Element) i.next(); uniqueFormats.put(e.getTextTrim(), e); } } i = uniqueFormats.values().iterator(); while (i.hasNext()) { supportedFormats.add((Element) i.next()); } } finally { lock.unlock(); log.debug("_catalogLock ReadLock Released."); } return supportedFormats; } public List<Element> getSupportedCrsElements() { ArrayList<Element> supportedCRSs = new ArrayList<Element>(); HashMap<String, Element> uniqueCRSs = new HashMap<String, Element>(); Enumeration enm; Element e; Iterator i; CoverageDescription cd; ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock(); try { lock.lock(); log.debug("_catalogLock ReadLock Acquired."); // Get all of the unique formats. enm = coverages.elements(); while (enm.hasMoreElements()) { cd = (CoverageDescription) enm.nextElement(); i = cd.getSupportedCrsElements().iterator(); while (i.hasNext()) { e = (Element) i.next(); uniqueCRSs.put(e.getTextTrim(), e); } } i = uniqueCRSs.values().iterator(); while (i.hasNext()) { supportedCRSs.add((Element) i.next()); } } finally { lock.unlock(); log.debug("_catalogLock ReadLock Released."); } return supportedCRSs; } public String getLatitudeCoordinateDapId(String coverageId) { return null; } public String getLongitudeCoordinateDapId(String coverageId) { return null; } public String getElevationCoordinateDapId(String coverageId) { return null; } public String getTimeCoordinateDapId(String coverageId) { return null; } public long getLastModified() { return _lastModified; } public void setStopFlag(boolean flag){ stopWorking = flag; } public void updateCatalogCache() throws InterruptedException{ Thread thread = Thread.currentThread(); int biffCount = 0; if (!stopWorking && !thread.isInterrupted() ) { ReentrantReadWriteLock.WriteLock catlock = _catalogLock.writeLock(); ReentrantReadWriteLock.ReadLock repLock = _repositoryLock.readLock(); try { repLock.lock(); catlock.lock(); log.debug("_catalogLock WriteLock Acquired."); if (!stopWorking && !thread.isInterrupted()) { log.debug("Updating Catalog Cache."); try { coverageIDServer = getCoverageIDServerURL(); // for (String covID :coverageIDServer.keySet()){ //print all coverageID and server // log.info("CoverageID: " +covID); // Vector <String> covURLs=coverageIDServer.get(covID); // for (int i =0; i <covURLs.size(); i++) { // log.info("CoverageURL ("+i+"): " +covURLs.get(i)); // } // } } catch (RepositoryException e) { log.error("Caught RepositoryException in getCoverageIDServerURL: " + e.getMessage()); } catch (MalformedQueryException e) { log.error("Caught MalformedQueryException in getCoverageIDServerURL: " + e.getMessage()); } catch (QueryEvaluationException e) { log.error("Caught QueryEvaluationException in getCoverageIDServerURL: " + e.getMessage()); } addSupportedFormats(buildDoc.getRootElement()); ingestCatalog(); timeOfLastUpdate = new Date().getTime(); log.debug("Catalog Cache updated at "+ new Date(timeOfLastUpdate)); } } catch (Exception e) { log.error("updateCatalog() has a problem: " + e.getMessage() + " biffCount: " + (++biffCount)); e.printStackTrace(); } finally { catlock.unlock(); repLock.unlock(); log.debug("_catalogLock WriteLock Released."); } } if(thread.isInterrupted()) { log.warn("updateCatalog(): WARNING! Thread "+thread.getName()+" was interrupted!"); throw new InterruptedException(); } } public void updateCatalog() throws InterruptedException{ if(updateRepository()) updateCatalogCache(); } /** * * @return * @throws RepositoryException * @throws MalformedQueryException * @throws QueryEvaluationException */ private HashMap<String, Vector<String>> getCoverageIDServerURL() throws RepositoryException, MalformedQueryException, QueryEvaluationException { TupleQueryResult result = null; HashMap<String, Vector<String>> coverageIDServer = new HashMap<String, Vector<String>>(); String queryString = "SELECT coverageurl,coverageid " + "FROM " + "{} wcs:CoverageDescription {coverageurl} wcs:Identifier {coverageid} " + "USING NAMESPACE " + "wcs = <http://www.opengis.net/wcs/1.1#>"; RepositoryConnection con = owlse2.getConnection(); log.debug("query coverage ID and server URL: \n" + queryString); TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SERQL, queryString); result = tupleQuery.evaluate(); log.debug("Qresult: " + result.hasNext()); List<String> bindingNames = result.getBindingNames(); //log.debug(bindingNames.probeServletContext()); while (result.hasNext()) { BindingSet bindingSet = (BindingSet) result.next(); // log.debug(bindingSet.probeServletContext()); Vector<String> coverageURL = new Vector<String>(); if (bindingSet.getValue("coverageid") != null && bindingSet.getValue("coverageurl") != null) { Value valueOfcoverageid = (Value) bindingSet.getValue("coverageid"); Value valueOfcoverageurl = (Value) bindingSet.getValue("coverageurl"); coverageURL.addElement(valueOfcoverageurl.stringValue()); //log.debug("coverageid:"); //log.debug(valueOfcoverageid.stringValue()); //log.debug("coverageurl:"); log.debug(valueOfcoverageurl.stringValue()); if (coverageIDServer.containsKey(valueOfcoverageid.stringValue())) coverageIDServer.get(valueOfcoverageid.stringValue()).addElement(valueOfcoverageurl.stringValue()); else coverageIDServer.put(valueOfcoverageid.stringValue(), coverageURL); } } con.close(); return coverageIDServer; } public long getCatalogAge() { Date now = new Date(); return now.getTime() - timeOfLastUpdate; } public boolean updateRepository() throws InterruptedException { boolean success = false; int biffCount = 0; Thread thread = Thread.currentThread(); if (!stopWorking && !thread.isInterrupted() ) { ReentrantReadWriteLock.WriteLock lock = _repositoryLock.writeLock(); try { lock.lock(); repositoryUpdateActive.set(true); log.debug("_repositoryLock WriteLock Acquired."); if (!stopWorking && !thread.isInterrupted()) { log.debug("updateRepository(): Updating Semantic Repository."); log.debug("updateRepository(): Connecting to Repository..."); RepositoryConnection con = owlse2.getConnection(); log.info("updateRepository(): Repository connection has been opened."); if(thread.isInterrupted() || stopWorking ){ log.warn("updateRepository(): WARNING! Thread "+thread.getName()+" was interrupted!"); throw new InterruptedException("Thread.currentThread.isInterrupted() returned 'true'."); } log.debug("updateRepository(): Getting RDF imports."); Vector<String> importURLs = getRdfImports(_config); if(thread.isInterrupted() || stopWorking){ log.warn("updateRepository(): WARNING! Thread "+thread.getName()+" was interrupted!"); throw new InterruptedException("Thread.currentThread.isInterrupted() returned 'true'."); } log.debug("updateRepository(): Updating semantic repository."); updateSemanticRepository(con, importURLs); if(thread.isInterrupted() || stopWorking){ log.warn("updateRepository(): WARNING! Thread "+thread.getName()+" was interrupted!"); throw new InterruptedException("Thread.currentThread.isInterrupted() returned 'true'."); } String filename = cacheDirectory + "daprepository2"; log.debug("updateRepository(): Dumping Semantic Repository to: "+filename); dumpRepository(con, filename); if(thread.isInterrupted() || stopWorking){ log.warn("updateRepository(): WARNING! Thread "+thread.getName()+" was interrupted!"); throw new InterruptedException("Thread.currentThread.isInterrupted() returned 'true'."); } /* log.debug("updateRepository(): Processing Contexts..."); processContexts(con); if(thread.isInterrupted() || stopWorking){ log.warn("updateRepository(): WARNING! Thread "+thread.getName()+" was interrupted!"); throw new InterruptedException("Thread.currentThread.isInterrupted() returned 'true'."); } */ log.debug("Extracting CoverageDescriptions from the Repository."); extractCoverageDescrptionsFromRepository(con); if(thread.isInterrupted() || stopWorking){ log.warn("updateRepository(): WARNING! Thread "+thread.getName()+" was interrupted!"); throw new InterruptedException("Thread.currentThread.isInterrupted() returned 'true'."); } filename = cacheDirectory + "coverageXMLfromRDF.xml"; log.debug("updateRepository(): Dumping CoverageDescriptions Document to: "+filename); dumpCoverageDescriptionsDocument(filename); if(thread.isInterrupted() || stopWorking){ log.warn("updateRepository(): WARNING! Thread "+thread.getName()+" was interrupted!"); throw new InterruptedException("Thread.currentThread.isInterrupted() returned 'true'."); } log.info("updateRepository(): Closing repository!"); con.close(); //close connection first if(thread.isInterrupted() || stopWorking){ log.warn("updateRepository(): WARNING! Thread "+thread.getName()+" was interrupted!"); throw new InterruptedException("Thread.currentThread.isInterrupted() returned 'true'."); } success = true; repositoryUpdateActive.set(false); } } catch (InterruptedException e){ throw e; } catch (Exception e) { log.error("updateRepository() has a problem. Error Message: '" + e.getMessage() + "' biffCount: " + (++biffCount)); } finally { lock.unlock(); log.debug("_repositoryLock.WriteLock Released."); if(thread.isInterrupted()) throw new InterruptedException(); } } if(thread.isInterrupted()){ log.warn("updateRepository(): WARNING! Thread "+thread.getName()+" was interrupted!"); throw new InterruptedException(); } log.debug("updateRepository() returning: " + success); return success; } public void run() { log.info("************* STARTING CATALOG UPDATE THREAD."); try { log.info("************* CATALOG UPDATE THREAD sleeping for "+ firstUpdateDelay /1000.0 +" seconds."); Thread.sleep(firstUpdateDelay); } catch (InterruptedException e) { log.warn("Caught Interrupted Exception."); stopWorking = true; } int updateCounter = 0; long startTime, endTime; long elapsedTime, sleepTime; stopWorking = false; Thread thread = Thread.currentThread(); while (!stopWorking) { try { startTime = new Date().getTime(); updateCatalog(); endTime = new Date().getTime(); elapsedTime = (endTime - startTime); updateCounter++; log.debug("Completed catalog update "+ updateCounter + " in "+ elapsedTime/1000.0 + " seconds."); sleepTime = catalogUpdateInterval - elapsedTime; stopWorking = thread.isInterrupted(); if(!stopWorking && sleepTime >0) { log.debug("Catalog Update thread sleeping for "+ sleepTime/1000.0 + " seconds."); Thread.sleep(sleepTime); } } catch (InterruptedException e) { log.warn("Caught Interrupted Exception."); stopWorking = true; } } log.info("************* EXITING CATALOG UPDATE THREAD."); } private void addSupportedFormats(Element coverages) throws MalformedURLException { XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat()); Element coverageDescription; Element identifierElem; Iterator i; String coverageID; String msg; Vector<String> servers; i = coverages.getChildren().iterator(); while(i.hasNext()){ coverageDescription = (Element)i.next(); identifierElem = coverageDescription.getChild("Identifier",WCS.WCS_NS); coverageID = identifierElem.getTextTrim(); servers = coverageIDServer.get(coverageID); Vector<Element> supportedFormats = getWcsSupportedFormatElements(new URL(servers.get(0))); coverageDescription.addContent(supportedFormats); msg = "Adding supported formats to coverage "+coverageID+ "\n"+ "CoverageDescription Element: \n "+xmlo.outputString(coverageDescription)+"\n"+ "Coverage "+coverageID+" held at: \n"; for(String s: servers){ msg += " "+s+"\n"; } log.debug(msg); } } private Vector<Element> getWcsSupportedFormatElements(URL dapServerUrl){ Vector<Element> sfEs = new Vector<Element>(); String[] formats = ServerCapabilities.getSupportedFormatStrings(dapServerUrl); Element sf; for(String format: formats){ sf = new Element("SupportedFormat",WCS.WCS_NS); sf.setText(format); sfEs.add(sf); } return sfEs; } /** * Build a wcs:Identifier for the coverage dataset described by the datasetUrl. * * @param datasetUrl * @return A valid and unique to this service wcs:Identifier String for the coverage dataset */ public String getWcsIdString(String datasetUrl) { String wcsID="FAILED_TO_BUILD_WCS_ID"; try { int i; String serverURL, serverPrefix; URL dsu = new URL(datasetUrl); serverURL = getServerUrlString(dsu); if(serviceIDs.containsKey(serverURL)){ // get server prefix serverPrefix = serviceIDs.get(serverURL); } else { serverPrefix = "S"+ (serviceIDs.size()+1) + ""; // Generate service prefix // Store service prefix. serviceIDs.put(serverURL,serverPrefix); } // Build wcsID wcsID = serverPrefix + datasetUrl.substring(serverURL.length(),datasetUrl.length()); log.debug("wcsID: "+wcsID); if(!wcsIDs.containsKey(datasetUrl)){ // add wcs:Identifier to MAP wcsIDs.put(datasetUrl,wcsID); } } catch (MalformedURLException e) { log.error("Cannot Build wcs:Identifier from URL "+datasetUrl+" error msg: "+e.getMessage()); } return wcsID; } private String getServerUrlString(URL url) { String baseURL = null; String protocol = url.getProtocol(); if (protocol.equalsIgnoreCase("file")) { log.debug("Protocol is FILE."); } else if (protocol.equalsIgnoreCase("http")) { log.debug("Protocol is HTTP."); String host = url.getHost(); String path = url.getPath(); int port = url.getPort(); baseURL = protocol + "://" + host; if (port != -1) baseURL += ":" + port; } log.debug("ServerURL: " + baseURL); return baseURL; } }
olfs: Trying to fix persistence bug in the servlet.
src/opendap/semantics/IRISail/StaticRDFCatalog.java
olfs: Trying to fix persistence bug in the servlet.
Java
apache-2.0
d49eaf349631fcb69278380de38bd85da5ac17f3
0
MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim
package reb2sac; import java.io.*; import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import verification.AbstPane; import biomodelsim.*; import buttons.*; /** * This is the Nary_Run class. It creates a GUI for input in the nary * abstraction. It implements the ActionListener class. This allows the Nary_Run * GUI to perform actions when buttons are pressed. * * @author Curtis Madsen */ public class Nary_Run implements ActionListener, Runnable { private JFrame naryFrame; // Frame for nary abstraction private JButton naryRun; // The run button for nary abstraction private JButton naryClose; // The close button for nary abstraction private JTextField stopRate; // Text field for nary abstraction private JList finalState; // List for final state private Object[] finalStates = new Object[0]; // List of final states private JComboBox stopEnabled; // Combo box for Nary Abstraction private ArrayList<JTextField> inhib; // Text fields for inhibition levels private ArrayList<JList> consLevel; // Lists for concentration levels private ArrayList<String> getSpeciesProps; // Species in properties file private JButton finalAdd, finalRemove; // Buttons for altering final state /* * Text fields for species properties */ private ArrayList<JTextField> texts; private ArrayList<Object[]> conLevel; // Lists for concentration levels private JComboBox highLow, speci; // Combo Boxes for final states private JTextField amountTerm; // Amount for termination condition /* * Radio Buttons for termination conditions */ private JRadioButton ge, gt, eq, le, lt; private JComboBox simulators; // Combo Box for possible simulators private String filename; // name of sbml file private String[] getFilename; // array of filename private JRadioButton sbml, dot, xhtml, lhpn; // Radio Buttons output option /* * Radio Buttons that represent the different abstractions */ private JRadioButton nary, ODE, monteCarlo; /* * Data used for monteCarlo abstraction */ private double timeLimit, printInterval, minTimeStep, timeStep; private int run;// Data used for monteCarlo abstraction private long rndSeed;// Data used for monteCarlo abstraction /* * Data used for monteCarlo abstraction */ private String outDir, printer_id, printer_track_quantity; /* * terminations and interesting species */ private String[] termCond, intSpecies; private double rap1, rap2, qss; // advanced options private int con; // advanced options private ArrayList<Integer> counts; // counts of con levels private Log log; // the log private JCheckBox usingSSA; // check box for ssa private String ssaFile; // ssa filename private BioSim biomodelsim; // tstubd gui private JTabbedPane simTab; // the simulation tab private String root; private String separator; private String useInterval; private String direct; private String modelFile; private JRadioButton abstraction; private AbstPane abstPane; /** * This constructs a new Nary_Run object. This object is a GUI that contains * input fields for the nary abstraction. This constructor initializes the * member variables and creates the nary frame. */ public Nary_Run(Component component, JTextField amountTerm, JRadioButton ge, JRadioButton gt, JRadioButton eq, JRadioButton lt, JRadioButton le, JComboBox simulators, String[] getFilename, String filename, JRadioButton sbml, JRadioButton dot, JRadioButton xhtml, JRadioButton lhpn, JRadioButton nary, JRadioButton ODE, JRadioButton monteCarlo, double timeLimit, String useInterval, double printInterval, double minTimeStep, double timeStep, String outDir, long rndSeed, int run, String printer_id, String printer_track_quantity, String[] termCond, String[] intSpecies, double rap1, double rap2, double qss, int con, Log log, JCheckBox usingSSA, String ssaFile, BioSim biomodelsim, JTabbedPane simTab, String root, String direct, String modelFile, JRadioButton abstraction, AbstPane abstPane) { if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } // intitializes the member variables this.root = root; this.rap1 = rap1; this.rap2 = rap2; this.qss = qss; this.con = con; this.termCond = termCond; this.intSpecies = intSpecies; this.amountTerm = amountTerm; this.ge = ge; this.gt = gt; this.eq = eq; this.le = le; this.lt = lt; this.timeLimit = timeLimit; this.printInterval = printInterval; this.minTimeStep = minTimeStep; this.timeStep = timeStep; this.outDir = outDir; this.rndSeed = rndSeed; this.run = run; this.printer_id = printer_id; this.printer_track_quantity = printer_track_quantity; this.simulators = simulators; this.getFilename = getFilename; this.filename = filename; this.dot = dot; this.sbml = sbml; this.xhtml = xhtml; this.lhpn = lhpn; this.nary = nary; this.monteCarlo = monteCarlo; this.ODE = ODE; this.log = log; this.usingSSA = usingSSA; this.ssaFile = ssaFile; this.biomodelsim = biomodelsim; this.simTab = simTab; this.useInterval = useInterval; this.direct = direct; this.modelFile = modelFile; this.abstPane = abstPane; this.abstraction = abstraction; // creates the nary frame and adds a window listener naryFrame = new JFrame("Nary Properties"); WindowListener w = new WindowListener() { public void windowClosing(WindowEvent arg0) { naryFrame.dispose(); } public void windowOpened(WindowEvent arg0) { } public void windowClosed(WindowEvent arg0) { } public void windowIconified(WindowEvent arg0) { } public void windowDeiconified(WindowEvent arg0) { } public void windowActivated(WindowEvent arg0) { } public void windowDeactivated(WindowEvent arg0) { } }; naryFrame.addWindowListener(w); // creates the input fields for the nary abstraction JPanel naryInput = new JPanel(new GridLayout(2, 2)); JLabel stopEnabledLabel = new JLabel("Analysis Stop Enabled:"); String choice[] = new String[2]; choice[0] = "false"; choice[1] = "true"; stopEnabled = new JComboBox(choice); JLabel stopRateLabel = new JLabel("Analysis Stop Rate:"); stopRate = new JTextField(); stopRate.setText("0.0005"); // creates the final state JList JLabel finalStateLabel = new JLabel("Final State:"); finalState = new JList(); JScrollPane finalScroll = new JScrollPane(); finalScroll.setPreferredSize(new Dimension(260, 100)); finalScroll.setViewportView(finalState); JPanel addRemove = new JPanel(); Object[] high = { "high", "low" }; highLow = new JComboBox(high); finalAdd = new JButton("Add"); finalRemove = new JButton("Remove"); finalAdd.addActionListener(this); finalRemove.addActionListener(this); // adds the nary input fields to a panel naryInput.add(stopEnabledLabel); naryInput.add(stopEnabled); naryInput.add(stopRateLabel); naryInput.add(stopRate); JPanel finalPanel = new JPanel(); finalPanel.add(finalStateLabel); finalPanel.add(finalScroll); JPanel naryInputPanel = new JPanel(new BorderLayout()); naryInputPanel.add(naryInput, "North"); naryInputPanel.add(finalPanel, "Center"); naryInputPanel.add(addRemove, "South"); // reads in the species properties to determine which species to use Properties naryProps = new Properties(); try { FileInputStream load = new FileInputStream(new File(outDir + separator + "species.properties")); naryProps.load(load); load.close(); FileOutputStream store = new FileOutputStream(new File(outDir + separator + "species.properties")); naryProps.store(store, ""); store.close(); naryProps = new Properties(); new File("species.properties").delete(); load = new FileInputStream(new File(outDir + separator + "species.properties")); naryProps.load(load); load.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(component, "Properties File Not Found!", "File Not Found", JOptionPane.ERROR_MESSAGE); } Iterator<Object> iter = naryProps.keySet().iterator(); getSpeciesProps = new ArrayList<String>(); while (iter.hasNext()) { String next = (String) iter.next(); if (next.contains("specification")) { String[] get = next.split("e"); getSpeciesProps.add(get[get.length - 1].substring(1, get[get.length - 1].length())); } } // puts the species into the combo box for the final state speci = new JComboBox(getSpeciesProps.toArray()); addRemove.add(highLow); addRemove.add(speci); addRemove.add(finalAdd); addRemove.add(finalRemove); // creates the species properties input fields ArrayList<JPanel> specProps = new ArrayList<JPanel>(); texts = new ArrayList<JTextField>(); inhib = new ArrayList<JTextField>(); consLevel = new ArrayList<JList>(); conLevel = new ArrayList<Object[]>(); counts = new ArrayList<Integer>(); for (int i = 0; i < getSpeciesProps.size(); i++) { JPanel newPanel1 = new JPanel(new GridLayout(1, 2)); JPanel newPanel2 = new JPanel(new GridLayout(1, 2)); JPanel label = new JPanel(); label.add(new JLabel(getSpeciesProps.get(i) + " Absolute Inhibition Threshold:")); newPanel1.add(label); JPanel text = new JPanel(); inhib.add(new JTextField()); inhib.get(i).setPreferredSize(new Dimension(260, 20)); inhib.get(i).setText("<<none>>"); text.add(inhib.get(i)); newPanel1.add(text); JPanel otherLabel = new JPanel(); otherLabel.add(new JLabel(getSpeciesProps.get(i) + " Concentration Level:")); newPanel2.add(otherLabel); consLevel.add(new JList()); conLevel.add(new Object[0]); iter = naryProps.keySet().iterator(); ArrayList<String> get = new ArrayList<String>(); int count = 0; while (iter.hasNext()) { String next = (String) iter.next(); if (next.contains("concentration.level." + getSpeciesProps.get(i) + ".")) { get.add(naryProps.getProperty(next)); count++; } } counts.add(count); int in; for (int out = 1; out < get.size(); out++) { if (!get.get(out).equals("<<none>>")) { double temp = Double.parseDouble(get.get(out)); in = out; while (in > 0 && Double.parseDouble(get.get(in - 1)) >= temp) { get.set(in, get.get(in - 1)); --in; } get.set(in, temp + ""); } } consLevel.get(i).setListData(get.toArray()); conLevel.set(i, get.toArray()); JScrollPane scroll = new JScrollPane(); scroll.setPreferredSize(new Dimension(260, 100)); scroll.setViewportView(consLevel.get(i)); JPanel area = new JPanel(); area.add(scroll); newPanel2.add(area); JPanel addAndRemove = new JPanel(); JTextField adding = new JTextField(15); texts.add(adding); JButton Add = new JButton("Add"); JButton Remove = new JButton("Remove"); Add.addActionListener(this); Add.setActionCommand("Add" + i); Remove.addActionListener(this); Remove.setActionCommand("Remove" + i); addAndRemove.add(adding); addAndRemove.add(Add); addAndRemove.add(Remove); JPanel newnewPanel = new JPanel(new BorderLayout()); newnewPanel.add(newPanel1, "North"); newnewPanel.add(newPanel2, "Center"); newnewPanel.add(addAndRemove, "South"); specProps.add(newnewPanel); } // creates the nary run and close buttons naryRun = new JButton("Run Nary"); naryClose = new JButton("Cancel"); naryRun.addActionListener(this); naryClose.addActionListener(this); JPanel naryRunPanel = new JPanel(); naryRunPanel.add(naryRun); naryRunPanel.add(naryClose); // creates tabs for all the nary options and all the species JTabbedPane naryTabs = new JTabbedPane(); naryTabs.addTab("Nary Properties", naryInputPanel); for (int i = 0; i < getSpeciesProps.size(); i++) { naryTabs.addTab(getSpeciesProps.get(i) + " Properties", specProps.get(i)); } // adds the tabs and the run button to the main panel JPanel naryPanel = new JPanel(new BorderLayout()); naryPanel.add(naryTabs, "Center"); naryPanel.add(naryRunPanel, "South"); // Packs the nary frame and displays it naryFrame.setContentPane(naryPanel); naryFrame.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = naryFrame.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; naryFrame.setLocation(x, y); naryFrame.setResizable(false); naryFrame.setVisible(true); } /** * This method performs different functions depending on what buttons are * pushed and what input fields contain data. */ public void actionPerformed(ActionEvent e) { // if the nary run button is clicked if (e.getSource() == naryRun) { new Thread(this).start(); } // if the nary close button is clicked if (e.getSource() == naryClose) { naryFrame.dispose(); } // if the add button for the final states is clicked else if (e.getSource() == finalAdd) { JList add = new JList(); Object[] adding = { highLow.getSelectedItem() + "." + speci.getSelectedItem() }; add.setListData(adding); add.setSelectedIndex(0); finalStates = Buttons.add(finalStates, finalState, add, false, amountTerm, ge, gt, eq, lt, le, naryFrame); } // if the remove button for the final states is clicked else if (e.getSource() == finalRemove) { Buttons.remove(finalState, finalStates); } // if the add or remove button for the species properties is clicked else { // if the add button for the species properties is clicked if (e.getActionCommand().contains("Add")) { int number = Integer.parseInt(e.getActionCommand().substring(3, e.getActionCommand().length())); try { double get = Double.parseDouble(texts.get(number).getText().trim()); if (get < 0) { JOptionPane.showMessageDialog(naryFrame, "Concentration Levels Must Be Positive Real Numbers.", "Error", JOptionPane.ERROR_MESSAGE); } else { JList add = new JList(); Object[] adding = { "" + get }; add.setListData(adding); add.setSelectedIndex(0); Object[] sort = Buttons.add(conLevel.get(number), consLevel.get(number), add, false, amountTerm, ge, gt, eq, lt, le, naryFrame); int in; for (int out = 1; out < sort.length; out++) { double temp = Double.parseDouble((String) sort[out]); in = out; while (in > 0 && Double.parseDouble((String) sort[in - 1]) >= temp) { sort[in] = sort[in - 1]; --in; } sort[in] = temp + ""; } conLevel.set(number, sort); } } catch (Exception e1) { JOptionPane.showMessageDialog(naryFrame, "Concentration Levels Must Be Positive Real Numbers.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the remove button for the species properties is clicked else if (e.getActionCommand().contains("Remove")) { int number = Integer.parseInt(e.getActionCommand().substring(6, e.getActionCommand().length())); Buttons.remove(consLevel.get(number), conLevel.get(number)); } } } /** * If the nary run button is pressed, this method starts a new thread for * the nary abstraction. */ public void run() { naryFrame.dispose(); final JButton naryCancel = new JButton("Cancel Nary"); final JFrame running = new JFrame("Running..."); WindowListener w = new WindowListener() { public void windowClosing(WindowEvent arg0) { naryCancel.doClick(); running.dispose(); } public void windowOpened(WindowEvent arg0) { } public void windowClosed(WindowEvent arg0) { } public void windowIconified(WindowEvent arg0) { } public void windowDeiconified(WindowEvent arg0) { } public void windowActivated(WindowEvent arg0) { } public void windowDeactivated(WindowEvent arg0) { } }; running.addWindowListener(w); JPanel text = new JPanel(); JPanel progBar = new JPanel(); JPanel button = new JPanel(); JPanel all = new JPanel(new BorderLayout()); JLabel label = new JLabel("Progress"); JProgressBar progress = new JProgressBar(0, run); progress.setStringPainted(true); // progress.setString(""); // progress.setIndeterminate(true); progress.setValue(0); text.add(label); progBar.add(progress); button.add(naryCancel); all.add(text, "North"); all.add(progBar, "Center"); all.add(button, "South"); running.setContentPane(all); running.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = running.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; running.setLocation(x, y); running.setVisible(true); running.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); String sim = (String) simulators.getSelectedItem(); String stopE = (String) stopEnabled.getSelectedItem(); double stopR = 0.0005; try { stopR = Double.parseDouble(stopRate.getText().trim()); } catch (Exception e1) { JOptionPane.showMessageDialog(naryFrame, "Must Enter A Real Number Into The Analysis Stop Rate Field.", "Error", JOptionPane.ERROR_MESSAGE); return; } String[] finalS = Buttons.getList(finalStates, finalState); Run runProgram = new Run(null); naryCancel.addActionListener(runProgram); runProgram.createNaryProperties(timeLimit, useInterval, printInterval, minTimeStep, timeStep, outDir, rndSeed, run, printer_id, printer_track_quantity, getFilename, naryFrame, filename, monteCarlo, stopE, stopR, finalS, inhib, consLevel, getSpeciesProps, conLevel, termCond, intSpecies, rap1, rap2, qss, con, counts, usingSSA, ssaFile); if (monteCarlo.isSelected()) { File[] files = new File(outDir).listFiles(); for (File f : files) { if (f.getName().contains("run-")) { f.delete(); } } } runProgram.execute(filename, sbml, dot, xhtml, lhpn, naryFrame, ODE, monteCarlo, sim, printer_id, printer_track_quantity, outDir, nary, 2, intSpecies, log, usingSSA, ssaFile, biomodelsim, simTab, root, progress, "", null, direct, timeLimit, timeLimit * run, modelFile, abstPane, abstraction, null); running.setCursor(null); running.dispose(); naryCancel.removeActionListener(runProgram); } }
gui/src/reb2sac/Nary_Run.java
package reb2sac; import java.io.*; import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import verification.AbstPane; import biomodelsim.*; import buttons.*; /** * This is the Nary_Run class. It creates a GUI for input in the nary * abstraction. It implements the ActionListener class. This allows the Nary_Run * GUI to perform actions when buttons are pressed. * * @author Curtis Madsen */ public class Nary_Run implements ActionListener, Runnable { private JFrame naryFrame; // Frame for nary abstraction private JButton naryRun; // The run button for nary abstraction private JButton naryClose; // The close button for nary abstraction private JTextField stopRate; // Text field for nary abstraction private JList finalState; // List for final state private Object[] finalStates = new Object[0]; // List of final states private JComboBox stopEnabled; // Combo box for Nary Abstraction private ArrayList<JTextField> inhib; // Text fields for inhibition levels private ArrayList<JList> consLevel; // Lists for concentration levels private ArrayList<String> getSpeciesProps; // Species in properties file private JButton finalAdd, finalRemove; // Buttons for altering final state /* * Text fields for species properties */ private ArrayList<JTextField> texts; private ArrayList<Object[]> conLevel; // Lists for concentration levels private JComboBox highLow, speci; // Combo Boxes for final states private JTextField amountTerm; // Amount for termination condition /* * Radio Buttons for termination conditions */ private JRadioButton ge, gt, eq, le, lt; private JComboBox simulators; // Combo Box for possible simulators private String filename; // name of sbml file private String[] getFilename; // array of filename private JRadioButton sbml, dot, xhtml, lhpn; // Radio Buttons output option /* * Radio Buttons that represent the different abstractions */ private JRadioButton nary, ODE, monteCarlo; /* * Data used for monteCarlo abstraction */ private double timeLimit, printInterval, minTimeStep, timeStep; private int run;// Data used for monteCarlo abstraction private long rndSeed;// Data used for monteCarlo abstraction /* * Data used for monteCarlo abstraction */ private String outDir, printer_id, printer_track_quantity; /* * terminations and interesting species */ private String[] termCond, intSpecies; private double rap1, rap2, qss; // advanced options private int con; // advanced options private ArrayList<Integer> counts; // counts of con levels private Log log; // the log private JCheckBox usingSSA; // check box for ssa private String ssaFile; // ssa filename private BioSim biomodelsim; // tstubd gui private JTabbedPane simTab; // the simulation tab private String root; private String separator; private String useInterval; private String direct; private String modelFile; private JRadioButton abstraction; private AbstPane abstPane; /** * This constructs a new Nary_Run object. This object is a GUI that contains * input fields for the nary abstraction. This constructor initializes the * member variables and creates the nary frame. */ public Nary_Run(Component component, JTextField amountTerm, JRadioButton ge, JRadioButton gt, JRadioButton eq, JRadioButton lt, JRadioButton le, JComboBox simulators, String[] getFilename, String filename, JRadioButton sbml, JRadioButton dot, JRadioButton xhtml, JRadioButton lhpn, JRadioButton nary, JRadioButton ODE, JRadioButton monteCarlo, double timeLimit, String useInterval, double printInterval, double minTimeStep, double timeStep, String outDir, long rndSeed, int run, String printer_id, String printer_track_quantity, String[] termCond, String[] intSpecies, double rap1, double rap2, double qss, int con, Log log, JCheckBox usingSSA, String ssaFile, BioSim biomodelsim, JTabbedPane simTab, String root, String direct, String modelFile, JRadioButton abstraction, AbstPane abstPane) { if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } // intitializes the member variables this.root = root; this.rap1 = rap1; this.rap2 = rap2; this.qss = qss; this.con = con; this.termCond = termCond; this.intSpecies = intSpecies; this.amountTerm = amountTerm; this.ge = ge; this.gt = gt; this.eq = eq; this.le = le; this.lt = lt; this.timeLimit = timeLimit; this.printInterval = printInterval; this.minTimeStep = minTimeStep; this.timeStep = timeStep; this.outDir = outDir; this.rndSeed = rndSeed; this.run = run; this.printer_id = printer_id; this.printer_track_quantity = printer_track_quantity; this.simulators = simulators; this.getFilename = getFilename; this.filename = filename; this.dot = dot; this.sbml = sbml; this.xhtml = xhtml; this.lhpn = lhpn; this.nary = nary; this.monteCarlo = monteCarlo; this.ODE = ODE; this.log = log; this.usingSSA = usingSSA; this.ssaFile = ssaFile; this.biomodelsim = biomodelsim; this.simTab = simTab; this.useInterval = useInterval; this.direct = direct; this.modelFile = modelFile; this.abstPane = abstPane; this.abstraction = abstraction; // creates the nary frame and adds a window listener naryFrame = new JFrame("Nary Properties"); WindowListener w = new WindowListener() { public void windowClosing(WindowEvent arg0) { naryFrame.dispose(); } public void windowOpened(WindowEvent arg0) { } public void windowClosed(WindowEvent arg0) { } public void windowIconified(WindowEvent arg0) { } public void windowDeiconified(WindowEvent arg0) { } public void windowActivated(WindowEvent arg0) { } public void windowDeactivated(WindowEvent arg0) { } }; naryFrame.addWindowListener(w); // creates the input fields for the nary abstraction JPanel naryInput = new JPanel(new GridLayout(2, 2)); JLabel stopEnabledLabel = new JLabel("Analysis Stop Enabled:"); String choice[] = new String[2]; choice[0] = "false"; choice[1] = "true"; stopEnabled = new JComboBox(choice); JLabel stopRateLabel = new JLabel("Analysis Stop Rate:"); stopRate = new JTextField(); stopRate.setText("0.0005"); // creates the final state JList JLabel finalStateLabel = new JLabel("Final State:"); finalState = new JList(); JScrollPane finalScroll = new JScrollPane(); finalScroll.setPreferredSize(new Dimension(260, 100)); finalScroll.setViewportView(finalState); JPanel addRemove = new JPanel(); Object[] high = { "high", "low" }; highLow = new JComboBox(high); finalAdd = new JButton("Add"); finalRemove = new JButton("Remove"); finalAdd.addActionListener(this); finalRemove.addActionListener(this); // adds the nary input fields to a panel naryInput.add(stopEnabledLabel); naryInput.add(stopEnabled); naryInput.add(stopRateLabel); naryInput.add(stopRate); JPanel finalPanel = new JPanel(); finalPanel.add(finalStateLabel); finalPanel.add(finalScroll); JPanel naryInputPanel = new JPanel(new BorderLayout()); naryInputPanel.add(naryInput, "North"); naryInputPanel.add(finalPanel, "Center"); naryInputPanel.add(addRemove, "South"); // reads in the species properties to determine which species to use Properties naryProps = new Properties(); try { FileInputStream load = new FileInputStream(new File(outDir + separator + "species.properties")); naryProps.load(load); load.close(); FileOutputStream store = new FileOutputStream(new File(outDir + separator + "species.properties")); naryProps.store(store, ""); store.close(); naryProps = new Properties(); new File("species.properties").delete(); load = new FileInputStream(new File(outDir + separator + "species.properties")); naryProps.load(load); load.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(component, "Properties File Not Found!", "File Not Found", JOptionPane.ERROR_MESSAGE); } Iterator<Object> iter = naryProps.keySet().iterator(); getSpeciesProps = new ArrayList<String>(); while (iter.hasNext()) { String next = (String) iter.next(); if (next.contains("specification")) { String[] get = next.split("e"); getSpeciesProps.add(get[get.length - 1].substring(1, get[get.length - 1].length())); } } // puts the species into the combo box for the final state speci = new JComboBox(getSpeciesProps.toArray()); addRemove.add(highLow); addRemove.add(speci); addRemove.add(finalAdd); addRemove.add(finalRemove); // creates the species properties input fields ArrayList<JPanel> specProps = new ArrayList<JPanel>(); texts = new ArrayList<JTextField>(); inhib = new ArrayList<JTextField>(); consLevel = new ArrayList<JList>(); conLevel = new ArrayList<Object[]>(); counts = new ArrayList<Integer>(); for (int i = 0; i < getSpeciesProps.size(); i++) { JPanel newPanel1 = new JPanel(new GridLayout(1, 2)); JPanel newPanel2 = new JPanel(new GridLayout(1, 2)); JPanel label = new JPanel(); label.add(new JLabel(getSpeciesProps.get(i) + " Absolute Inhibition Threshold:")); newPanel1.add(label); JPanel text = new JPanel(); inhib.add(new JTextField()); inhib.get(i).setPreferredSize(new Dimension(260, 20)); inhib.get(i).setText("<<none>>"); text.add(inhib.get(i)); newPanel1.add(text); JPanel otherLabel = new JPanel(); otherLabel.add(new JLabel(getSpeciesProps.get(i) + " Concentration Level:")); newPanel2.add(otherLabel); consLevel.add(new JList()); conLevel.add(new Object[0]); iter = naryProps.keySet().iterator(); ArrayList<String> get = new ArrayList<String>(); int count = 0; while (iter.hasNext()) { String next = (String) iter.next(); if (next.contains("concentration.level." + getSpeciesProps.get(i) + ".")) { get.add(naryProps.getProperty(next)); count++; } } counts.add(count); int in; for (int out = 1; out < get.size(); out++) { if (!get.get(out).equals("<<none>>")) { double temp = Double.parseDouble(get.get(out)); in = out; while (in > 0 && Double.parseDouble(get.get(in - 1)) >= temp) { get.set(in, get.get(in - 1)); --in; } get.set(in, temp + ""); } } consLevel.get(i).setListData(get.toArray()); conLevel.set(i, get.toArray()); JScrollPane scroll = new JScrollPane(); scroll.setPreferredSize(new Dimension(260, 100)); scroll.setViewportView(consLevel.get(i)); JPanel area = new JPanel(); area.add(scroll); newPanel2.add(area); JPanel addAndRemove = new JPanel(); JTextField adding = new JTextField(15); texts.add(adding); JButton Add = new JButton("Add"); JButton Remove = new JButton("Remove"); Add.addActionListener(this); Add.setActionCommand("Add" + i); Remove.addActionListener(this); Remove.setActionCommand("Remove" + i); addAndRemove.add(adding); addAndRemove.add(Add); addAndRemove.add(Remove); JPanel newnewPanel = new JPanel(new BorderLayout()); newnewPanel.add(newPanel1, "North"); newnewPanel.add(newPanel2, "Center"); newnewPanel.add(addAndRemove, "South"); specProps.add(newnewPanel); } // creates the nary run and close buttons naryRun = new JButton("Run Nary"); naryClose = new JButton("Cancel"); naryRun.addActionListener(this); naryClose.addActionListener(this); JPanel naryRunPanel = new JPanel(); naryRunPanel.add(naryRun); naryRunPanel.add(naryClose); // creates tabs for all the nary options and all the species JTabbedPane naryTabs = new JTabbedPane(); naryTabs.addTab("Nary Properties", naryInputPanel); for (int i = 0; i < getSpeciesProps.size(); i++) { naryTabs.addTab(getSpeciesProps.get(i) + " Properties", specProps.get(i)); } // adds the tabs and the run button to the main panel JPanel naryPanel = new JPanel(new BorderLayout()); naryPanel.add(naryTabs, "Center"); naryPanel.add(naryRunPanel, "South"); // Packs the nary frame and displays it naryFrame.setContentPane(naryPanel); naryFrame.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = naryFrame.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; naryFrame.setLocation(x, y); naryFrame.setResizable(false); naryFrame.setVisible(true); } /** * This method performs different functions depending on what buttons are * pushed and what input fields contain data. */ public void actionPerformed(ActionEvent e) { // if the nary run button is clicked if (e.getSource() == naryRun) { new Thread(this).start(); } // if the nary close button is clicked if (e.getSource() == naryClose) { naryFrame.dispose(); } // if the add button for the final states is clicked else if (e.getSource() == finalAdd) { JList add = new JList(); Object[] adding = { highLow.getSelectedItem() + "." + speci.getSelectedItem() }; add.setListData(adding); add.setSelectedIndex(0); finalStates = Buttons.add(finalStates, finalState, add, false, amountTerm, ge, gt, eq, lt, le, naryFrame); } // if the remove button for the final states is clicked else if (e.getSource() == finalRemove) { Buttons.remove(finalState, finalStates); } // if the add or remove button for the species properties is clicked else { // if the add button for the species properties is clicked if (e.getActionCommand().contains("Add")) { int number = Integer.parseInt(e.getActionCommand().substring(3, e.getActionCommand().length())); try { double get = Double.parseDouble(texts.get(number).getText().trim()); if (get < 0) { JOptionPane.showMessageDialog(naryFrame, "Concentration Levels Must Be Positive Real Numbers.", "Error", JOptionPane.ERROR_MESSAGE); } else { JList add = new JList(); Object[] adding = { "" + get }; add.setListData(adding); add.setSelectedIndex(0); Object[] sort = Buttons.add(conLevel.get(number), consLevel.get(number), add, false, amountTerm, ge, gt, eq, lt, le, naryFrame); int in; for (int out = 1; out < sort.length; out++) { double temp = Double.parseDouble((String) sort[out]); in = out; while (in > 0 && Double.parseDouble((String) sort[in - 1]) >= temp) { sort[in] = sort[in - 1]; --in; } sort[in] = temp + ""; } conLevel.set(number, sort); } } catch (Exception e1) { JOptionPane.showMessageDialog(naryFrame, "Concentration Levels Must Be Positive Real Numbers.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the remove button for the species properties is clicked else if (e.getActionCommand().contains("Remove")) { int number = Integer.parseInt(e.getActionCommand().substring(6, e.getActionCommand().length())); Buttons.remove(consLevel.get(number), conLevel.get(number)); } } } /** * If the nary run button is pressed, this method starts a new thread for * the nary abstraction. */ public void run() { naryFrame.dispose(); final JButton naryCancel = new JButton("Cancel Nary"); final JFrame running = new JFrame("Running..."); WindowListener w = new WindowListener() { public void windowClosing(WindowEvent arg0) { naryCancel.doClick(); running.dispose(); } public void windowOpened(WindowEvent arg0) { } public void windowClosed(WindowEvent arg0) { } public void windowIconified(WindowEvent arg0) { } public void windowDeiconified(WindowEvent arg0) { } public void windowActivated(WindowEvent arg0) { } public void windowDeactivated(WindowEvent arg0) { } }; running.addWindowListener(w); JPanel text = new JPanel(); JPanel progBar = new JPanel(); JPanel button = new JPanel(); JPanel all = new JPanel(new BorderLayout()); JLabel label = new JLabel("Progress"); JProgressBar progress = new JProgressBar(0, run); progress.setStringPainted(true); // progress.setString(""); // progress.setIndeterminate(true); progress.setValue(0); text.add(label); progBar.add(progress); button.add(naryCancel); all.add(text, "North"); all.add(progBar, "Center"); all.add(button, "South"); running.setContentPane(all); running.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = running.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; running.setLocation(x, y); running.setVisible(true); running.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); String sim = (String) simulators.getSelectedItem(); String stopE = (String) stopEnabled.getSelectedItem(); double stopR = 0.0005; try { stopR = Double.parseDouble(stopRate.getText().trim()); } catch (Exception e1) { JOptionPane.showMessageDialog(naryFrame, "Must Enter A Real Number Into The Analysis Stop Rate Field.", "Error", JOptionPane.ERROR_MESSAGE); return; } String[] finalS = Buttons.getList(finalStates, finalState); Run runProgram = new Run(null); naryCancel.addActionListener(runProgram); runProgram.createNaryProperties(timeLimit, useInterval, printInterval, minTimeStep, timeStep, outDir, rndSeed, run, printer_id, printer_track_quantity, getFilename, naryFrame, filename, monteCarlo, stopE, stopR, finalS, inhib, consLevel, getSpeciesProps, conLevel, termCond, intSpecies, rap1, rap2, qss, con, counts, usingSSA, ssaFile); if (monteCarlo.isSelected()) { File[] files = new File(outDir).listFiles(); for (File f : files) { if (f.getName().contains("run-")) { f.delete(); } } } runProgram.execute(filename, sbml, dot, xhtml, lhpn, naryFrame, ODE, monteCarlo, sim, printer_id, printer_track_quantity, outDir, nary, 2, intSpecies, log, usingSSA, ssaFile, biomodelsim, simTab, root, progress, "", null, direct, timeLimit, timeLimit * run, modelFile, abstPane, abstraction); running.setCursor(null); running.dispose(); naryCancel.removeActionListener(runProgram); } }
Added the last argument passed to runProgram.execute().
gui/src/reb2sac/Nary_Run.java
Added the last argument passed to runProgram.execute().
Java
apache-2.0
d1df753448b91c47191f3cd2f33d5e39447ad6e3
0
statsbiblioteket/doms-server
/* * $Id$ * $Revision$ * $Date$ * $Author$ * * The DOMS project. * Copyright (C) 2007-2010 The State and University Library * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package dk.statsbiblioteket.doms.central.connectors.fedora; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import dk.statsbiblioteket.doms.central.connectors.BackendInvalidCredsException; import dk.statsbiblioteket.doms.central.connectors.BackendInvalidResourceException; import dk.statsbiblioteket.doms.central.connectors.BackendMethodFailedException; import dk.statsbiblioteket.doms.central.connectors.Connector; import dk.statsbiblioteket.doms.central.connectors.fedora.generated.DatastreamProfileType; import dk.statsbiblioteket.doms.central.connectors.fedora.generated.DatastreamType; import dk.statsbiblioteket.doms.central.connectors.fedora.generated.ObjectDatastreams; import dk.statsbiblioteket.doms.central.connectors.fedora.generated.ObjectFieldsType; import dk.statsbiblioteket.doms.central.connectors.fedora.generated.ResultType; import dk.statsbiblioteket.doms.central.connectors.fedora.generated.Validation; import dk.statsbiblioteket.doms.central.connectors.fedora.structures.DatastreamProfile; import dk.statsbiblioteket.doms.central.connectors.fedora.structures.FedoraRelation; import dk.statsbiblioteket.doms.central.connectors.fedora.structures.ObjectProfile; import dk.statsbiblioteket.doms.central.connectors.fedora.structures.ObjectType; import dk.statsbiblioteket.doms.central.connectors.fedora.structures.SearchResult; import dk.statsbiblioteket.doms.central.connectors.fedora.utils.Constants; import dk.statsbiblioteket.doms.central.connectors.fedora.utils.DateUtils; import dk.statsbiblioteket.doms.webservices.authentication.Credentials; import dk.statsbiblioteket.util.xml.DOM; import dk.statsbiblioteket.util.xml.XPathSelector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.xml.transform.TransformerException; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.Date; import java.util.List; import java.util.TimeZone; /** * Created by IntelliJ IDEA. User: abr Date: Aug 25, 2010 Time: 1:50:31 PM To change this template use File | Settings * | * File Templates. */ public class FedoraRest extends Connector implements Fedora { private static final String AS_OF_DATE_TIME = "asOfDateTime"; private static Log log = LogFactory.getLog(FedoraRest.class); private WebResource restApi; private String port; public FedoraRest(Credentials creds, String location) throws MalformedURLException { super(creds, location); restApi = client.resource(location + "/objects"); restApi.addFilter(new HTTPBasicAuthFilter(creds.getUsername(), creds.getPassword())); port = calculateFedoraPort(location); } private String calculateFedoraPort(String location) { String portString = location.substring(location.lastIndexOf(':') + 1); portString = portString.substring(0, portString.indexOf('/')); return portString; } @Override public boolean exists(String pid, Long asOfDateTime) throws BackendInvalidCredsException, BackendMethodFailedException { try { ObjectProfile profile = getObjectProfile(pid, asOfDateTime); } catch (BackendInvalidResourceException e) { return false; } return true; } @Override public boolean isDataObject(String pid, Long asOfDateTime) throws BackendInvalidCredsException, BackendMethodFailedException { try { ObjectProfile profile = getObjectProfile(pid, asOfDateTime); return profile.getType().equals(ObjectType.DATA_OBJECT); } catch (BackendInvalidResourceException e) { return false; } } @Override public boolean isTemplate(String pid, Long asOfDateTime) throws BackendInvalidCredsException, BackendMethodFailedException { try { ObjectProfile profile = getObjectProfile(pid, asOfDateTime); return profile.getType().equals(ObjectType.TEMPLATE); } catch (BackendInvalidResourceException e) { return false; } } @Override public boolean isContentModel(String pid, Long asOfDateTime) throws BackendInvalidCredsException, BackendMethodFailedException { try { ObjectProfile profile = getObjectProfile(pid, asOfDateTime); return profile.getType().equals(ObjectType.CONTENT_MODEL); } catch (BackendInvalidResourceException e) { return false; } } @Override public String getObjectXml(String pid, Long asOfTime) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { //Get basic fedora profile //Get the object xml //Strip the old versions //Search for managed datastreams with format text/xml //retrieve and insert the content String xml = getRaxXml(pid); ObjectXml objectXml = new ObjectXml(pid, xml, this, asOfTime); return objectXml.getCleaned(); } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw new BackendInvalidResourceException("Resource not found", e); } else { throw new BackendMethodFailedException("Server error", e); } } catch (TransformerException e) { throw new BackendMethodFailedException("Failed to transform object to output format", e); } } protected String getRaxXml(String pid) throws UnsupportedEncodingException { return restApi.path("/") .path(URLEncoder.encode(pid, "UTF-8")) .path("/objectXML") .type(MediaType.TEXT_XML_TYPE) .get(String.class); } private String StringOrNull(Long time) { if (time != null && time > 0) { DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); formatter.setTimeZone(TimeZone.getTimeZone("UTC")); return formatter.format(new Date(time)); } return ""; } @Override public String ingestDocument(Document document, String logmessage) throws BackendMethodFailedException, BackendInvalidCredsException { String payload; try { payload = DOM.domToString(document); } catch (TransformerException e) { throw new BackendMethodFailedException("Supplied document not valid", e); } try { String pid = restApi.path("/") .path(URLEncoder.encode("new", "UTF-8")) .type(MediaType.TEXT_XML_TYPE) .post(String.class, payload); return pid; } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException( "Invalid Credentials Supplied when ingesting document: \n'" + payload + "'", e); } else { throw new BackendMethodFailedException("Server error when ingesting document: \n'" + payload + "'", e); } } } @Override public ObjectProfile getObjectProfile(String pid, Long asOfTime) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { //Get basic fedora profile dk.statsbiblioteket.doms.central.connectors.fedora.generated.ObjectProfile profile; profile = restApi.path("/") .path( URLEncoder.encode( pid, "UTF-8") ) .queryParam( "format", "text/xml") .get(dk.statsbiblioteket.doms.central.connectors.fedora.generated.ObjectProfile.class); ObjectProfile prof = new ObjectProfile(); prof.setObjectCreatedDate(profile.getObjCreateDate().toGregorianCalendar().getTime()); prof.setObjectLastModifiedDate(profile.getObjLastModDate().toGregorianCalendar().getTime()); prof.setLabel(profile.getObjLabel()); prof.setOwnerID(profile.getObjOwnerId()); prof.setState(profile.getObjState()); prof.setPid(profile.getPid()); List<String> contentmodels = new ArrayList<String>(); for (String s : profile.getObjModels().getModel()) { if (s.startsWith("info:fedora/")) { s = s.substring("info:fedora/".length()); } contentmodels.add(s); } prof.setContentModels(contentmodels); //Get relations List<FedoraRelation> relations = getNamedRelations(pid, null, asOfTime); prof.setRelations(relations); //get Datastream list ObjectDatastreams datastreams = restApi.path("/") .path(URLEncoder.encode(pid, "UTF-8")) .path("/datastreams") .queryParam("format", "text/xml") .get(ObjectDatastreams.class); List<DatastreamProfile> pdatastreams = new ArrayList<DatastreamProfile>(); for (DatastreamType datastreamType : datastreams.getDatastream()) { pdatastreams.add(getDatastreamProfile(pid, datastreamType.getDsid(), asOfTime)); } prof.setDatastreams(pdatastreams); //decode type prof.setType(ObjectType.DATA_OBJECT); if (prof.getContentModels().contains("fedora-system:ContentModel-3.0")) { prof.setType(ObjectType.CONTENT_MODEL); } if (prof.getContentModels().contains("doms:ContentModel_File")) { prof.setType(ObjectType.FILE); } if (prof.getContentModels().contains("doms:ContentModel_Collection")) { prof.setType(ObjectType.COLLECTION); } for (FedoraRelation fedoraRelation : prof.getRelations()) { String predicate = fedoraRelation.getPredicate(); if (Constants.TEMPLATE_REL.equals(predicate)) { prof.setType(ObjectType.TEMPLATE); break; } } return prof; } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied: pid '" + pid + "'", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw new BackendInvalidResourceException("Resource '" + pid + "'not found", e); } else { throw new BackendMethodFailedException("Server error for '" + pid + "'", e); } } } public DatastreamProfile getDatastreamProfile(String pid, String dsid, Long asOfTime) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { DatastreamProfileType fdatastream = restApi.path( "/") .path( URLEncoder .encode( pid, "UTF-8") ) .path("/datastreams/") .path(dsid) .queryParam( AS_OF_DATE_TIME, StringOrNull( asOfTime) ) .queryParam( "format", "text/xml") .get(DatastreamProfileType.class); DatastreamProfile profile = new DatastreamProfile(); profile.setID(fdatastream.getDsID()); profile.setLabel(fdatastream.getDsLabel()); profile.setState(fdatastream.getDsState()); profile.setChecksum(fdatastream.getDsChecksum()); profile.setChecksumType(fdatastream.getDsChecksumType()); profile.setCreated(fdatastream.getDsCreateDate().toGregorianCalendar().getTime().getTime()); profile.setFormatURI(fdatastream.getDsFormatURI()); profile.setMimeType(fdatastream.getDsMIME()); String type = fdatastream.getDsControlGroup(); if (type.equals("X") || type.equals("M")) { profile.setInternal(true); } else if (type.equals("E") || type.equals("R")) { profile.setInternal(false); profile.setUrl(fdatastream.getDsLocation()); } return profile; } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied: pid '" + pid + "'", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw new BackendInvalidResourceException("Resource '" + pid + "'not found", e); } else { throw new BackendMethodFailedException("Server error for '" + pid + "'", e); } } } @Override public void modifyObjectState(String pid, String state, String comment) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { if (comment == null || comment.isEmpty()) { comment = "No message supplied"; } ClientResponse response = restApi.path("/") .path(URLEncoder.encode(pid, "UTF-8")) .queryParam("state", state) .queryParam("logMessage", comment) .put(ClientResponse.class); switch (response.getClientResponseStatus()) { case UNAUTHORIZED: throw new BackendInvalidCredsException("Invalid Credentials Supplied: pid '" + pid + "'"); case NOT_FOUND: throw new BackendInvalidResourceException("Resource '" + pid + "'not found"); case BAD_REQUEST: throw new BackendMethodFailedException(response.getEntity(String.class)); case OK: break; default: throw new BackendMethodFailedException("Server error for '" + pid + "', " + response.toString()); } } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } } @Override public void modifyDatastreamByValue(String pid, String datastream, ChecksumType checksumType, String checksum, byte[] contents, List<String> alternativeIdentifiers, String comment) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { updateExistingDatastreamByValue( pid, datastream, checksumType, checksum, contents, alternativeIdentifiers, comment, null, null); } catch (BackendInvalidResourceException e) { //perhaps the datastream did not exist createDatastreamByValue( pid, datastream, checksumType, checksum, contents, alternativeIdentifiers, null, comment); } } @Override public void modifyDatastreamByValue(String pid, String datastream, ChecksumType checksumType, String checksum, byte[] contents, List<String> alternativeIdentifiers, String comment, Long lastModifiedDate) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException, ConcurrentModificationException { try { updateExistingDatastreamByValue( pid, datastream, checksumType, checksum, contents, alternativeIdentifiers, comment, lastModifiedDate, null); } catch (BackendInvalidResourceException e) { //perhaps the datastream did not exist createDatastreamByValue( pid, datastream, checksumType, checksum, contents, alternativeIdentifiers, null, comment); } } @Override public void modifyDatastreamByValue(String pid, String datastream, ChecksumType checksumType, String checksum, byte[] contents, List<String> alternativeIdentifiers, String mimeType, String comment, Long lastModifiedDate) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException, ConcurrentModificationException { try { updateExistingDatastreamByValue( pid, datastream, checksumType, checksum, contents, alternativeIdentifiers, comment, lastModifiedDate, mimeType); } catch (BackendInvalidResourceException e) { //perhaps the datastream did not exist createDatastreamByValue( pid, datastream, checksumType, checksum, contents, alternativeIdentifiers, mimeType, comment); } } private void createDatastreamByValue(String pid, String datastream, ChecksumType checksumType, String checksum, byte[] contents, List<String> alternativeIdentifiers, String mimeType, String comment) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { if (mimeType == null) { mimeType = "text/xml"; } WebResource resource = getModifyDatastreamWebResource( pid, datastream, checksumType, checksum, alternativeIdentifiers, comment, null, mimeType); resource.queryParam("controlGroup", "M").post(new ByteArrayInputStream(contents)); } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied: pid '" + pid + "'", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw new BackendInvalidResourceException("Resource '" + pid + "'not found", e); } else { throw new BackendMethodFailedException("Server error for '" + pid + "'", e); } } } private WebResource getModifyDatastreamWebResource(String pid, String datastream, ChecksumType checksumType, String checksum, List<String> alternativeIdentifiers, String comment, Long lastModifiedDate, String mimeType) throws UnsupportedEncodingException { if (comment == null || comment.isEmpty()) { comment = "No message supplied"; } WebResource resource = restApi.path("/") .path(URLEncoder.encode(pid, "UTF-8")) .path("/datastreams/") .path(URLEncoder.encode(datastream, "UTF-8")) .queryParam("logMessage", comment); if (alternativeIdentifiers != null) { for (String alternativeIdentifier : alternativeIdentifiers) { resource = resource.queryParam("altIDs", alternativeIdentifier); } } if (checksumType != null) { resource = resource.queryParam("checksumType", checksumType.toString()); } if (checksum != null) { resource = resource.queryParam("checksum", checksum); } if (lastModifiedDate != null) { resource = resource.queryParam("lastModifiedDate", StringOrNull(lastModifiedDate)); } if (mimeType != null) { resource = resource.queryParam("mimeType", mimeType); } /*else { resource = resource.queryParam("mimeType", "text/xml"); }*/ return resource; } private void updateExistingDatastreamByValue(String pid, String datastream, ChecksumType checksumType, String checksum, byte[] contents, List<String> alternativeIdentifiers, String comment, Long lastModifiedDate, String mimeType) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException, ConcurrentModificationException { try { WebResource resource = getModifyDatastreamWebResource( pid, datastream, checksumType, checksum, alternativeIdentifiers, comment, lastModifiedDate, mimeType); WebResource.Builder header = resource.header(HttpHeaders.CONTENT_TYPE, null); if (mimeType != null){ header.entity(new ByteArrayInputStream(contents), mimeType); } else { header.entity(new ByteArrayInputStream(contents)); } header.put(); } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied: pid '" + pid + "'", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw new BackendInvalidResourceException("Resource '" + pid + "'not found", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.CONFLICT.getStatusCode()) { throw new ConcurrentModificationException("Datastream has changed between reading and writing."); } else { throw new BackendMethodFailedException("Server error for '" + pid + "'", e); } } } @Override public void deleteObject(String pid, String comment) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { restApi.path("/").path(URLEncoder.encode(pid, "UTF-8")).queryParam("logMessage", comment).delete(); } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied: pid '" + pid + "'", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw new BackendInvalidResourceException("Resource '" + pid + "'not found", e); } else { throw new BackendMethodFailedException("Server error for '" + pid + "'", e); } } } @Override public void deleteDatastream(String pid, String datastream, String comment) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { restApi.path("/") .path(URLEncoder.encode(pid, "UTF-8")) .path("/datastreams/") .path(URLEncoder.encode(datastream, "UTF-8")) .queryParam("logMessage", comment) .delete(); } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied: pid '" + pid + "'", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw new BackendInvalidResourceException("Resource '" + pid + "'not found", e); } else { throw new BackendMethodFailedException("Server error for '" + pid + "'", e); } } } @Override public String getXMLDatastreamContents(String pid, String datastream, Long asOfTime) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { String contents = restApi.path("/") .path(URLEncoder.encode(pid, "UTF-8")) .path("/datastreams/") .path(URLEncoder.encode(datastream, "UTF-8")) .path("/content") .queryParam(AS_OF_DATE_TIME, StringOrNull(asOfTime)) .get(String.class); return contents; } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied: pid '" + pid + "'", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw new BackendInvalidResourceException("Resource '" + pid + "'not found", e); } else { throw new BackendMethodFailedException("Server error for '" + pid + "'", e); } } } @Override public void addRelation(String pid, String subject, String predicate, String object, boolean literal, String comment) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { if (comment == null || comment.isEmpty()) { comment = "No message supplied"; } //TODO, fedora should take this logmessage if (!literal) { if (!object.startsWith("info:fedora/")) { object = "info:fedora/" + object; } } URI predURI = new URI(predicate); if (!predURI.isAbsolute()) { predicate = "info:fedora/" + predicate; } if (subject == null || subject.isEmpty()) { subject = "info:fedora/" + pid; } restApi.path("/") .path(pid) .path("/relationships/new") .queryParam("subject", subject) .queryParam("predicate", predicate) .queryParam("object", object) .queryParam("isLiteral", "" + literal) .post(); if (predicate.equals("http://doms.statsbiblioteket.dk/relations/default/0/1/#hasLicense")) { //this is a license relation, update the policy datastream if (object.startsWith("info:fedora/")) { object = object.substring("info:fedora/".length()); } restApi.path("/") .path(URLEncoder.encode(pid, "UTF-8")) .path("/datastreams/POLICY") .queryParam( "dsLocation", "http://localhost:" + port + "/fedora/objects/" + object + "/datastreams/LICENSE/content" ) .queryParam("mimeType", "application/rdf+xml") .queryParam("ignoreContent", "true") .put(); } } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied: pid '" + pid + "'", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw new BackendInvalidResourceException("Resource '" + pid + "'not found", e); } else { throw new BackendMethodFailedException("Server error for '" + pid + "'", e); } } catch (URISyntaxException e) { throw new BackendMethodFailedException("Failed to parse predicate as an URI", e); } } @Override public void addRelations(String pid, String subject, String predicate, List<String> objects, boolean literal, String comment) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { if (comment == null || comment.isEmpty()) { comment = "No message supplied"; } if (literal) {//cant handle literal yet for (String object : objects) { addRelation(pid, subject, predicate, object, literal, comment); } } if (objects.size() == 1) {//more efficient if only adding one relation addRelation(pid, subject, predicate, objects.get(0), literal, comment); } try { XPathSelector xpath = DOM.createXPathSelector( "rdf", Constants.NAMESPACE_RDF); String datastream; if (subject == null || subject.isEmpty() || subject.equals(pid) || subject.equals("info:fedora/" + pid)) { subject = "info:fedora/" + pid; datastream = "RELS-EXT"; } else { datastream = "RELS-INT"; } String rels = getXMLDatastreamContents(pid, datastream, null); Document relsDoc = DOM.stringToDOM(rels, true); Node rdfDescriptionNode = xpath.selectNode( relsDoc, "/rdf:RDF/rdf:Description[@rdf:about='" + subject + "']"); URI predURI = new URI(predicate); if (!predURI.isAbsolute()) { predicate = "info:fedora/" + predicate; } String[] splits = predicate.split("#"); for (String object : objects) { if (!object.startsWith("info:fedora/")) { object = "info:fedora/" + object; } Element relationsShipElement = relsDoc.createElementNS(splits[0] + "#", splits[1]); relationsShipElement.setAttributeNS(Constants.NAMESPACE_RDF, "rdf:resource", object); rdfDescriptionNode.appendChild(relationsShipElement); } modifyDatastreamByValue( pid, datastream, ChecksumType.MD5, null, DOM.domToString(relsDoc).getBytes("UTF-8"), null, "application/rdf+xml", comment, null); } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("Failed to transform RELS-EXT", e); } catch (TransformerException e) { throw new BackendMethodFailedException("Failed to transform RELS-EXT", e); } catch (URISyntaxException e) { throw new BackendMethodFailedException("Failed to parse predicate as an URI", e); } } @Override public List<FedoraRelation> getNamedRelations(String pid, String name, Long asOfTime) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { //TODO use asOfTime here, when fedora supports it String subject = pid; if (!subject.startsWith("info:fedora/")) { subject = "info:fedora/" + subject; } WebResource temp = restApi.path("/") .path(pid) .path("/relationships/") .queryParam("subject", subject) .queryParam("format", "n-triples"); if (name != null) { temp = temp.queryParam("predicate", name); } String relationString = temp.get(String.class); String[] lines = relationString.split("\n"); List<FedoraRelation> relations = new ArrayList<FedoraRelation>(); for (String line : lines) { String[] elements = line.split(" "); if (elements.length > 2) { FedoraRelation rel = new FedoraRelation( cleanInfo(elements[0]), clean(elements[1]), cleanInfo(elements[2])); if (elements[2].startsWith("<info:fedora/")) { rel.setLiteral(false); } else { rel.setLiteral(true); } relations.add(rel); } } return relations; } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied: pid '" + pid + "'", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw new BackendInvalidResourceException("Resource '" + pid + "'not found", e); } else { throw new BackendMethodFailedException("Server error for '" + pid + "'", e); } } } private String clean(String element) { if (element.startsWith("<") && element.endsWith(">")) { element = element.substring(1, element.length() - 1); } return element; //To change body of created methods use File | Settings | File Templates. } private String cleanInfo(String element) { element = clean(element); if (element.startsWith("info:fedora/")) { element = element.substring("info:fedora/".length()); } return element; //To change body of created methods use File | Settings | File Templates. } @Override public void deleteRelation(String pid, String subject, String predicate, String object, boolean literal, String comment) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { if (comment == null || comment.isEmpty()) { comment = "No message supplied"; } //TODO, fedora should take this logmessage if (!literal) { if (!object.startsWith("info:fedora/")) { object = "info:fedora/" + object; } } URI predURI = new URI(predicate); if (!predURI.isAbsolute()) { predicate = "info:fedora/" + predicate; } restApi.path("/") .path(pid) .path("/relationships/") .queryParam("predicate", predicate) .queryParam("object", object) .queryParam("isLiteral", "" + literal) .delete(); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied: pid '" + pid + "'", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw new BackendInvalidResourceException("Resource '" + pid + "'not found", e); } else { throw new BackendMethodFailedException("Server error for '" + pid + "'", e); } } catch (URISyntaxException e) { throw new BackendMethodFailedException("Failed to parse predicate as an URI", e); } } @Override public void modifyObjectLabel(String pid, String name, String comment) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { if (comment == null || comment.isEmpty()) { comment = "No message supplied"; } restApi.path("/") .path(URLEncoder.encode(pid, "UTF-8")) .queryParam("label", name) .queryParam("logMessage", comment) .put(); } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw new BackendInvalidResourceException("Resource not found", e); } else { throw new BackendMethodFailedException("Server error", e); } } } @Override public List<SearchResult> fieldsearch(String query, int offset, int pageLength) throws BackendMethodFailedException, BackendInvalidCredsException { try { ResultType searchResult = restApi.queryParam("terms", query) .queryParam("maxResults", pageLength + "") .queryParam("resultFormat", "xml") .queryParam("pid", "true") .queryParam("label", "true") .queryParam("state", "true") .queryParam("cDate", "true") .queryParam("mDate", "true") .get(ResultType.class); if (offset > 0) { for (int i = 1; i <= offset; i++) { String token = searchResult.getListSession().getValue().getToken(); searchResult = restApi.queryParam("query", query) .queryParam("sessionToken", token) .queryParam("resultFormat", "xml") .get(ResultType.class); } } List<SearchResult> outputResults = new ArrayList<SearchResult>( searchResult.getResultList().getObjectFields().size()); for (ObjectFieldsType objectFieldsType : searchResult.getResultList().getObjectFields()) { outputResults.add( new SearchResult( objectFieldsType.getPid().getValue(), objectFieldsType.getLabel().getValue(), objectFieldsType.getState().getValue(), DateUtils.parseDateStrict(objectFieldsType.getCDate().getValue()).getTime(), DateUtils.parseDateStrict(objectFieldsType.getMDate().getValue()).getTime()) ); } return outputResults; } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied", e); } else { throw new BackendMethodFailedException("Server error", e); } } catch (ParseException e) { throw new BackendMethodFailedException("Failed to parse date from search result", e); } } @Override public void addExternalDatastream(String pid, String datastream, String label, String url, String formatURI, String mimeType, String checksumType, String checksum, String comment) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { if (comment == null || comment.isEmpty()) { comment = "No message supplied"; } /* @PathParam(RestParam.PID) String pid, @PathParam(RestParam.DSID) String dsID, @QueryParam(RestParam.CONTROL_GROUP) @DefaultValue("X") String controlGroup, @QueryParam(RestParam.DS_LOCATION) String dsLocation, @QueryParam(RestParam.ALT_IDS) List<String> altIDs, @QueryParam(RestParam.DS_LABEL) String dsLabel, @QueryParam(RestParam.VERSIONABLE) @DefaultValue("true") Boolean versionable, @QueryParam(RestParam.DS_STATE) @DefaultValue("A") String dsState, @QueryParam(RestParam.FORMAT_URI) String formatURI, @QueryParam(RestParam.CHECKSUM_TYPE) String checksumType, @QueryParam(RestParam.CHECKSUM) String checksum, @QueryParam(RestParam.MIME_TYPE) String mimeType, @QueryParam(RestParam.LOG_MESSAGE) String logMessage */ WebResource resource = restApi.path("/") .path(URLEncoder.encode(pid, "UTF-8")) .path("/datastreams/") .path(URLEncoder.encode(datastream, "UTF-8")) .queryParam("controlGroup", "R") .queryParam("dsLocation", url) .queryParam("dsLabel", label) .queryParam("formatURI", formatURI) .queryParam("mimeType", mimeType) .queryParam("logMessage", comment); if (checksumType != null) { resource = resource.queryParam("checksumType", checksumType); } if (checksum != null) { resource = resource.queryParam("checksum", checksum); } resource.post(); } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied: pid '" + pid + "'", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw new BackendInvalidResourceException("Resource '" + pid + "'not found", e); } else { throw new BackendMethodFailedException("Server error for '" + pid + "'", e); } } } @Override public Validation validate(String pid) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { WebResource format = restApi.path("/").path( URLEncoder.encode( pid, "UTF-8") ).path("/validate").queryParam( "format", "text/xml"); return format.get(Validation.class); } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } } @Override public String newEmptyObject(String pid, List<String> oldIDs, List<String> collections, String logMessage) throws BackendMethodFailedException, BackendInvalidCredsException { try { InputStream emptyObjectStream = Thread.currentThread() .getContextClassLoader() .getResourceAsStream("EmptyObject.xml"); Document emptyObject = DOM.streamToDOM(emptyObjectStream, true); XPathSelector xpath = DOM.createXPathSelector( "foxml", Constants.NAMESPACE_FOXML, "rdf", Constants.NAMESPACE_RDF, "d", Constants.NAMESPACE_RELATIONS, "dc", Constants.NAMESPACE_DC, "oai_dc", Constants.NAMESPACE_OAIDC); //Set pid Node pidNode = xpath.selectNode(emptyObject, "/foxml:digitalObject/@PID"); pidNode.setNodeValue(pid); Node rdfNode = xpath.selectNode( emptyObject, "/foxml:digitalObject/foxml:datastream/foxml:datastreamVersion/foxml:xmlContent/rdf:RDF/rdf:Description/@rdf:about"); rdfNode.setNodeValue("info:fedora/" + pid); //add Old Identifiers to DC Node dcIdentifierNode = xpath.selectNode( emptyObject, "/foxml:digitalObject/foxml:datastream/foxml:datastreamVersion/foxml:xmlContent/oai_dc:dc/dc:identifier"); dcIdentifierNode.setTextContent(pid); Node parent = dcIdentifierNode.getParentNode(); for (String oldID : oldIDs) { Node clone = dcIdentifierNode.cloneNode(true); clone.setTextContent(oldID); parent.appendChild(clone); } Node collectionRelationNode = xpath.selectNode( emptyObject, "/foxml:digitalObject/foxml:datastream/foxml:datastreamVersion/foxml:xmlContent/rdf:RDF/rdf:Description/d:isPartOfCollection"); parent = collectionRelationNode.getParentNode(); //remove the placeholder relationNode parent.removeChild(collectionRelationNode); for (String collection : collections) { Node clone = collectionRelationNode.cloneNode(true); clone.getAttributes().getNamedItem("rdf:resource").setNodeValue("info:fedora/" + collection); parent.appendChild(clone); } String createdPid = restApi.path("/") .path(URLEncoder.encode(pid, "UTF-8")) .queryParam("state", "I") .type(MediaType.TEXT_XML_TYPE) .post(String.class, DOM.domToString(emptyObject)); return createdPid; } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied", e); } else { throw new BackendMethodFailedException("Server error", e); } } catch (TransformerException e) { throw new BackendMethodFailedException("Failed to convert DC back to string", e); } } }
central-fedoraClient/src/main/java/dk/statsbiblioteket/doms/central/connectors/fedora/FedoraRest.java
/* * $Id$ * $Revision$ * $Date$ * $Author$ * * The DOMS project. * Copyright (C) 2007-2010 The State and University Library * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package dk.statsbiblioteket.doms.central.connectors.fedora; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import dk.statsbiblioteket.doms.central.connectors.BackendInvalidCredsException; import dk.statsbiblioteket.doms.central.connectors.BackendInvalidResourceException; import dk.statsbiblioteket.doms.central.connectors.BackendMethodFailedException; import dk.statsbiblioteket.doms.central.connectors.Connector; import dk.statsbiblioteket.doms.central.connectors.fedora.generated.DatastreamProfileType; import dk.statsbiblioteket.doms.central.connectors.fedora.generated.DatastreamType; import dk.statsbiblioteket.doms.central.connectors.fedora.generated.ObjectDatastreams; import dk.statsbiblioteket.doms.central.connectors.fedora.generated.ObjectFieldsType; import dk.statsbiblioteket.doms.central.connectors.fedora.generated.ResultType; import dk.statsbiblioteket.doms.central.connectors.fedora.generated.Validation; import dk.statsbiblioteket.doms.central.connectors.fedora.structures.DatastreamProfile; import dk.statsbiblioteket.doms.central.connectors.fedora.structures.FedoraRelation; import dk.statsbiblioteket.doms.central.connectors.fedora.structures.ObjectProfile; import dk.statsbiblioteket.doms.central.connectors.fedora.structures.ObjectType; import dk.statsbiblioteket.doms.central.connectors.fedora.structures.SearchResult; import dk.statsbiblioteket.doms.central.connectors.fedora.utils.Constants; import dk.statsbiblioteket.doms.central.connectors.fedora.utils.DateUtils; import dk.statsbiblioteket.doms.webservices.authentication.Credentials; import dk.statsbiblioteket.util.xml.DOM; import dk.statsbiblioteket.util.xml.XPathSelector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.xml.transform.TransformerException; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.Date; import java.util.List; import java.util.TimeZone; /** * Created by IntelliJ IDEA. User: abr Date: Aug 25, 2010 Time: 1:50:31 PM To change this template use File | Settings * | * File Templates. */ public class FedoraRest extends Connector implements Fedora { private static final String AS_OF_DATE_TIME = "asOfDateTime"; private static Log log = LogFactory.getLog(FedoraRest.class); private WebResource restApi; private String port; public FedoraRest(Credentials creds, String location) throws MalformedURLException { super(creds, location); restApi = client.resource(location + "/objects"); restApi.addFilter(new HTTPBasicAuthFilter(creds.getUsername(), creds.getPassword())); port = calculateFedoraPort(location); } private String calculateFedoraPort(String location) { String portString = location.substring(location.lastIndexOf(':') + 1); portString = portString.substring(0, portString.indexOf('/')); return portString; } @Override public boolean exists(String pid, Long asOfDateTime) throws BackendInvalidCredsException, BackendMethodFailedException { try { ObjectProfile profile = getObjectProfile(pid, asOfDateTime); } catch (BackendInvalidResourceException e) { return false; } return true; } @Override public boolean isDataObject(String pid, Long asOfDateTime) throws BackendInvalidCredsException, BackendMethodFailedException { try { ObjectProfile profile = getObjectProfile(pid, asOfDateTime); return profile.getType().equals(ObjectType.DATA_OBJECT); } catch (BackendInvalidResourceException e) { return false; } } @Override public boolean isTemplate(String pid, Long asOfDateTime) throws BackendInvalidCredsException, BackendMethodFailedException { try { ObjectProfile profile = getObjectProfile(pid, asOfDateTime); return profile.getType().equals(ObjectType.TEMPLATE); } catch (BackendInvalidResourceException e) { return false; } } @Override public boolean isContentModel(String pid, Long asOfDateTime) throws BackendInvalidCredsException, BackendMethodFailedException { try { ObjectProfile profile = getObjectProfile(pid, asOfDateTime); return profile.getType().equals(ObjectType.CONTENT_MODEL); } catch (BackendInvalidResourceException e) { return false; } } @Override public String getObjectXml(String pid, Long asOfTime) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { //Get basic fedora profile //Get the object xml //Strip the old versions //Search for managed datastreams with format text/xml //retrieve and insert the content String xml = getRaxXml(pid); ObjectXml objectXml = new ObjectXml(pid, xml, this, asOfTime); return objectXml.getCleaned(); } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw new BackendInvalidResourceException("Resource not found", e); } else { throw new BackendMethodFailedException("Server error", e); } } catch (TransformerException e) { throw new BackendMethodFailedException("Failed to transform object to output format", e); } } protected String getRaxXml(String pid) throws UnsupportedEncodingException { return restApi.path("/") .path(URLEncoder.encode(pid, "UTF-8")) .path("/objectXML") .type(MediaType.TEXT_XML_TYPE) .get(String.class); } private String StringOrNull(Long time) { if (time != null && time > 0) { DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); formatter.setTimeZone(TimeZone.getTimeZone("UTC")); return formatter.format(new Date(time)); } return ""; } @Override public String ingestDocument(Document document, String logmessage) throws BackendMethodFailedException, BackendInvalidCredsException { String payload; try { payload = DOM.domToString(document); } catch (TransformerException e) { throw new BackendMethodFailedException("Supplied document not valid", e); } try { String pid = restApi.path("/") .path(URLEncoder.encode("new", "UTF-8")) .type(MediaType.TEXT_XML_TYPE) .post(String.class, payload); return pid; } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException( "Invalid Credentials Supplied when ingesting document: \n'" + payload + "'", e); } else { throw new BackendMethodFailedException("Server error when ingesting document: \n'" + payload + "'", e); } } } @Override public ObjectProfile getObjectProfile(String pid, Long asOfTime) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { //Get basic fedora profile dk.statsbiblioteket.doms.central.connectors.fedora.generated.ObjectProfile profile; profile = restApi.path("/") .path( URLEncoder.encode( pid, "UTF-8") ) .queryParam( "format", "text/xml") .get(dk.statsbiblioteket.doms.central.connectors.fedora.generated.ObjectProfile.class); ObjectProfile prof = new ObjectProfile(); prof.setObjectCreatedDate(profile.getObjCreateDate().toGregorianCalendar().getTime()); prof.setObjectLastModifiedDate(profile.getObjLastModDate().toGregorianCalendar().getTime()); prof.setLabel(profile.getObjLabel()); prof.setOwnerID(profile.getObjOwnerId()); prof.setState(profile.getObjState()); prof.setPid(profile.getPid()); List<String> contentmodels = new ArrayList<String>(); for (String s : profile.getObjModels().getModel()) { if (s.startsWith("info:fedora/")) { s = s.substring("info:fedora/".length()); } contentmodels.add(s); } prof.setContentModels(contentmodels); //Get relations List<FedoraRelation> relations = getNamedRelations(pid, null, asOfTime); prof.setRelations(relations); //get Datastream list ObjectDatastreams datastreams = restApi.path("/") .path(URLEncoder.encode(pid, "UTF-8")) .path("/datastreams") .queryParam("format", "text/xml") .get(ObjectDatastreams.class); List<DatastreamProfile> pdatastreams = new ArrayList<DatastreamProfile>(); for (DatastreamType datastreamType : datastreams.getDatastream()) { pdatastreams.add(getDatastreamProfile(pid, datastreamType.getDsid(), asOfTime)); } prof.setDatastreams(pdatastreams); //decode type prof.setType(ObjectType.DATA_OBJECT); if (prof.getContentModels().contains("fedora-system:ContentModel-3.0")) { prof.setType(ObjectType.CONTENT_MODEL); } if (prof.getContentModels().contains("doms:ContentModel_File")) { prof.setType(ObjectType.FILE); } if (prof.getContentModels().contains("doms:ContentModel_Collection")) { prof.setType(ObjectType.COLLECTION); } for (FedoraRelation fedoraRelation : prof.getRelations()) { String predicate = fedoraRelation.getPredicate(); if (Constants.TEMPLATE_REL.equals(predicate)) { prof.setType(ObjectType.TEMPLATE); break; } } return prof; } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied: pid '" + pid + "'", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw new BackendInvalidResourceException("Resource '" + pid + "'not found", e); } else { throw new BackendMethodFailedException("Server error for '" + pid + "'", e); } } } public DatastreamProfile getDatastreamProfile(String pid, String dsid, Long asOfTime) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { DatastreamProfileType fdatastream = restApi.path( "/") .path( URLEncoder .encode( pid, "UTF-8") ) .path("/datastreams/") .path(dsid) .queryParam( AS_OF_DATE_TIME, StringOrNull( asOfTime) ) .queryParam( "format", "text/xml") .get(DatastreamProfileType.class); DatastreamProfile profile = new DatastreamProfile(); profile.setID(fdatastream.getDsID()); profile.setLabel(fdatastream.getDsLabel()); profile.setState(fdatastream.getDsState()); profile.setChecksum(fdatastream.getDsChecksum()); profile.setChecksumType(fdatastream.getDsChecksumType()); profile.setCreated(fdatastream.getDsCreateDate().toGregorianCalendar().getTime().getTime()); profile.setFormatURI(fdatastream.getDsFormatURI()); profile.setMimeType(fdatastream.getDsMIME()); String type = fdatastream.getDsControlGroup(); if (type.equals("X") || type.equals("M")) { profile.setInternal(true); } else if (type.equals("E") || type.equals("R")) { profile.setInternal(false); profile.setUrl(fdatastream.getDsLocation()); } return profile; } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied: pid '" + pid + "'", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw new BackendInvalidResourceException("Resource '" + pid + "'not found", e); } else { throw new BackendMethodFailedException("Server error for '" + pid + "'", e); } } } @Override public void modifyObjectState(String pid, String state, String comment) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { if (comment == null || comment.isEmpty()) { comment = "No message supplied"; } ClientResponse response = restApi.path("/") .path(URLEncoder.encode(pid, "UTF-8")) .queryParam("state", state) .queryParam("logMessage", comment) .put(ClientResponse.class); switch (response.getClientResponseStatus()) { case UNAUTHORIZED: throw new BackendInvalidCredsException("Invalid Credentials Supplied: pid '" + pid + "'"); case NOT_FOUND: throw new BackendInvalidResourceException("Resource '" + pid + "'not found"); case BAD_REQUEST: throw new BackendMethodFailedException(response.getEntity(String.class)); case OK: break; default: throw new BackendMethodFailedException("Server error for '" + pid + "', " + response.toString()); } } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } } @Override public void modifyDatastreamByValue(String pid, String datastream, ChecksumType checksumType, String checksum, byte[] contents, List<String> alternativeIdentifiers, String comment) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { updateExistingDatastreamByValue( pid, datastream, checksumType, checksum, contents, alternativeIdentifiers, comment, null, null); } catch (BackendInvalidResourceException e) { //perhaps the datastream did not exist createDatastreamByValue( pid, datastream, checksumType, checksum, contents, alternativeIdentifiers, null, comment); } } @Override public void modifyDatastreamByValue(String pid, String datastream, ChecksumType checksumType, String checksum, byte[] contents, List<String> alternativeIdentifiers, String comment, Long lastModifiedDate) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException, ConcurrentModificationException { try { updateExistingDatastreamByValue( pid, datastream, checksumType, checksum, contents, alternativeIdentifiers, comment, lastModifiedDate, null); } catch (BackendInvalidResourceException e) { //perhaps the datastream did not exist createDatastreamByValue( pid, datastream, checksumType, checksum, contents, alternativeIdentifiers, null, comment); } } @Override public void modifyDatastreamByValue(String pid, String datastream, ChecksumType checksumType, String checksum, byte[] contents, List<String> alternativeIdentifiers, String mimeType, String comment, Long lastModifiedDate) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException, ConcurrentModificationException { try { updateExistingDatastreamByValue( pid, datastream, checksumType, checksum, contents, alternativeIdentifiers, comment, lastModifiedDate, mimeType); } catch (BackendInvalidResourceException e) { //perhaps the datastream did not exist createDatastreamByValue( pid, datastream, checksumType, checksum, contents, alternativeIdentifiers, mimeType, comment); } } private void createDatastreamByValue(String pid, String datastream, ChecksumType checksumType, String checksum, byte[] contents, List<String> alternativeIdentifiers, String mimeType, String comment) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { if (mimeType == null) { mimeType = "text/xml"; } WebResource resource = getModifyDatastreamWebResource( pid, datastream, checksumType, checksum, alternativeIdentifiers, comment, null, mimeType); resource.queryParam("controlGroup", "M").post(new ByteArrayInputStream(contents)); } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied: pid '" + pid + "'", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw new BackendInvalidResourceException("Resource '" + pid + "'not found", e); } else { throw new BackendMethodFailedException("Server error for '" + pid + "'", e); } } } private WebResource getModifyDatastreamWebResource(String pid, String datastream, ChecksumType checksumType, String checksum, List<String> alternativeIdentifiers, String comment, Long lastModifiedDate, String mimeType) throws UnsupportedEncodingException { if (comment == null || comment.isEmpty()) { comment = "No message supplied"; } WebResource resource = restApi.path("/") .path(URLEncoder.encode(pid, "UTF-8")) .path("/datastreams/") .path(URLEncoder.encode(datastream, "UTF-8")) .queryParam("logMessage", comment); if (alternativeIdentifiers != null) { for (String alternativeIdentifier : alternativeIdentifiers) { resource = resource.queryParam("altIDs", alternativeIdentifier); } } if (checksumType != null) { resource = resource.queryParam("checksumType", checksumType.toString()); } if (checksum != null) { resource = resource.queryParam("checksum", checksum); } if (lastModifiedDate != null) { resource = resource.queryParam("lastModifiedDate", StringOrNull(lastModifiedDate)); } if (mimeType != null) { resource = resource.queryParam("mimeType", mimeType); } /*else { resource = resource.queryParam("mimeType", "text/xml"); }*/ return resource; } private void updateExistingDatastreamByValue(String pid, String datastream, ChecksumType checksumType, String checksum, byte[] contents, List<String> alternativeIdentifiers, String comment, Long lastModifiedDate, String mimeType) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException, ConcurrentModificationException { try { WebResource resource = getModifyDatastreamWebResource( pid, datastream, checksumType, checksum, alternativeIdentifiers, comment, lastModifiedDate, mimeType); resource.header(HttpHeaders.CONTENT_TYPE, null).entity(new ByteArrayInputStream(contents),mimeType).put(); } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied: pid '" + pid + "'", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw new BackendInvalidResourceException("Resource '" + pid + "'not found", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.CONFLICT.getStatusCode()) { throw new ConcurrentModificationException("Datastream has changed between reading and writing."); } else { throw new BackendMethodFailedException("Server error for '" + pid + "'", e); } } } @Override public void deleteObject(String pid, String comment) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { restApi.path("/").path(URLEncoder.encode(pid, "UTF-8")).queryParam("logMessage", comment).delete(); } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied: pid '" + pid + "'", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw new BackendInvalidResourceException("Resource '" + pid + "'not found", e); } else { throw new BackendMethodFailedException("Server error for '" + pid + "'", e); } } } @Override public void deleteDatastream(String pid, String datastream, String comment) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { restApi.path("/") .path(URLEncoder.encode(pid, "UTF-8")) .path("/datastreams/") .path(URLEncoder.encode(datastream, "UTF-8")) .queryParam("logMessage", comment) .delete(); } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied: pid '" + pid + "'", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw new BackendInvalidResourceException("Resource '" + pid + "'not found", e); } else { throw new BackendMethodFailedException("Server error for '" + pid + "'", e); } } } @Override public String getXMLDatastreamContents(String pid, String datastream, Long asOfTime) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { String contents = restApi.path("/") .path(URLEncoder.encode(pid, "UTF-8")) .path("/datastreams/") .path(URLEncoder.encode(datastream, "UTF-8")) .path("/content") .queryParam(AS_OF_DATE_TIME, StringOrNull(asOfTime)) .get(String.class); return contents; } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied: pid '" + pid + "'", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw new BackendInvalidResourceException("Resource '" + pid + "'not found", e); } else { throw new BackendMethodFailedException("Server error for '" + pid + "'", e); } } } @Override public void addRelation(String pid, String subject, String predicate, String object, boolean literal, String comment) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { if (comment == null || comment.isEmpty()) { comment = "No message supplied"; } //TODO, fedora should take this logmessage if (!literal) { if (!object.startsWith("info:fedora/")) { object = "info:fedora/" + object; } } URI predURI = new URI(predicate); if (!predURI.isAbsolute()) { predicate = "info:fedora/" + predicate; } if (subject == null || subject.isEmpty()) { subject = "info:fedora/" + pid; } restApi.path("/") .path(pid) .path("/relationships/new") .queryParam("subject", subject) .queryParam("predicate", predicate) .queryParam("object", object) .queryParam("isLiteral", "" + literal) .post(); if (predicate.equals("http://doms.statsbiblioteket.dk/relations/default/0/1/#hasLicense")) { //this is a license relation, update the policy datastream if (object.startsWith("info:fedora/")) { object = object.substring("info:fedora/".length()); } restApi.path("/") .path(URLEncoder.encode(pid, "UTF-8")) .path("/datastreams/POLICY") .queryParam( "dsLocation", "http://localhost:" + port + "/fedora/objects/" + object + "/datastreams/LICENSE/content" ) .queryParam("mimeType", "application/rdf+xml") .queryParam("ignoreContent", "true") .put(); } } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied: pid '" + pid + "'", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw new BackendInvalidResourceException("Resource '" + pid + "'not found", e); } else { throw new BackendMethodFailedException("Server error for '" + pid + "'", e); } } catch (URISyntaxException e) { throw new BackendMethodFailedException("Failed to parse predicate as an URI", e); } } @Override public void addRelations(String pid, String subject, String predicate, List<String> objects, boolean literal, String comment) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { if (comment == null || comment.isEmpty()) { comment = "No message supplied"; } if (literal) {//cant handle literal yet for (String object : objects) { addRelation(pid, subject, predicate, object, literal, comment); } } if (objects.size() == 1) {//more efficient if only adding one relation addRelation(pid, subject, predicate, objects.get(0), literal, comment); } try { XPathSelector xpath = DOM.createXPathSelector( "rdf", Constants.NAMESPACE_RDF); String datastream; if (subject == null || subject.isEmpty() || subject.equals(pid) || subject.equals("info:fedora/" + pid)) { subject = "info:fedora/" + pid; datastream = "RELS-EXT"; } else { datastream = "RELS-INT"; } String rels = getXMLDatastreamContents(pid, datastream, null); Document relsDoc = DOM.stringToDOM(rels, true); Node rdfDescriptionNode = xpath.selectNode( relsDoc, "/rdf:RDF/rdf:Description[@rdf:about='" + subject + "']"); URI predURI = new URI(predicate); if (!predURI.isAbsolute()) { predicate = "info:fedora/" + predicate; } String[] splits = predicate.split("#"); for (String object : objects) { if (!object.startsWith("info:fedora/")) { object = "info:fedora/" + object; } Element relationsShipElement = relsDoc.createElementNS(splits[0] + "#", splits[1]); relationsShipElement.setAttributeNS(Constants.NAMESPACE_RDF, "rdf:resource", object); rdfDescriptionNode.appendChild(relationsShipElement); } modifyDatastreamByValue( pid, datastream, ChecksumType.MD5, null, DOM.domToString(relsDoc).getBytes("UTF-8"), null, "application/rdf+xml", comment, null); } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("Failed to transform RELS-EXT", e); } catch (TransformerException e) { throw new BackendMethodFailedException("Failed to transform RELS-EXT", e); } catch (URISyntaxException e) { throw new BackendMethodFailedException("Failed to parse predicate as an URI", e); } } @Override public List<FedoraRelation> getNamedRelations(String pid, String name, Long asOfTime) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { //TODO use asOfTime here, when fedora supports it String subject = pid; if (!subject.startsWith("info:fedora/")) { subject = "info:fedora/" + subject; } WebResource temp = restApi.path("/") .path(pid) .path("/relationships/") .queryParam("subject", subject) .queryParam("format", "n-triples"); if (name != null) { temp = temp.queryParam("predicate", name); } String relationString = temp.get(String.class); String[] lines = relationString.split("\n"); List<FedoraRelation> relations = new ArrayList<FedoraRelation>(); for (String line : lines) { String[] elements = line.split(" "); if (elements.length > 2) { FedoraRelation rel = new FedoraRelation( cleanInfo(elements[0]), clean(elements[1]), cleanInfo(elements[2])); if (elements[2].startsWith("<info:fedora/")) { rel.setLiteral(false); } else { rel.setLiteral(true); } relations.add(rel); } } return relations; } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied: pid '" + pid + "'", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw new BackendInvalidResourceException("Resource '" + pid + "'not found", e); } else { throw new BackendMethodFailedException("Server error for '" + pid + "'", e); } } } private String clean(String element) { if (element.startsWith("<") && element.endsWith(">")) { element = element.substring(1, element.length() - 1); } return element; //To change body of created methods use File | Settings | File Templates. } private String cleanInfo(String element) { element = clean(element); if (element.startsWith("info:fedora/")) { element = element.substring("info:fedora/".length()); } return element; //To change body of created methods use File | Settings | File Templates. } @Override public void deleteRelation(String pid, String subject, String predicate, String object, boolean literal, String comment) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { if (comment == null || comment.isEmpty()) { comment = "No message supplied"; } //TODO, fedora should take this logmessage if (!literal) { if (!object.startsWith("info:fedora/")) { object = "info:fedora/" + object; } } URI predURI = new URI(predicate); if (!predURI.isAbsolute()) { predicate = "info:fedora/" + predicate; } restApi.path("/") .path(pid) .path("/relationships/") .queryParam("predicate", predicate) .queryParam("object", object) .queryParam("isLiteral", "" + literal) .delete(); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied: pid '" + pid + "'", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw new BackendInvalidResourceException("Resource '" + pid + "'not found", e); } else { throw new BackendMethodFailedException("Server error for '" + pid + "'", e); } } catch (URISyntaxException e) { throw new BackendMethodFailedException("Failed to parse predicate as an URI", e); } } @Override public void modifyObjectLabel(String pid, String name, String comment) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { if (comment == null || comment.isEmpty()) { comment = "No message supplied"; } restApi.path("/") .path(URLEncoder.encode(pid, "UTF-8")) .queryParam("label", name) .queryParam("logMessage", comment) .put(); } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw new BackendInvalidResourceException("Resource not found", e); } else { throw new BackendMethodFailedException("Server error", e); } } } @Override public List<SearchResult> fieldsearch(String query, int offset, int pageLength) throws BackendMethodFailedException, BackendInvalidCredsException { try { ResultType searchResult = restApi.queryParam("terms", query) .queryParam("maxResults", pageLength + "") .queryParam("resultFormat", "xml") .queryParam("pid", "true") .queryParam("label", "true") .queryParam("state", "true") .queryParam("cDate", "true") .queryParam("mDate", "true") .get(ResultType.class); if (offset > 0) { for (int i = 1; i <= offset; i++) { String token = searchResult.getListSession().getValue().getToken(); searchResult = restApi.queryParam("query", query) .queryParam("sessionToken", token) .queryParam("resultFormat", "xml") .get(ResultType.class); } } List<SearchResult> outputResults = new ArrayList<SearchResult>( searchResult.getResultList().getObjectFields().size()); for (ObjectFieldsType objectFieldsType : searchResult.getResultList().getObjectFields()) { outputResults.add( new SearchResult( objectFieldsType.getPid().getValue(), objectFieldsType.getLabel().getValue(), objectFieldsType.getState().getValue(), DateUtils.parseDateStrict(objectFieldsType.getCDate().getValue()).getTime(), DateUtils.parseDateStrict(objectFieldsType.getMDate().getValue()).getTime()) ); } return outputResults; } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied", e); } else { throw new BackendMethodFailedException("Server error", e); } } catch (ParseException e) { throw new BackendMethodFailedException("Failed to parse date from search result", e); } } @Override public void addExternalDatastream(String pid, String datastream, String label, String url, String formatURI, String mimeType, String checksumType, String checksum, String comment) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { if (comment == null || comment.isEmpty()) { comment = "No message supplied"; } /* @PathParam(RestParam.PID) String pid, @PathParam(RestParam.DSID) String dsID, @QueryParam(RestParam.CONTROL_GROUP) @DefaultValue("X") String controlGroup, @QueryParam(RestParam.DS_LOCATION) String dsLocation, @QueryParam(RestParam.ALT_IDS) List<String> altIDs, @QueryParam(RestParam.DS_LABEL) String dsLabel, @QueryParam(RestParam.VERSIONABLE) @DefaultValue("true") Boolean versionable, @QueryParam(RestParam.DS_STATE) @DefaultValue("A") String dsState, @QueryParam(RestParam.FORMAT_URI) String formatURI, @QueryParam(RestParam.CHECKSUM_TYPE) String checksumType, @QueryParam(RestParam.CHECKSUM) String checksum, @QueryParam(RestParam.MIME_TYPE) String mimeType, @QueryParam(RestParam.LOG_MESSAGE) String logMessage */ WebResource resource = restApi.path("/") .path(URLEncoder.encode(pid, "UTF-8")) .path("/datastreams/") .path(URLEncoder.encode(datastream, "UTF-8")) .queryParam("controlGroup", "R") .queryParam("dsLocation", url) .queryParam("dsLabel", label) .queryParam("formatURI", formatURI) .queryParam("mimeType", mimeType) .queryParam("logMessage", comment); if (checksumType != null) { resource = resource.queryParam("checksumType", checksumType); } if (checksum != null) { resource = resource.queryParam("checksum", checksum); } resource.post(); } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied: pid '" + pid + "'", e); } else if (e.getResponse().getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw new BackendInvalidResourceException("Resource '" + pid + "'not found", e); } else { throw new BackendMethodFailedException("Server error for '" + pid + "'", e); } } } @Override public Validation validate(String pid) throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException { try { WebResource format = restApi.path("/").path( URLEncoder.encode( pid, "UTF-8") ).path("/validate").queryParam( "format", "text/xml"); return format.get(Validation.class); } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } } @Override public String newEmptyObject(String pid, List<String> oldIDs, List<String> collections, String logMessage) throws BackendMethodFailedException, BackendInvalidCredsException { try { InputStream emptyObjectStream = Thread.currentThread() .getContextClassLoader() .getResourceAsStream("EmptyObject.xml"); Document emptyObject = DOM.streamToDOM(emptyObjectStream, true); XPathSelector xpath = DOM.createXPathSelector( "foxml", Constants.NAMESPACE_FOXML, "rdf", Constants.NAMESPACE_RDF, "d", Constants.NAMESPACE_RELATIONS, "dc", Constants.NAMESPACE_DC, "oai_dc", Constants.NAMESPACE_OAIDC); //Set pid Node pidNode = xpath.selectNode(emptyObject, "/foxml:digitalObject/@PID"); pidNode.setNodeValue(pid); Node rdfNode = xpath.selectNode( emptyObject, "/foxml:digitalObject/foxml:datastream/foxml:datastreamVersion/foxml:xmlContent/rdf:RDF/rdf:Description/@rdf:about"); rdfNode.setNodeValue("info:fedora/" + pid); //add Old Identifiers to DC Node dcIdentifierNode = xpath.selectNode( emptyObject, "/foxml:digitalObject/foxml:datastream/foxml:datastreamVersion/foxml:xmlContent/oai_dc:dc/dc:identifier"); dcIdentifierNode.setTextContent(pid); Node parent = dcIdentifierNode.getParentNode(); for (String oldID : oldIDs) { Node clone = dcIdentifierNode.cloneNode(true); clone.setTextContent(oldID); parent.appendChild(clone); } Node collectionRelationNode = xpath.selectNode( emptyObject, "/foxml:digitalObject/foxml:datastream/foxml:datastreamVersion/foxml:xmlContent/rdf:RDF/rdf:Description/d:isPartOfCollection"); parent = collectionRelationNode.getParentNode(); //remove the placeholder relationNode parent.removeChild(collectionRelationNode); for (String collection : collections) { Node clone = collectionRelationNode.cloneNode(true); clone.getAttributes().getNamedItem("rdf:resource").setNodeValue("info:fedora/" + collection); parent.appendChild(clone); } String createdPid = restApi.path("/") .path(URLEncoder.encode(pid, "UTF-8")) .queryParam("state", "I") .type(MediaType.TEXT_XML_TYPE) .post(String.class, DOM.domToString(emptyObject)); return createdPid; } catch (UnsupportedEncodingException e) { throw new BackendMethodFailedException("UTF-8 not known....", e); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == ClientResponse.Status.UNAUTHORIZED.getStatusCode()) { throw new BackendInvalidCredsException("Invalid Credentials Supplied", e); } else { throw new BackendMethodFailedException("Server error", e); } } catch (TransformerException e) { throw new BackendMethodFailedException("Failed to convert DC back to string", e); } } }
Fixed stupid mediatype bug
central-fedoraClient/src/main/java/dk/statsbiblioteket/doms/central/connectors/fedora/FedoraRest.java
Fixed stupid mediatype bug
Java
apache-2.0
d8101729711ac6aab9b2e7072dda06856df99abd
0
Moocar/logback-gelf,captaininspiration/logback-gelf,exabrial/logback-gelf
package me.moocar.logbackgelf; import java.io.IOException; import java.net.*; import java.util.List; /** * Responsible for sending packet(s) to the graylog2 server */ public class Transport { private final InetAddress graylog2ServerAddress; private final int graylog2ServerPort; private final SocketAddress loopbackAddress = new InetSocketAddress("localhost", 0); public Transport(int graylog2ServerPort, InetAddress graylog2ServerAddress) { this.graylog2ServerPort = graylog2ServerPort; this.graylog2ServerAddress = graylog2ServerAddress; } /** * Sends a single packet GELF message to the graylog2 server * * @param data gzipped GELF Message (JSON) */ public void send(byte[] data) { DatagramPacket datagramPacket = new DatagramPacket(data, data.length, graylog2ServerAddress, graylog2ServerPort); sendPacket(datagramPacket); } /** * Sends a bunch of GELF Chunks to the graylog2 server * * @param packets The packets to send over the wire */ public void send(List<byte[]> packets) { for(byte[] packet : packets) { send(packet); } } private void sendPacket(DatagramPacket datagramPacket) { DatagramSocket datagramSocket = getDatagramSocket(); try { datagramSocket.send(datagramPacket); } catch (IOException ex) { throw new RuntimeException(ex); } finally { datagramSocket.close(); } } private DatagramSocket getDatagramSocket() { try { return new DatagramSocket(loopbackAddress); } catch (SocketException ex) { throw new RuntimeException(ex); } } }
src/main/java/me/moocar/logbackgelf/Transport.java
package me.moocar.logbackgelf; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.util.List; /** * Responsible for sending packet(s) to the graylog2 server */ public class Transport { private final InetAddress graylog2ServerAddress; private final int graylog2ServerPort; public Transport(int graylog2ServerPort, InetAddress graylog2ServerAddress) { this.graylog2ServerPort = graylog2ServerPort; this.graylog2ServerAddress = graylog2ServerAddress; } /** * Sends a single packet GELF message to the graylog2 server * * @param data gzipped GELF Message (JSON) */ public void send(byte[] data) { DatagramPacket datagramPacket = new DatagramPacket(data, data.length, graylog2ServerAddress, graylog2ServerPort); sendPacket(datagramPacket); } /** * Sends a bunch of GELF Chunks to the graylog2 server * * @param packets The packets to send over the wire */ public void send(List<byte[]> packets) { for(byte[] packet : packets) { send(packet); } } private void sendPacket(DatagramPacket datagramPacket) { DatagramSocket datagramSocket = getDatagramSocket(); try { datagramSocket.send(datagramPacket); } catch (IOException ex) { throw new RuntimeException(ex); } finally { datagramSocket.close(); } } private DatagramSocket getDatagramSocket() { try { return new DatagramSocket(); } catch (SocketException ex) { throw new RuntimeException(ex); } } }
Changed the DatagramSocket constructor to use the lookback address to bind on. This fixes an issue on Windows systems where the DatagramSocket.close() takes 3000 ms to unbind when connecting to a non exisitig or disabled graylog server in the same subnet.
src/main/java/me/moocar/logbackgelf/Transport.java
Changed the DatagramSocket constructor to use the lookback address to bind on. This fixes an issue on Windows systems where the DatagramSocket.close() takes 3000 ms to unbind when connecting to a non exisitig or disabled graylog server in the same subnet.
Java
apache-2.0
120bfab61202e6f5876d05a7d4d068a108f56aa0
0
JFrogDev/jenkins-artifactory-plugin,JFrogDev/jenkins-artifactory-plugin,AlexeiVainshtein/jenkins-artifactory-plugin,AlexeiVainshtein/jenkins-artifactory-plugin,AlexeiVainshtein/jenkins-artifactory-plugin,JFrogDev/jenkins-artifactory-plugin
/* * Copyright (C) 2010 JFrog Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jfrog.hudson; import com.google.common.collect.Lists; import hudson.model.Item; import hudson.model.TaskListener; import hudson.util.XStream2; import jenkins.model.Jenkins; import org.apache.commons.lang.StringUtils; import org.jfrog.build.api.util.NullLog; import org.jfrog.build.client.ArtifactoryHttpClient; import org.jfrog.build.client.ArtifactoryVersion; import org.jfrog.build.client.ProxyConfiguration; import org.jfrog.build.extractor.clientConfiguration.client.ArtifactoryBaseClient; import org.jfrog.build.extractor.clientConfiguration.client.ArtifactoryBuildInfoClient; import org.jfrog.build.extractor.clientConfiguration.client.ArtifactoryDependenciesClient; import org.jfrog.hudson.util.CredentialManager; import org.jfrog.hudson.util.Credentials; import org.jfrog.hudson.util.JenkinsBuildInfoLog; import org.jfrog.hudson.util.RepositoriesUtils; import org.jfrog.hudson.util.converters.ArtifactoryServerConverter; import org.kohsuke.stapler.DataBoundConstructor; import java.io.IOException; import java.io.Serializable; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /** * Represents an artifactory instance. * * @author Yossi Shaul */ public class ArtifactoryServer implements Serializable { private static final Logger log = Logger.getLogger(ArtifactoryServer.class.getName()); private static final int DEFAULT_CONNECTION_TIMEOUT = 300; // 5 Minutes private final String url; private final String id; // Network timeout in seconds to use both for connection establishment and for unanswered requests private int timeout = DEFAULT_CONNECTION_TIMEOUT; private boolean bypassProxy; // This object is set to Integer instead of int so upon starting if it's missing (due to upgrade from previous version) // This object will be null instead of 0. In the ArtifactoryBuilder there is a check if the object is null then we are // setting to 3 that is the default. private Integer connectionRetry; /** * List of repository keys, last time we checked. Copy on write semantics. */ private transient volatile List<String> repositories; private transient volatile List<VirtualRepository> virtualRepositories; /** * @deprecated: Use org.jfrog.hudson.ArtifactoryServer#getDeployerCredentials()() */ @Deprecated private Credentials deployerCredentials; /** * @deprecated: Use org.jfrog.hudson.ArtifactoryServer#getResolverCredentials() */ @Deprecated private Credentials resolverCredentials; private CredentialsConfig deployerCredentialsConfig; private CredentialsConfig resolverCredentialsConfig; @DataBoundConstructor public ArtifactoryServer(String serverId, String artifactoryUrl, CredentialsConfig deployerCredentialsConfig, CredentialsConfig resolverCredentialsConfig, int timeout, boolean bypassProxy, Integer connectionRetry) { this.url = StringUtils.removeEnd(artifactoryUrl, "/"); this.deployerCredentialsConfig = deployerCredentialsConfig; this.resolverCredentialsConfig = resolverCredentialsConfig; this.timeout = timeout > 0 ? timeout : DEFAULT_CONNECTION_TIMEOUT; this.bypassProxy = bypassProxy; this.id = serverId; this.connectionRetry = connectionRetry != null ? connectionRetry : 3; } public String getName() { return id; } public String getUrl() { return url != null ? url : getName(); } public CredentialsConfig getDeployerCredentialsConfig() { return deployerCredentialsConfig; } public CredentialsConfig getResolverCredentialsConfig() { return resolverCredentialsConfig; } public int getTimeout() { return timeout; } public boolean isBypassProxy() { return bypassProxy; } // To populate the dropdown list from the jelly public List<Integer> getConnectionRetries() { List<Integer> items = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) { items.add(i); } return items; } public int getConnectionRetry() { if (connectionRetry == null) { connectionRetry = 3; } return connectionRetry; } public void setConnectionRetry(int connectionRetry) { this.connectionRetry = connectionRetry; } public List<String> getLocalRepositoryKeys(Credentials credentials) throws IOException { ArtifactoryBuildInfoClient client = createArtifactoryClient(credentials.getUsername(), credentials.getPassword(), createProxyConfiguration(Jenkins.getInstance().proxy)); try { repositories = client.getLocalRepositoriesKeys(); } catch (IOException e) { if (log.isLoggable(Level.FINE)) { log.log(Level.WARNING, "Could not obtain local repositories list from '" + url + "'", e); } else { log.log(Level.WARNING, "Could not obtain local repositories list from '" + url + "': " + e.getMessage()); } throw e; } finally { client.close(); } return repositories; } public List<String> getReleaseRepositoryKeysFirst(DeployerOverrider deployerOverrider, Item item) throws IOException { CredentialsConfig credentialsConfig = CredentialManager.getPreferredDeployer(deployerOverrider, this); List<String> repositoryKeys = getLocalRepositoryKeys(credentialsConfig.getCredentials(item)); if (repositoryKeys == null || repositoryKeys.isEmpty()) { return Lists.newArrayList(); } Collections.sort(repositoryKeys, new RepositoryComparator()); return repositoryKeys; } public List<String> getSnapshotRepositoryKeysFirst(DeployerOverrider deployerOverrider, Item item) throws IOException { CredentialsConfig credentialsConfig = CredentialManager.getPreferredDeployer(deployerOverrider, this); List<String> repositoryKeys = getLocalRepositoryKeys(credentialsConfig.getCredentials(item)); if (repositoryKeys == null || repositoryKeys.isEmpty()) { return Lists.newArrayList(); } Collections.sort(repositoryKeys, Collections.reverseOrder(new RepositoryComparator())); return repositoryKeys; } public Map getStagingStrategy(PluginSettings selectedStagingPlugin, String buildName, Item item) throws IOException { CredentialsConfig resolvingCredentialsConfig = getResolvingCredentialsConfig(); ArtifactoryBuildInfoClient client = createArtifactoryClient(resolvingCredentialsConfig.provideUsername(item), resolvingCredentialsConfig.providePassword(item), createProxyConfiguration(Jenkins.getInstance().proxy)); try { return client.getStagingStrategy(selectedStagingPlugin.getPluginName(), buildName, selectedStagingPlugin.getParamMap()); } finally { client.close(); } } public List<VirtualRepository> getVirtualRepositoryKeys(ResolverOverrider resolverOverrider, Item item) { CredentialsConfig preferredResolver = CredentialManager.getPreferredResolver(resolverOverrider, this); ArtifactoryBuildInfoClient client = createArtifactoryClient(preferredResolver.provideUsername(item), preferredResolver.providePassword(item), createProxyConfiguration(Jenkins.getInstance().proxy)); try { virtualRepositories = RepositoriesUtils.generateVirtualRepos(client); } catch (IOException e) { if (log.isLoggable(Level.FINE)) { log.log(Level.WARNING, "Could not obtain virtual repositories list from '" + url + "'", e); } else { log.log(Level.WARNING, "Could not obtain virtual repositories list from '" + url + "': " + e.getMessage()); } return Lists.newArrayList(); } finally { client.close(); } return virtualRepositories; } public boolean isArtifactoryPro(DeployerOverrider deployerOverrider, Item item) { CredentialsConfig credentialsConfig = CredentialManager.getPreferredDeployer(deployerOverrider, this); try { ArtifactoryHttpClient client = new ArtifactoryHttpClient(url, credentialsConfig.provideUsername(item), credentialsConfig.providePassword(item), new NullLog()); ArtifactoryVersion version = client.getVersion(); return version.hasAddons(); } catch (IOException e) { if (log.isLoggable(Level.FINE)) { log.log(Level.WARNING, "Could not obtain artifactory version from '" + url + "'", e); } else { log.log(Level.WARNING, "Could not obtain artifactory version from '" + url + "': " + e.getMessage()); } } return false; } public List<UserPluginInfo> getStagingUserPluginInfo(DeployerOverrider deployerOverrider, Item item) { List<UserPluginInfo> infosToReturn = Lists.newArrayList(UserPluginInfo.NO_PLUGIN); gatherUserPluginInfo(infosToReturn, "staging", deployerOverrider, item); return infosToReturn; } public List<UserPluginInfo> getPromotionsUserPluginInfo(DeployerOverrider deployerOverrider, Item item) { List<UserPluginInfo> infosToReturn = Lists.newArrayList(UserPluginInfo.NO_PLUGIN); gatherUserPluginInfo(infosToReturn, "promotions", deployerOverrider, item); return infosToReturn; } /** * This method might run on slaves, this is why we provide it with a proxy from the master config */ public ArtifactoryBuildInfoClient createArtifactoryClient(String userName, String password, ProxyConfiguration proxyConfiguration) { ArtifactoryBuildInfoClient client = new ArtifactoryBuildInfoClient(url, userName, password, new NullLog()); client.setConnectionTimeout(timeout); setRetryParams(client); if (!bypassProxy && proxyConfiguration != null) { client.setProxyConfiguration(proxyConfiguration.host, proxyConfiguration.port, proxyConfiguration.username, proxyConfiguration.password); } return client; } /** * Set the retry params for the base client * * @param client - the client to set the params. */ private void setRetryParams(ArtifactoryBaseClient client) { RepositoriesUtils.setRetryParams(getConnectionRetry(), client); } public ProxyConfiguration createProxyConfiguration(hudson.ProxyConfiguration proxy) { ProxyConfiguration proxyConfiguration = null; if (proxy != null) { proxyConfiguration = new ProxyConfiguration(); proxyConfiguration.host = proxy.name; proxyConfiguration.port = proxy.port; proxyConfiguration.username = proxy.getUserName(); proxyConfiguration.password = proxy.getPassword(); } return proxyConfiguration; } /** * This method might run on slaves, this is why we provide it with a proxy from the master config */ public ArtifactoryDependenciesClient createArtifactoryDependenciesClient(String userName, String password, ProxyConfiguration proxyConfiguration, TaskListener listener) { ArtifactoryDependenciesClient client = new ArtifactoryDependenciesClient(url, userName, password, new JenkinsBuildInfoLog(listener)); client.setConnectionTimeout(timeout); setRetryParams(client); if (!bypassProxy && proxyConfiguration != null) { client.setProxyConfiguration(proxyConfiguration.host, proxyConfiguration.port, proxyConfiguration.username, proxyConfiguration.password); } return client; } /** * Decides what are the preferred credentials to use for resolving the repo keys of the server * * @return Preferred credentials for repo resolving. Never null. */ public CredentialsConfig getResolvingCredentialsConfig() { if (resolverCredentialsConfig != null && resolverCredentialsConfig.isCredentialsProvided()) { return getResolverCredentialsConfig(); } if (deployerCredentialsConfig != null) { return getDeployerCredentialsConfig(); } return CredentialsConfig.EMPTY_CREDENTIALS_CONFIG; } private void gatherUserPluginInfo(List<UserPluginInfo> infosToReturn, String pluginKey, DeployerOverrider deployerOverrider, Item item) { CredentialsConfig credentialsConfig = CredentialManager.getPreferredDeployer(deployerOverrider, this); ArtifactoryBuildInfoClient client = createArtifactoryClient(credentialsConfig.provideUsername(item), credentialsConfig.providePassword(item), createProxyConfiguration(Jenkins.getInstance().proxy)); try { Map<String, List<Map>> userPluginInfo = client.getUserPluginInfo(); if (userPluginInfo != null && userPluginInfo.containsKey(pluginKey)) { List<Map> stagingUserPluginInfo = userPluginInfo.get(pluginKey); if (stagingUserPluginInfo != null) { for (Map stagingPluginInfo : stagingUserPluginInfo) { infosToReturn.add(new UserPluginInfo(stagingPluginInfo)); } Collections.sort(infosToReturn, new Comparator<UserPluginInfo>() { public int compare(UserPluginInfo o1, UserPluginInfo o2) { return o1.getPluginName().compareTo(o2.getPluginName()); } }); } } } catch (IOException e) { log.log(Level.WARNING, "Failed to obtain user plugin info: " + e.getMessage()); } finally { client.close(); } } private static class RepositoryComparator implements Comparator<String>, Serializable { public int compare(String o1, String o2) { if (o1.contains("snapshot") && !o2.contains("snapshot")) { return 1; } else { return -1; } } } /** * Log setter for jobs that are using createArtifactoryClient which * creates the client with NullLog object. * * @param listener the listener of the job * @param client the client that was created */ public void setLog(TaskListener listener, ArtifactoryBaseClient client) { client.setLog(new JenkinsBuildInfoLog(listener)); } /** * Page Converter */ public static final class ConverterImpl extends ArtifactoryServerConverter { public ConverterImpl(XStream2 xstream) { super(xstream); } } }
src/main/java/org/jfrog/hudson/ArtifactoryServer.java
/* * Copyright (C) 2010 JFrog Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jfrog.hudson; import com.google.common.collect.Lists; import hudson.model.Item; import hudson.model.TaskListener; import hudson.util.XStream2; import jenkins.model.Jenkins; import org.apache.commons.lang.StringUtils; import org.jfrog.build.api.util.NullLog; import org.jfrog.build.client.ArtifactoryHttpClient; import org.jfrog.build.client.ArtifactoryVersion; import org.jfrog.build.client.ProxyConfiguration; import org.jfrog.build.extractor.clientConfiguration.client.ArtifactoryBaseClient; import org.jfrog.build.extractor.clientConfiguration.client.ArtifactoryBuildInfoClient; import org.jfrog.build.extractor.clientConfiguration.client.ArtifactoryDependenciesClient; import org.jfrog.hudson.action.ActionableHelper; import org.jfrog.hudson.util.CredentialManager; import org.jfrog.hudson.util.Credentials; import org.jfrog.hudson.util.JenkinsBuildInfoLog; import org.jfrog.hudson.util.RepositoriesUtils; import org.jfrog.hudson.util.converters.ArtifactoryServerConverter; import org.kohsuke.stapler.DataBoundConstructor; import java.io.IOException; import java.io.Serializable; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /** * Represents an artifactory instance. * * @author Yossi Shaul */ public class ArtifactoryServer implements Serializable { private static final Logger log = Logger.getLogger(ArtifactoryServer.class.getName()); private static final int DEFAULT_CONNECTION_TIMEOUT = 300; // 5 Minutes private final String url; private final String id; // Network timeout in seconds to use both for connection establishment and for unanswered requests private int timeout = DEFAULT_CONNECTION_TIMEOUT; private boolean bypassProxy; // This object is set to Integer instead of int so upon starting if it's missing (due to upgrade from previous version) // This object will be null instead of 0. In the ArtifactoryBuilder there is a check if the object is null then we are // setting to 3 that is the default. private Integer connectionRetry; /** * List of repository keys, last time we checked. Copy on write semantics. */ private transient volatile List<String> repositories; private transient volatile List<VirtualRepository> virtualRepositories; /** * @deprecated: Use org.jfrog.hudson.ArtifactoryServer#getDeployerCredentials()() */ @Deprecated private Credentials deployerCredentials; /** * @deprecated: Use org.jfrog.hudson.ArtifactoryServer#getResolverCredentials() */ @Deprecated private Credentials resolverCredentials; private CredentialsConfig deployerCredentialsConfig; private CredentialsConfig resolverCredentialsConfig; @DataBoundConstructor public ArtifactoryServer(String serverId, String artifactoryUrl, CredentialsConfig deployerCredentialsConfig, CredentialsConfig resolverCredentialsConfig, int timeout, boolean bypassProxy, Integer connectionRetry) { this.url = StringUtils.removeEnd(artifactoryUrl, "/"); this.deployerCredentialsConfig = deployerCredentialsConfig; this.resolverCredentialsConfig = resolverCredentialsConfig; this.timeout = timeout > 0 ? timeout : DEFAULT_CONNECTION_TIMEOUT; this.bypassProxy = bypassProxy; this.id = serverId; this.connectionRetry = connectionRetry; } public String getName() { return id; } public String getUrl() { return url != null ? url : getName(); } public CredentialsConfig getDeployerCredentialsConfig() { return deployerCredentialsConfig; } public CredentialsConfig getResolverCredentialsConfig() { return resolverCredentialsConfig; } public int getTimeout() { return timeout; } public boolean isBypassProxy() { return bypassProxy; } // To populate the dropdown list from the jelly public List<Integer> getConnectionRetries() { List<Integer> items = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) { items.add(i); } return items; } public int getConnectionRetry() { if (connectionRetry == null) { connectionRetry = 3; } return connectionRetry; } public void setConnectionRetry(int connectionRetry) { this.connectionRetry = connectionRetry; } public List<String> getLocalRepositoryKeys(Credentials credentials) throws IOException { ArtifactoryBuildInfoClient client = createArtifactoryClient(credentials.getUsername(), credentials.getPassword(), createProxyConfiguration(Jenkins.getInstance().proxy)); try { repositories = client.getLocalRepositoriesKeys(); } catch (IOException e) { if (log.isLoggable(Level.FINE)) { log.log(Level.WARNING, "Could not obtain local repositories list from '" + url + "'", e); } else { log.log(Level.WARNING, "Could not obtain local repositories list from '" + url + "': " + e.getMessage()); } throw e; } finally { client.close(); } return repositories; } public List<String> getReleaseRepositoryKeysFirst(DeployerOverrider deployerOverrider, Item item) throws IOException { CredentialsConfig credentialsConfig = CredentialManager.getPreferredDeployer(deployerOverrider, this); List<String> repositoryKeys = getLocalRepositoryKeys(credentialsConfig.getCredentials(item)); if (repositoryKeys == null || repositoryKeys.isEmpty()) { return Lists.newArrayList(); } Collections.sort(repositoryKeys, new RepositoryComparator()); return repositoryKeys; } public List<String> getSnapshotRepositoryKeysFirst(DeployerOverrider deployerOverrider, Item item) throws IOException { CredentialsConfig credentialsConfig = CredentialManager.getPreferredDeployer(deployerOverrider, this); List<String> repositoryKeys = getLocalRepositoryKeys(credentialsConfig.getCredentials(item)); if (repositoryKeys == null || repositoryKeys.isEmpty()) { return Lists.newArrayList(); } Collections.sort(repositoryKeys, Collections.reverseOrder(new RepositoryComparator())); return repositoryKeys; } public Map getStagingStrategy(PluginSettings selectedStagingPlugin, String buildName, Item item) throws IOException { CredentialsConfig resolvingCredentialsConfig = getResolvingCredentialsConfig(); ArtifactoryBuildInfoClient client = createArtifactoryClient(resolvingCredentialsConfig.provideUsername(item), resolvingCredentialsConfig.providePassword(item), createProxyConfiguration(Jenkins.getInstance().proxy)); try { return client.getStagingStrategy(selectedStagingPlugin.getPluginName(), buildName, selectedStagingPlugin.getParamMap()); } finally { client.close(); } } public List<VirtualRepository> getVirtualRepositoryKeys(ResolverOverrider resolverOverrider, Item item) { CredentialsConfig preferredResolver = CredentialManager.getPreferredResolver(resolverOverrider, this); ArtifactoryBuildInfoClient client = createArtifactoryClient(preferredResolver.provideUsername(item), preferredResolver.providePassword(item), createProxyConfiguration(Jenkins.getInstance().proxy)); try { virtualRepositories = RepositoriesUtils.generateVirtualRepos(client); } catch (IOException e) { if (log.isLoggable(Level.FINE)) { log.log(Level.WARNING, "Could not obtain virtual repositories list from '" + url + "'", e); } else { log.log(Level.WARNING, "Could not obtain virtual repositories list from '" + url + "': " + e.getMessage()); } return Lists.newArrayList(); } finally { client.close(); } return virtualRepositories; } public boolean isArtifactoryPro(DeployerOverrider deployerOverrider, Item item) { CredentialsConfig credentialsConfig = CredentialManager.getPreferredDeployer(deployerOverrider, this); try { ArtifactoryHttpClient client = new ArtifactoryHttpClient(url, credentialsConfig.provideUsername(item), credentialsConfig.providePassword(item), new NullLog()); ArtifactoryVersion version = client.getVersion(); return version.hasAddons(); } catch (IOException e) { if (log.isLoggable(Level.FINE)) { log.log(Level.WARNING, "Could not obtain artifactory version from '" + url + "'", e); } else { log.log(Level.WARNING, "Could not obtain artifactory version from '" + url + "': " + e.getMessage()); } } return false; } public List<UserPluginInfo> getStagingUserPluginInfo(DeployerOverrider deployerOverrider, Item item) { List<UserPluginInfo> infosToReturn = Lists.newArrayList(UserPluginInfo.NO_PLUGIN); gatherUserPluginInfo(infosToReturn, "staging", deployerOverrider, item); return infosToReturn; } public List<UserPluginInfo> getPromotionsUserPluginInfo(DeployerOverrider deployerOverrider, Item item) { List<UserPluginInfo> infosToReturn = Lists.newArrayList(UserPluginInfo.NO_PLUGIN); gatherUserPluginInfo(infosToReturn, "promotions", deployerOverrider, item); return infosToReturn; } /** * This method might run on slaves, this is why we provide it with a proxy from the master config */ public ArtifactoryBuildInfoClient createArtifactoryClient(String userName, String password, ProxyConfiguration proxyConfiguration) { ArtifactoryBuildInfoClient client = new ArtifactoryBuildInfoClient(url, userName, password, new NullLog()); client.setConnectionTimeout(timeout); setRetryParams(client); if (!bypassProxy && proxyConfiguration != null) { client.setProxyConfiguration(proxyConfiguration.host, proxyConfiguration.port, proxyConfiguration.username, proxyConfiguration.password); } return client; } /** * Set the retry params for the base client * * @param client - the client to set the params. */ private void setRetryParams(ArtifactoryBaseClient client) { RepositoriesUtils.setRetryParams(connectionRetry, client); } public ProxyConfiguration createProxyConfiguration(hudson.ProxyConfiguration proxy) { ProxyConfiguration proxyConfiguration = null; if (proxy != null) { proxyConfiguration = new ProxyConfiguration(); proxyConfiguration.host = proxy.name; proxyConfiguration.port = proxy.port; proxyConfiguration.username = proxy.getUserName(); proxyConfiguration.password = proxy.getPassword(); } return proxyConfiguration; } /** * This method might run on slaves, this is why we provide it with a proxy from the master config */ public ArtifactoryDependenciesClient createArtifactoryDependenciesClient(String userName, String password, ProxyConfiguration proxyConfiguration, TaskListener listener) { ArtifactoryDependenciesClient client = new ArtifactoryDependenciesClient(url, userName, password, new JenkinsBuildInfoLog(listener)); client.setConnectionTimeout(timeout); setRetryParams(client); if (!bypassProxy && proxyConfiguration != null) { client.setProxyConfiguration(proxyConfiguration.host, proxyConfiguration.port, proxyConfiguration.username, proxyConfiguration.password); } return client; } /** * Decides what are the preferred credentials to use for resolving the repo keys of the server * * @return Preferred credentials for repo resolving. Never null. */ public CredentialsConfig getResolvingCredentialsConfig() { if (resolverCredentialsConfig != null && resolverCredentialsConfig.isCredentialsProvided()) { return getResolverCredentialsConfig(); } if (deployerCredentialsConfig != null) { return getDeployerCredentialsConfig(); } return CredentialsConfig.EMPTY_CREDENTIALS_CONFIG; } private void gatherUserPluginInfo(List<UserPluginInfo> infosToReturn, String pluginKey, DeployerOverrider deployerOverrider, Item item) { CredentialsConfig credentialsConfig = CredentialManager.getPreferredDeployer(deployerOverrider, this); ArtifactoryBuildInfoClient client = createArtifactoryClient(credentialsConfig.provideUsername(item), credentialsConfig.providePassword(item), createProxyConfiguration(Jenkins.getInstance().proxy)); try { Map<String, List<Map>> userPluginInfo = client.getUserPluginInfo(); if (userPluginInfo != null && userPluginInfo.containsKey(pluginKey)) { List<Map> stagingUserPluginInfo = userPluginInfo.get(pluginKey); if (stagingUserPluginInfo != null) { for (Map stagingPluginInfo : stagingUserPluginInfo) { infosToReturn.add(new UserPluginInfo(stagingPluginInfo)); } Collections.sort(infosToReturn, new Comparator<UserPluginInfo>() { public int compare(UserPluginInfo o1, UserPluginInfo o2) { return o1.getPluginName().compareTo(o2.getPluginName()); } }); } } } catch (IOException e) { log.log(Level.WARNING, "Failed to obtain user plugin info: " + e.getMessage()); } finally { client.close(); } } private static class RepositoryComparator implements Comparator<String>, Serializable { public int compare(String o1, String o2) { if (o1.contains("snapshot") && !o2.contains("snapshot")) { return 1; } else { return -1; } } } /** * Log setter for jobs that are using createArtifactoryClient which * creates the client with NullLog object. * * @param listener the listener of the job * @param client the client that was created */ public void setLog(TaskListener listener, ArtifactoryBaseClient client) { client.setLog(new JenkinsBuildInfoLog(listener)); } /** * Page Converter */ public static final class ConverterImpl extends ArtifactoryServerConverter { public ConverterImpl(XStream2 xstream) { super(xstream); } } }
HAP-855 - Retry capability for requests that fails
src/main/java/org/jfrog/hudson/ArtifactoryServer.java
HAP-855 - Retry capability for requests that fails
Java
apache-2.0
11510f762d8980357d7924f2159a6a93d49438f5
0
Evolveum/connector-siebel
package com.evolveum.polygon.connector.siebel; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.SocketTimeoutException; import java.net.URL; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.EnumMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.ws.WebServiceException; import javax.xml.ws.soap.SOAPFaultException; import javax.xml.xpath.XPathExpressionException; import org.apache.cxf.endpoint.Client; import org.apache.cxf.feature.LoggingFeature; import org.apache.cxf.frontend.ClientProxy; import org.apache.cxf.frontend.ClientProxyFactoryBean; import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; import org.apache.cxf.transport.http.HTTPConduit; import org.apache.cxf.transport.http.HTTPException; import org.apache.cxf.transports.http.configuration.HTTPClientPolicy; import org.identityconnectors.common.logging.Log; import org.identityconnectors.framework.common.exceptions.AlreadyExistsException; import org.identityconnectors.framework.common.exceptions.InvalidAttributeValueException; import org.identityconnectors.framework.common.exceptions.InvalidCredentialException; import org.identityconnectors.framework.common.exceptions.OperationTimeoutException; import org.identityconnectors.framework.common.exceptions.UnknownUidException; import org.identityconnectors.framework.common.objects.Attribute; import org.identityconnectors.framework.common.objects.AttributeInfo; import org.identityconnectors.framework.common.objects.AttributeInfoBuilder; import org.identityconnectors.framework.common.objects.ConnectorObject; import org.identityconnectors.framework.common.objects.ConnectorObjectBuilder; import org.identityconnectors.framework.common.objects.Name; import org.identityconnectors.framework.common.objects.ObjectClass; import org.identityconnectors.framework.common.objects.ObjectClassInfo; import org.identityconnectors.framework.common.objects.ObjectClassInfoBuilder; import org.identityconnectors.framework.common.objects.OperationOptions; import org.identityconnectors.framework.common.objects.OperationalAttributeInfos; import org.identityconnectors.framework.common.objects.OperationalAttributes; import org.identityconnectors.framework.common.objects.ResultsHandler; import org.identityconnectors.framework.common.objects.Schema; import org.identityconnectors.framework.common.objects.SchemaBuilder; import org.identityconnectors.framework.common.objects.SearchResult; import org.identityconnectors.framework.common.objects.Uid; import org.identityconnectors.framework.spi.Configuration; import org.identityconnectors.framework.spi.ConnectorClass; import org.identityconnectors.framework.spi.PoolableConnector; import org.identityconnectors.framework.spi.SearchResultsHandler; import org.identityconnectors.framework.spi.operations.CreateOp; import org.identityconnectors.framework.spi.operations.SchemaOp; import org.identityconnectors.framework.spi.operations.SearchOp; import org.identityconnectors.framework.spi.operations.TestOp; import org.identityconnectors.framework.spi.operations.UpdateOp; import com.evolveum.polygon.connector.siebel.util.Pair; import com.evolveum.polygon.connector.siebel.util.PrimaryXorSecondary; import com.evolveum.polygon.connector.siebel.util.SearchResultLogger; import com.siebel.asi.SWIEmployeeServicesQueryPageInput; import com.siebel.asi.SWIEmployeeServicesQueryPageOutput; import com.siebel.asi.SWISpcEmployeeSpcService; import com.siebel.customui.SiebelEmployeeInsert1Input; import com.siebel.customui.SiebelEmployeeInsert1Output; import com.siebel.customui.SiebelEmployeeUpdate1Input; import com.siebel.customui.SiebelEmployeeUpdate1Output; import com.siebel.customui.SiebelSpcEmployee; import com.siebel.xml.employee_20interface.ListOfEmployeeInterface; import com.siebel.xml.employee_20interface.RelatedEmployeeOrganization; import com.siebel.xml.employee_20interface.RelatedPosition; import com.siebel.xml.employee_20interface.RelatedResponsibility; import com.siebel.xml.swiemployeeio.Employee; import com.siebel.xml.swiemployeeio.EmployeeOrganization; import com.siebel.xml.swiemployeeio.EmployeePosition; import com.siebel.xml.swiemployeeio.EmployeeResponsibility; import com.siebel.xml.swiemployeeio.ListOfSwiemployeeio; import static com.evolveum.polygon.connector.siebel.LogUtils.getAttributeNames; import static com.evolveum.polygon.connector.siebel.Operation.CREATE; import static com.evolveum.polygon.connector.siebel.Operation.UPDATE; import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; import static java.lang.Math.min; import static java.util.Collections.emptyList; import static java.util.EnumSet.of; import static org.identityconnectors.common.CollectionUtil.isEmpty; import static org.identityconnectors.common.StringUtil.isNotEmpty; import static org.identityconnectors.framework.common.objects.AttributeInfo.Flags.MULTIVALUED; import static org.identityconnectors.framework.common.objects.AttributeInfo.Flags.NOT_CREATABLE; import static org.identityconnectors.framework.common.objects.AttributeInfo.Flags.NOT_UPDATEABLE; import static org.identityconnectors.framework.common.objects.AttributeInfo.Flags.REQUIRED; import static org.identityconnectors.framework.common.objects.AttributeUtil.getBooleanValue; import static org.identityconnectors.framework.common.objects.AttributeUtil.getStringValue; import static org.identityconnectors.framework.common.objects.AttributeUtil.isSpecialName; @ConnectorClass(displayNameKey = "siebel.connector.display", configurationClass = SiebelConfiguration.class) public class SiebelConnector implements PoolableConnector, TestOp, SchemaOp, SearchOp<Filter>, CreateOp, UpdateOp { private static final Log LOG = Log.getLog(SiebelConnector.class); private static final int HTTP_STATUS_UNAUTHORIZED = 401; private static final int HTTP_STATUS_REQUEST_TIMEOUT = 408; private static final String EMPLOYEE_ACTIVE = "Active"; private static final String EMPLOYEE_INACTIVE = "Inactive"; private static final String RESOURCE_PROP_VALUE_YES = "Y"; private static final String RESOURCE_PROP_VALUE_NO = "N"; private static final String REQUEST_LOG_FILENAME = "siebel-soap-request.xml"; private static final String RESPONSE_LOG_FILENAME = "siebel-soap-response.xml"; /** * account Id used when testing the connection * * @see #test() test() */ private static final String TEST_ID = "BFLM_DUMMY_HCHKR"; /** * offset passed to the {@code SearchOp} when the first page is requested */ static final int CONNID_SPI_FIRST_PAGE_OFFSET = 1; /** * number of the first row in Siebel */ private static final int SIEBEL_WS_FIRST_ROW_NUMBER = 0; /** * number of the first row in Siebel - as a string */ private static final String SIEBEL_WS_FIRST_ROW_NUMBER_STR = Integer.toString(SIEBEL_WS_FIRST_ROW_NUMBER); /** * constant to be added to the ConnId paged results offset to calculate * the value of the corresponding web service's parameter <i>StartRowNum</i> */ private static final int CONNID_TO_WS_REC_NO_SHIFT = SIEBEL_WS_FIRST_ROW_NUMBER - CONNID_SPI_FIRST_PAGE_OFFSET; private static final Set<AttributeInfo.Flags> F_REQUIRED = of(REQUIRED); private static final Set<AttributeInfo.Flags> F_MULTIVALUED = of(MULTIVALUED); private static final Set<AttributeInfo.Flags> F_MULTIVALUED_READONLY = of(MULTIVALUED, NOT_UPDATEABLE); private static final SearchResult ALL_RESULTS_RETURNED = new SearchResult(); /** * error symbol of a SOAP fault caused by an attempt to create a duplicite * account */ private static final String ERR_SYMBOL_DUPLICITE_LOGIN_NAME = "IDS_ERR_EAI_SA_INSERT_MATCH_FOUND"; private static final String ERR_CODE_SPACE_IN_LOGIN_NAME = "SBL-APS-00195"; /** * error code of a SOAP fault caused by an attempt to change login name * to a login name that is assigned to another account */ private static final String ERR_CODE_DUPLICITE_LOGIN_NAME = "SBL-DAT-00381"; private static final String ERR_CODE_MISSING_LOGIN_NAME = "SBL-DAT-00498"; private static final String ERR_CODE_NOT_FROM_PICKLIST = "SBL-DAT-00225"; private static final String ERR_CODE_NOT_IN_BOUND_LIST = "SBL-EAI-04401"; private static final String ERR_SYMBOL_NOT_IN_BOUND_LIST = "IDS_ERR_EAI_SA_PICK_VALIDATE"; private static final String ERR_CODE_NOT_FROM_LIST_OF_VALUES = "SBL-DAT-00510"; /** * error code of a SOAP fault caused by an invalid value of attribute * &quot;employee position&quot; * * @see #ERR_SYMBOL_INVALID_POSITION */ private static final String ERR_CODE_INVALID_POSITION = "SBL-EAI-04397"; /** * error code of a SOAP fault caused by an invalid value of attribute * &quot;employee organization&quot; or &quot;employee responsibility&quot; * * @see #ERR_SYMBOL_INVALID_ORG_OR_RESP */ private static final String ERR_CODE_INVALID_ORG_OR_RESP = "SBL-EAI-04184"; /** * error symbol of a SOAP fault caused by an invalid value of attribute * &quot;employee position&quot; * * @see #ERR_CODE_INVALID_POSITION */ private static final String ERR_SYMBOL_INVALID_POSITION = "IDS_ERR_EAI_SA_NO_USERKEY"; /** * error symbol of a SOAP fault caused by an invalid value of attribute * &quot;employee organization&quot; or &quot;employee responsibility&quot; * * @see #ERR_CODE_INVALID_ORG_OR_RESP */ private static final String ERR_SYMBOL_INVALID_ORG_OR_RESP = "IDS_EAI_ERR_SA_INT_NOINSERT"; static final String ATTR_ID = "Id"; static final String ATTR_LOGIN_NAME = "LoginName"; static final String ATTR_ALIAS = "Alias"; static final String ATTR_EMPLOYEE_TYPE_CODE = "EmployeeTypeCode"; static final String ATTR_PERSONAL_TITLE = "PersonalTitle"; static final String ATTR_PREFERRED_COMMUNICATION = "PreferredCommunication"; static final String ATTR_TIME_ZONE = "TimeZoneName"; static final String ATTR_USER_TYPE = "UserType"; static final String ATTR_CELL_PHONE = "CellPhone"; static final String ATTR_EMAIL_ADDR = "EMailAddr"; static final String ATTR_FAX = "Fax"; static final String ATTR_FIRST_NAME = "FirstName"; static final String ATTR_JOB_TITLE = "JobTitle"; static final String ATTR_LAST_NAME = "LastName"; static final String ATTR_PHONE = "Phone"; static final String ATTR_SALES_CHANNEL = "SalesChannel"; static final String ATTR_PRIMARY_POSITION = "PrimaryPosition"; static final String ATTR_SECONDARY_POSITIONS = "SecondaryPositions"; static final String ATTR_PRIMARY_ORGANIZATION = "EmployeePrimaryOrganization"; static final String ATTR_SECONDARY_ORGANIZATIONS = "EmployeeSecondaryOrganizations"; static final String ATTR_PRIMARY_RESPONSIBILITY = "PrimaryResponsibility"; static final String ATTR_SECONDARY_RESPONSIBILITIES = "SecondaryResponsibilities"; private static final PrimarySecondaryEmployeeAttribute<EmployeePosition, RelatedPosition> POSITIONS; private static final PrimarySecondaryEmployeeAttribute<EmployeeOrganization, RelatedEmployeeOrganization> ORGANIZATIONS; private static final PrimarySecondaryEmployeeAttribute<EmployeeResponsibility, RelatedResponsibility> RESPONSIBILITIES; static { try { POSITIONS = new PrimarySecondaryEmployeeAttribute<>(EmployeePosition.class, RelatedPosition.class, ATTR_PRIMARY_POSITION, ATTR_SECONDARY_POSITIONS, "PositionId"); ORGANIZATIONS = new PrimarySecondaryEmployeeAttribute<>(EmployeeOrganization.class, RelatedEmployeeOrganization.class, ATTR_PRIMARY_ORGANIZATION, ATTR_SECONDARY_ORGANIZATIONS); RESPONSIBILITIES = new PrimarySecondaryEmployeeAttribute<>(EmployeeResponsibility.class, RelatedResponsibility.class, ATTR_PRIMARY_RESPONSIBILITY, ATTR_SECONDARY_RESPONSIBILITIES); } catch (ReflectiveOperationException ex) { throw new RuntimeException(ex); } } private SiebelConfiguration configuration; private SWISpcEmployeeSpcService queryService; private SiebelSpcEmployee insertUpdateService; private int maxResourcePageSize; private String maxResourcePageSizeStr; /** * contains query input prototypes for each of the search modes * (by Id, by login name, get all) */ private final Map<Filter.Mode, Pair<SWIEmployeeServicesQueryPageInput, Employee>> queryInputPrototypes = new EnumMap<>(Filter.Mode.class); private SoapFaultInspector soapFaultInspector; @Override public Configuration getConfiguration() { return configuration; } @Override public void init(final Configuration configuration) { LOG.info("Initializing connector (connecting to the WS)..."); this.configuration = (SiebelConfiguration) configuration; queryService = createService(SWISpcEmployeeSpcService.class); insertUpdateService = createService(SiebelSpcEmployee.class); setMaxResourcePageSize(this.configuration.getMaxPageSize()); setupQueryInputPrototypes(); try { soapFaultInspector = new SoapFaultInspector(); } catch (XPathExpressionException ex) { throw new RuntimeException(ex); } } private void setMaxResourcePageSize(final int maxResourcePageSize) { this.maxResourcePageSize = maxResourcePageSize; this.maxResourcePageSizeStr = Integer.toString(maxResourcePageSize); } private void setupQueryInputPrototypes() { Pair<SWIEmployeeServicesQueryPageInput, Employee> queryInputPrototype; queryInputPrototype = createQueryInputPrototype(); queryInputPrototypes.put(Filter.Mode.RETURN_ALL, queryInputPrototype); queryInputPrototype = createQueryInputPrototype(); queryInputPrototypes.put(Filter.Mode.SEARCH_BY_ID, queryInputPrototype); queryInputPrototype = createQueryInputPrototype(); queryInputPrototypes.put(Filter.Mode.SEARCH_BY_LOGIN_NAME, queryInputPrototype); } private Pair<SWIEmployeeServicesQueryPageInput, Employee> createQueryInputPrototype() { final SWIEmployeeServicesQueryPageInput queryInput = new SWIEmployeeServicesQueryPageInput(); final Employee employee = new Employee(); final ListOfSwiemployeeio listOfSwiemployeeio = new ListOfSwiemployeeio(); listOfSwiemployeeio.getEmployee().add(employee); queryInput.setListOfSwiemployeeio(listOfSwiemployeeio); return new Pair<>(queryInput, employee); } private <S> S createService(final Class<S> seiClass) { final ClientProxyFactoryBean factory = new JaxWsProxyFactoryBean(); // a new instance must be used for each service final Path soapLogTargetPath = configuration.getSoapLogTargetPath(); if (soapLogTargetPath != null) { try { final Path targetForRequests = soapLogTargetPath.resolve(REQUEST_LOG_FILENAME); final Path targetForResponses = soapLogTargetPath.resolve(RESPONSE_LOG_FILENAME); final URL targetPathURLForRequests = targetForRequests .toUri().toURL(); final URL targetPathURLForResponses = targetForResponses.toUri().toURL(); factory.getFeatures().add(new LoggingFeature(targetPathURLForResponses.toString(), targetPathURLForRequests.toString(), 100_000, true)); } catch (MalformedURLException ex) { LOG.warn(ex, "Couldn't initialize logging of SOAP messages."); } } factory.setAddress (configuration.getWsUrl()); factory.setUsername(configuration.getUsername()); factory.setPassword(configuration.getPassword()); factory.setServiceClass(seiClass); final S result = (S) factory.create(); /* disable chunking: */ final Client client = ClientProxy.getClient(result); final HTTPConduit http = (HTTPConduit) client.getConduit(); final HTTPClientPolicy httpClientPolicy; { httpClientPolicy = new HTTPClientPolicy(); httpClientPolicy.setAllowChunking(false); httpClientPolicy.setConnectionTimeout(configuration.getConnectTimeout()); httpClientPolicy.setReceiveTimeout(configuration.getReceiveTimeout()); } http.setClient(httpClientPolicy); return result; } /** * Used by unit tests. * * @param queryService test query service to be used by this connector */ void init(final SWISpcEmployeeSpcService queryService) { init(queryService, SiebelConfiguration.DEFAULT_MAX_PAGE_SIZE); } /** * Used by unit tests. * * @param queryService test query service to be used by this connector */ void init(final SWISpcEmployeeSpcService queryService, final int maxResourcePageSize) { this.queryService = queryService; setMaxResourcePageSize(maxResourcePageSize); setupQueryInputPrototypes(); } /** * Used by unit tests. * * @param queryService test update service to be used by this connector */ void init(final SiebelSpcEmployee insertUpdateService) { this.insertUpdateService = insertUpdateService; setupQueryInputPrototypes(); } @Override public void dispose() { LOG.info("Disposing connector..."); closeWsClient(insertUpdateService); insertUpdateService = null; closeWsClient(queryService); queryService = null; maxResourcePageSizeStr = null; maxResourcePageSize = -1; queryInputPrototypes.clear(); configuration = null; soapFaultInspector = null; } private static void closeWsClient(final Object service) { if (service != null) { final Client client = ClientProxy.getClient(service); if (client != null) { client.destroy(); } } } @Override public void checkAlive() { } @Override public void test() { LOG.ok("test() ..."); configuration.validate(); executeQueryById(TEST_ID); LOG.ok("test() finished successfully"); } @Override public Schema schema() { LOG.ok("schema()"); final SchemaBuilder schemaBuilder = new SchemaBuilder(SiebelConnector.class); schemaBuilder.defineObjectClass(getEmployeeInfo()); return schemaBuilder.build(); } private static ObjectClassInfo getEmployeeInfo() { final ObjectClassInfoBuilder builder = new ObjectClassInfoBuilder(); builder.addAttributeInfo(new AttributeInfoBuilder(Uid.NAME) .setFlags(of(NOT_CREATABLE, NOT_UPDATEABLE)) .setNativeName(ATTR_ID) .build()); builder.addAttributeInfo(new AttributeInfoBuilder(Name.NAME) .setFlags(of(REQUIRED)) .setNativeName(ATTR_LOGIN_NAME) .build()); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_ALIAS, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_EMPLOYEE_TYPE_CODE, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_PERSONAL_TITLE, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_PREFERRED_COMMUNICATION, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_TIME_ZONE, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_USER_TYPE, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_CELL_PHONE, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_EMAIL_ADDR, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_FAX, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_FIRST_NAME, String.class, F_REQUIRED)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_JOB_TITLE, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_LAST_NAME, String.class, F_REQUIRED)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_PHONE, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_SALES_CHANNEL, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_PRIMARY_POSITION, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_SECONDARY_POSITIONS, String.class, F_MULTIVALUED_READONLY)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_PRIMARY_ORGANIZATION, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_SECONDARY_ORGANIZATIONS, String.class, F_MULTIVALUED)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_PRIMARY_RESPONSIBILITY, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_SECONDARY_RESPONSIBILITIES, String.class, F_MULTIVALUED)); builder.addAttributeInfo(OperationalAttributeInfos.ENABLE); return builder.build(); } @Override public org.identityconnectors.framework.common.objects.filter.FilterTranslator<Filter> createFilterTranslator(final ObjectClass objectClass, final OperationOptions options) { return new FilterTranslator(); } @Override public void executeQuery(final ObjectClass objectClass, final Filter query, final ResultsHandler handler, final OperationOptions options) { if (!objectClass.equals(ObjectClass.ACCOUNT)) { return; } LOG.ok("executeQuery(query={0}, options={1})", query, options); final SWIEmployeeServicesQueryPageInput queryInput = setupQueryInput(query); findMatchingObjects(queryInput, handler, options); } private void findMatchingObjects(final SWIEmployeeServicesQueryPageInput queryInput, final ResultsHandler resultsHandler, final OperationOptions options) { SWIEmployeeServicesQueryPageOutput queryResponse; List<Employee> employees; Boolean moreResultsAvailable = TRUE; final Integer requestedPageSize = normalizePagedOption(options.getPageSize()); final Integer requestedOffset = (requestedPageSize != null) ? normalizePagedOption(options.getPagedResultsOffset()) : null; int resourceOffset = (requestedOffset != null) ? requestedOffset + CONNID_TO_WS_REC_NO_SHIFT : 0; final SearchResultLogger employeeLogger = new SearchResultLogger(LOG); if (requestedPageSize == null) { queryInput.setPageSize(maxResourcePageSizeStr); main: do { int employeesCount; queryInput.setStartRowNum(Integer.toString(resourceOffset)); LOG.ok(" - WS input: start row = {0}, page size = {1}", queryInput.getStartRowNum(), queryInput.getPageSize()); queryResponse = executeQuery(queryInput); employees = queryResponse.getListOfSwiemployeeio().getEmployee(); employeesCount = employees.size(); LOG.ok(" - WS output: count = {0}, last page = {1}", employeesCount, queryResponse.getLastPage()); int handledCount = 0; for (Employee employee : employees) { boolean cont = resultsHandler.handle(createAccount(employee)); if (!cont) { LOG.ok(" - the connector only accepted {0} object(s)", handledCount); break main; } handledCount++; employeeLogger.logEmployee(employee); } moreResultsAvailable = isMoreResultsAvailable(queryResponse); resourceOffset += employeesCount; } while (moreResultsAvailable == TRUE); } else { int requestedRecordsRemaining = requestedPageSize; main: do { int resourcePageSize = min(requestedRecordsRemaining, maxResourcePageSize); int employeesCount; queryInput.setStartRowNum(Integer.toString(resourceOffset)); queryInput.setPageSize(Integer.toString(resourcePageSize)); LOG.ok(" - WS input: start row = {0}, page size = {1}", queryInput.getStartRowNum(), queryInput.getPageSize()); queryResponse = executeQuery(queryInput); employees = queryResponse.getListOfSwiemployeeio().getEmployee(); employeesCount = employees.size(); LOG.ok(" - WS output: count = {0}, last page = {1}", employeesCount, queryResponse.getLastPage()); int handledCount = 0; for (Employee employee : employees) { boolean cont = resultsHandler.handle(createAccount(employee)); if (!cont) { LOG.ok(" - the connector only accepted {0} object(s)", handledCount); break main; } handledCount++; employeeLogger.logEmployee(employee); } moreResultsAvailable = isMoreResultsAvailable(queryResponse); if (moreResultsAvailable != TRUE) { break; } resourceOffset += employeesCount; requestedRecordsRemaining -= employeesCount; } while (requestedRecordsRemaining > 0); } employeeLogger.writeResultToLog(); if (moreResultsAvailable == null) { //should be TRUE or FALSE recordInvalidValueOfLastPage(queryResponse); } if (resultsHandler instanceof SearchResultsHandler) { final SearchResultsHandler handler = (SearchResultsHandler) resultsHandler; final SearchResult searchResult = (moreResultsAvailable == TRUE) ? new SearchResult(null, -1, false) : ALL_RESULTS_RETURNED; handler.handleResult(searchResult); } else { LOG.warn("The ResultsHandler doesn't implement interface SearchResultsHandler: {0}", resultsHandler.getClass().getName()); } } private Employee findEmployeeById(final Uid uid) { return findEmployeeById(uid.getUidValue()); } private Employee findEmployeeById(final String id) { final Employee result; final SWIEmployeeServicesQueryPageOutput queryOutput = executeQueryById(id); final List<Employee> employees = queryOutput.getListOfSwiemployeeio().getEmployee(); if (isEmpty(employees)) { result = null; } else if (employees.size() == 1) { result = employees.get(0); } else { LOG.error("There were multiple accounts ({1}) found when searching by Id ({0}).", id, employees.size()); throw new IllegalStateException("Multiple accounts found by Id."); } return result; } private SWIEmployeeServicesQueryPageOutput executeQueryById(final String id) { final SWIEmployeeServicesQueryPageInput testQueryInput; testQueryInput = setupQueryInput(Filter.byId(id)); testQueryInput.setStartRowNum(SIEBEL_WS_FIRST_ROW_NUMBER_STR); testQueryInput.setPageSize("1"); return executeQuery(testQueryInput); } private SWIEmployeeServicesQueryPageOutput executeQuery(final SWIEmployeeServicesQueryPageInput queryInput) { try { return queryService.swiEmployeeServicesQueryPage(queryInput); } catch (WebServiceException ex) { handleWebServiceException(ex); throw ex; } } /** * Determines whether there are (possibly) more matching results available * according to the given response from Siebel. * * @param queryResponse response from the Siebel web service * @return {@code Boolean.TRUE} if more results are (possibly) available, * {@code Boolean.FALSE} if there are no more results available, * {@code null} if the response from Siebel contained an invalid * value */ private static Boolean isMoreResultsAvailable(final SWIEmployeeServicesQueryPageOutput queryResponse) { final String isLastPageStr = getMoreResultsAvailableStr(queryResponse); if (isLastPageStr == null) { return null; } switch (isLastPageStr) { case "true": return FALSE; case "false": return TRUE; } return null; } private static void recordInvalidValueOfLastPage(final SWIEmployeeServicesQueryPageOutput queryResponse) { LOG.warn("Unsupported value of attribute \"LastPage\" in the response: {0}", getMoreResultsAvailableStr(queryResponse)); } private static String getMoreResultsAvailableStr(final SWIEmployeeServicesQueryPageOutput queryResponse) { return queryResponse.getLastPage(); } private SWIEmployeeServicesQueryPageInput setupQueryInput(final Filter query) { final Filter.Mode queryMode = (query == null) ? Filter.Mode.RETURN_ALL : query.mode; final Pair<SWIEmployeeServicesQueryPageInput, Employee> prototype = queryInputPrototypes.get(queryMode); switch (queryMode) { case SEARCH_BY_ID: prototype.b.setId(query.param); break; case SEARCH_BY_LOGIN_NAME: prototype.b.setLoginName(query.param); break; } return prototype.a; } private static ConnectorObject createAccount(final Employee employee) { final ConnectorObjectBuilder builder = new ConnectorObjectBuilder(); builder.setUid (employee.getId()); builder.setName(employee.getLoginName()); builder.addAttribute(ATTR_ALIAS, employee.getAlias()); builder.addAttribute(ATTR_EMPLOYEE_TYPE_CODE, employee.getEmployeeTypeCode()); builder.addAttribute(ATTR_PERSONAL_TITLE, employee.getPersonalTitle()); builder.addAttribute(ATTR_PREFERRED_COMMUNICATION, employee.getPreferredCommunications()); builder.addAttribute(ATTR_TIME_ZONE, employee.getTimeZone()); builder.addAttribute(ATTR_USER_TYPE, employee.getUserType()); builder.addAttribute(ATTR_CELL_PHONE, employee.getCellPhone()); builder.addAttribute(ATTR_EMAIL_ADDR, employee.getEMailAddr()); builder.addAttribute(ATTR_FAX, employee.getFax()); builder.addAttribute(ATTR_FIRST_NAME, employee.getFirstName()); builder.addAttribute(ATTR_JOB_TITLE, employee.getJobTitle()); builder.addAttribute(ATTR_LAST_NAME, employee.getLastName()); builder.addAttribute(ATTR_PHONE, employee.getPhone()); builder.addAttribute(ATTR_SALES_CHANNEL, employee.getSalesChannel()); POSITIONS.fillConnObjAttributes(employee, builder); ORGANIZATIONS.fillConnObjAttributes(employee, builder); RESPONSIBILITIES.fillConnObjAttributes(employee, builder); builder.addAttribute(OperationalAttributes.ENABLE_NAME, isEmployeeActive(employee)); final ConnectorObject account = builder.build(); return account; } private static Boolean isEmployeeActive(final Employee employee) { final String status = employee.getEmployeeStatus(); if (status == null) { LOG.warn("Employee {0} has assigned no employee status.", employee.getId()); return null; } switch (status) { case EMPLOYEE_ACTIVE: return TRUE; case EMPLOYEE_INACTIVE: return FALSE; default: LOG.warn("Invalid employee status ({1}) assigned to employee #{0}.", employee.getId(), status); return null; } } private static String employeeActiveAsString(final Boolean active) { final String result; if (active == null) { result = null; } else { result = active ? EMPLOYEE_ACTIVE : EMPLOYEE_INACTIVE; } return result; } /** * Normalizes the page size such that it is either positive or {@code null}. * * @param pageSize page size to be normalized (possibly {@code null}) * @return the original page size if it is {@code null} or positive; * {@code null} otherwise */ private static Integer normalizePagedOption(final Integer pageSize) { return ((pageSize != null) && (pageSize <= 0)) ? null : pageSize; } @Override public Uid create(final ObjectClass objectClass, final Set<Attribute> createAttributes, final OperationOptions options) { if (!objectClass.equals(ObjectClass.ACCOUNT)) { throw new UnsupportedOperationException("This connector can only create accounts. Requested ObjectClass: " + objectClass.getObjectClassValue()); } if (LOG.isOk()) { LOG.ok("create(attributes = {1})", getAttributeNames(createAttributes)); } final SiebelEmployeeInsert1Input insertInput = createInsertInput(createAttributes); final SiebelEmployeeInsert1Output insertOutput; try { insertOutput = insertUpdateService.siebelEmployeeInsert1(insertInput); } catch (WebServiceException ex) { if (ex instanceof SOAPFaultException) { handleCreateOpSoapFault((SOAPFaultException) ex); } handleWebServiceException(ex); throw ex; } final String id = insertOutput.getListOfEmployeeInterface().getEmployee().get(0).getId(); return new Uid(id); } @Override public Uid update(final ObjectClass objectClass, final Uid uid, final Set<Attribute> replaceAttributes, final OperationOptions options) { if (!objectClass.equals(ObjectClass.ACCOUNT)) { throw new UnsupportedOperationException("This connector can only update accounts. Requested ObjectClass: " + objectClass.getObjectClassValue()); } if (LOG.isOk()) { LOG.ok("update(uid = {0}, attributes = {1})", uid.getUidValue(), getAttributeNames(replaceAttributes)); } final Set<String> missingAttributes = findMissingUpdateAttributes(replaceAttributes); final Set<Attribute> combinedReplaceAttributes; if (isEmpty(missingAttributes)) { combinedReplaceAttributes = replaceAttributes; } else { LOG.ok(" - needs to GET extra attributes: {0}", missingAttributes); final Employee employee = findEmployeeById(uid); if (employee == null) { throw new UnknownUidException(uid, ObjectClass.ACCOUNT); } combinedReplaceAttributes = addMissingAttributes(replaceAttributes, missingAttributes, employee); } final SiebelEmployeeUpdate1Input updateInput = createUpdateInput(uid, combinedReplaceAttributes); final SiebelEmployeeUpdate1Output updateOutput; try { updateOutput = insertUpdateService.siebelEmployeeUpdate1(updateInput); } catch (WebServiceException ex) { if (ex instanceof SOAPFaultException) { handleUpdateOpSoapFault((SOAPFaultException) ex); } handleWebServiceException(ex); throw ex; } final String id = updateOutput.getListOfEmployeeInterface().getEmployee().get(0).getId(); return new Uid(id); } /** * Creates a new set of attributes by combining the current attributes * with new attributes created from a given {@code Employee} object. * The attributes specified by the parameter are left unchanged * in the resulting set. * * @param currentAttributes current set of attributes * @param namesOfMissingAttributes names of attributes whose values are * to be taken from the given employee * @param employee employee to the values of missing attributes from * @return new set of attributes */ private Set<Attribute> addMissingAttributes(final Set<Attribute> currentAttributes, final Set<String> namesOfMissingAttributes, final Employee employee) { /* * Get values of missing attributes: */ final ConnectorObjectBuilder builder = new ConnectorObjectBuilder(); builder.setUid (employee.getId()); //necessary for builder.build() builder.setName(employee.getLoginName());//necessary for builder.build() if (containsAny(namesOfMissingAttributes, ATTR_PRIMARY_POSITION, ATTR_SECONDARY_POSITIONS)) { POSITIONS.fillConnObjAttributes(employee, builder); } if (containsAny(namesOfMissingAttributes, ATTR_PRIMARY_ORGANIZATION, ATTR_SECONDARY_ORGANIZATIONS)) { ORGANIZATIONS.fillConnObjAttributes(employee, builder); } if (containsAny(namesOfMissingAttributes, ATTR_PRIMARY_RESPONSIBILITY, ATTR_SECONDARY_RESPONSIBILITIES)) { RESPONSIBILITIES.fillConnObjAttributes(employee, builder); } final ConnectorObject connObj = builder.build(); /* * Create the combined set of attributes: */ final Set<Attribute> result = new HashSet<>(currentAttributes); for (String attrName : namesOfMissingAttributes) { final Attribute attribute = connObj.getAttributeByName(attrName); if (attribute != null) { result.add(attribute); } } /* * TODO: * Find a solution for the case that the new primary responsibility * (organization, position) is among the current secondary responsibilities * (organizations, positions). */ return result; } /** * Determines attributes whose values are missing for a correct update * of the account. * The reason why some attributes may be missing is the difference between * two different representations of multi-value attributes in Siebel * and in the ConnId framework. * <p>For example, in Siebel, all the employee * positions are considered to be a single set of positions where each * position has a boolean attribute (primary/secondary). In the ConnId * framework, the same set of positions is represented by two separate * attributes - a single-valued attribute &quot;primary position&quot; * and a multi-valued attribute &quot;secondary positions&quot;. * If the user modifies the primary position attribute only, * the UpdateOp operation only receives a single attribute * containing the new value of attribute &quot;primary position&quot;, * but it must pass an updated set of <em>all positions</em> to Siebel. * In such a case, the list of secondary positions must be obtained * (read from Siebel) such that it can be appended to the (updated) primary * position.</p> * * @param presentAttributes attributes whose values are being updated * and whose values are currently known * @return attributes that must be added to the given attributes * to make the update operation correct and successful */ private Set<String> findMissingUpdateAttributes(final Collection<Attribute> presentAttributes) { final Set<String> result = new HashSet<>(); final PrimaryXorSecondary positions = new PrimaryXorSecondary(ATTR_PRIMARY_POSITION, ATTR_SECONDARY_POSITIONS); final PrimaryXorSecondary organizations = new PrimaryXorSecondary(ATTR_PRIMARY_ORGANIZATION, ATTR_SECONDARY_ORGANIZATIONS); final PrimaryXorSecondary responsibilities = new PrimaryXorSecondary(ATTR_PRIMARY_RESPONSIBILITY, ATTR_SECONDARY_RESPONSIBILITIES); for (Attribute attribute : presentAttributes) { final String attrName = attribute.getName(); switch (attrName) { case ATTR_PRIMARY_POSITION: case ATTR_SECONDARY_POSITIONS: positions.markPresent(attrName); break; case ATTR_PRIMARY_ORGANIZATION: case ATTR_SECONDARY_ORGANIZATIONS: organizations.markPresent(attrName); break; case ATTR_PRIMARY_RESPONSIBILITY: case ATTR_SECONDARY_RESPONSIBILITIES: responsibilities.markPresent(attrName); break; } } result.add(positions.getMissing()); //may be null result.add(organizations.getMissing()); //may be null result.add(responsibilities.getMissing()); //may be null result.remove(null); return result; } private void handleCreateOpSoapFault(final SOAPFaultException exception) { final SOAPFaultInfo faultInfo = soapFaultInspector.getSOAPErrorInfo(exception); final SOAPFaultInfo.Error error = faultInfo.getFirstError(); if (error != null) { handleInvalidValue(exception, error); if (ERR_SYMBOL_DUPLICITE_LOGIN_NAME.equals(error.symbol)) { throw new AlreadyExistsException( error.symbol + ": " + error.msg, exception); } } } private void handleUpdateOpSoapFault(final SOAPFaultException exception) { final SOAPFaultInfo faultInfo = soapFaultInspector.getSOAPErrorInfo(exception); final SOAPFaultInfo.Error error = faultInfo.getFirstError(); if (error != null) { handleInvalidValue(exception, error); if (ERR_CODE_DUPLICITE_LOGIN_NAME.equals(error.code)) { throw new AlreadyExistsException(error.msg, exception); } } } private void handleInvalidValue(final SOAPFaultException exception, final SOAPFaultInfo.Error error) { if (isCausedByInvalidValue(error)) { throw new InvalidAttributeValueException(error.msg, exception); } } private static boolean isCausedByInvalidValue(final SOAPFaultInfo.Error error) { if (error.code != null) { switch (error.code) { case ERR_CODE_SPACE_IN_LOGIN_NAME: case ERR_CODE_MISSING_LOGIN_NAME: case ERR_CODE_NOT_FROM_PICKLIST: case ERR_CODE_NOT_IN_BOUND_LIST: case ERR_CODE_NOT_FROM_LIST_OF_VALUES: case ERR_CODE_INVALID_POSITION: case ERR_CODE_INVALID_ORG_OR_RESP: return true; } return false; } if (error.symbol != null) { switch (error.symbol) { case ERR_SYMBOL_NOT_IN_BOUND_LIST: case ERR_SYMBOL_INVALID_POSITION: case ERR_SYMBOL_INVALID_ORG_OR_RESP: return true; } return false; } return false; } private SiebelEmployeeInsert1Input createInsertInput(final Set<Attribute> attributes) { final ListOfEmployeeInterface listOfEmployees = createListOfEmployee(attributes); final SiebelEmployeeInsert1Input input = new SiebelEmployeeInsert1Input(); input.setListOfEmployeeInterface(listOfEmployees); return input; } private SiebelEmployeeUpdate1Input createUpdateInput(final Uid uid, final Set<Attribute> attributes) { final ListOfEmployeeInterface listOfEmployees = createListOfEmployee(attributes, uid); final SiebelEmployeeUpdate1Input input = new SiebelEmployeeUpdate1Input(); input.setListOfEmployeeInterface(listOfEmployees); return input; } private ListOfEmployeeInterface createListOfEmployee(final Set<Attribute> attributes) { return createListOfEmployee(attributes, null); } private ListOfEmployeeInterface createListOfEmployee(final Set<Attribute> attributes, final Uid uid) { final com.siebel.xml.employee_20interface.Employee employee = createEmployee(attributes, uid); final ListOfEmployeeInterface listOfEmployeeInterface = new ListOfEmployeeInterface(); listOfEmployeeInterface.getEmployee().add(employee); return listOfEmployeeInterface; } private com.siebel.xml.employee_20interface.Employee createEmployee(final Set<Attribute> attributes, final Uid uid) { final com.siebel.xml.employee_20interface.Employee employee = new com.siebel.xml.employee_20interface.Employee(); final PrimarySecondaryEmployeeAttrValue positions = new PrimarySecondaryEmployeeAttrValue(); final PrimarySecondaryEmployeeAttrValue organizations = new PrimarySecondaryEmployeeAttrValue(); final PrimarySecondaryEmployeeAttrValue responsibilities = new PrimarySecondaryEmployeeAttrValue(); final Operation operation; if (uid == null) { operation = CREATE; } else { operation = UPDATE; employee.setId(uid.getUidValue()); } for (Attribute attribute : attributes) { final String attrName = attribute.getName(); if (isSpecialName(attrName)) { if (attrName.equals(Name.NAME)) { employee.setLoginName(getStringValue(attribute)); } else if (attrName.equals(OperationalAttributes.ENABLE_NAME)) { employee.setEmployeeStatus(employeeActiveAsString(getBooleanValue(attribute))); } else { LOG.warn("Unsupported attribute ({0}) will not be applied to a new account.", attrName); } } else { switch (attrName) { case ATTR_SECONDARY_POSITIONS: setSecondaryAttrValues(attribute, positions); break; case ATTR_SECONDARY_ORGANIZATIONS: setSecondaryAttrValues(attribute, organizations); break; case ATTR_SECONDARY_RESPONSIBILITIES: setSecondaryAttrValues(attribute, responsibilities); break; default: String stringValue = getStringValue(attribute); if (isEmptyString(stringValue)) { if (operation == CREATE) { continue; } else { stringValue = ""; // if it was null, change it to "" } } switch (attrName) { case ATTR_ALIAS: employee.setAlias(stringValue); break; case ATTR_EMPLOYEE_TYPE_CODE: employee.setEmployeeTypeCode(stringValue); break; case ATTR_PERSONAL_TITLE: employee.setPersonalTitle(stringValue); break; case ATTR_PREFERRED_COMMUNICATION: employee.setPreferredCommunications(stringValue); break; case ATTR_TIME_ZONE: employee.setTimeZoneName(stringValue); break; case ATTR_USER_TYPE: employee.setUserType(stringValue); break; case ATTR_CELL_PHONE: employee.setCellPhone(stringValue); break; case ATTR_EMAIL_ADDR: employee.setEMailAddr(stringValue); break; case ATTR_FAX: employee.setFax(stringValue); break; case ATTR_FIRST_NAME: employee.setFirstName(stringValue); break; case ATTR_JOB_TITLE: employee.setJobTitle(stringValue); break; case ATTR_LAST_NAME: employee.setLastName(stringValue); break; case ATTR_PHONE: employee.setPhone(stringValue); break; case ATTR_SALES_CHANNEL: employee.setSalesChannel(stringValue); break; case ATTR_PRIMARY_POSITION: positions .setPrimary(stringValue); break; case ATTR_PRIMARY_ORGANIZATION: organizations .setPrimary(stringValue); break; case ATTR_PRIMARY_RESPONSIBILITY: responsibilities.setPrimary(stringValue); break; default: LOG.warn("Unsupported attribute ({0}) will not be applied to a new account.", attrName); } } } } POSITIONS .fillEmployeeProperties(positions, employee); ORGANIZATIONS .fillEmployeeProperties(organizations, employee); RESPONSIBILITIES.fillEmployeeProperties(responsibilities, employee); return employee; } /** * Analyses the given web service exception and handles the common causes. * If the given exception is found to be caused by a common scenario * (unauthorized user, request timeout), then the exception is handled * by throwing an appropriate runtime exception. In other cases, * no exception is thrown and no data is changed. * * @param exception exception to be analyzed (and possibly handled) * @exception InvalidCredentialException * if the given exception was caused by invalid credentials * @exception OperationTimeoutException * if the given exception was caused by a timeout during * the network communication */ private static void handleWebServiceException(final WebServiceException exception) { final Throwable cause = exception.getCause(); if (cause instanceof HTTPException) { final HTTPException httpException = (HTTPException) cause; final int responseCode = httpException.getResponseCode(); switch (responseCode) { case HTTP_STATUS_UNAUTHORIZED: throw new InvalidCredentialException(httpException.getMessage()); case HTTP_STATUS_REQUEST_TIMEOUT: throw new OperationTimeoutException(httpException.getMessage()); } } else if (cause instanceof SocketTimeoutException) { throw new OperationTimeoutException(cause.getMessage()); } } private static void setSecondaryAttrValues(final Attribute attribute, final PrimarySecondaryEmployeeAttrValue attrValue) { final List<Object> values = attribute.getValue(); if (!isEmpty(values)) { for (Object value : values) { final String trimmed = trimToNull(value); if (trimmed != null) { attrValue.addSecondary(trimmed); } } } } private static boolean isEmptyString(final String str) { return (str == null) || str.isEmpty(); } private static String trimToNull(final Object obj) { if (obj == null) { return null; } final String string = obj.toString(); if (string == null) { return null; } final String trimmed = string.trim(); if (trimmed.isEmpty()) { return null; } return trimmed; } /** * Helper class that gets/sets values of the following attributes: * <ul> * <li>primary position and secondary positions</li> * <li>primary organization and secondary organizations</li> * <li>primary responsibility and secondary responsibilities</li> * </ul> * The aim of this class is elimination of repetition of code * (now in methods {@link #fillConnObjAttributesImpl fillAttributesImpl(&hellip;)} * and {@link #fillEmployeeProperties fillEmployeeProperties(&hellip;)}). * * @param <P> type of attribute in the source object (<code>Employee</code>) * when employees are being read from Siebel * ({@code EmployeePosition}, {@code EmployeeOrganization}, * {@code EmployeeResponsibility}) * @param <Q> type of attribute in the target object (<code>Employee</code>) * when employees are being written to Siebel * ({@code RelatedPosition}, {@code RelatedEmployeeOrganization}, * {@code RelatedResponsibility}) */ private static final class PrimarySecondaryEmployeeAttribute<P, Q> { /* --------- reading from Siebel --------- */ private static final String CLASSNAME_PREFIX_READING = "Employee"; private final Method methodGetListOfEmployee; private final Method methodGetList; private final Method methodGetProp; private final Method methodIsPrimary; private final String connObjAttrPrimary; private final String connObjAttrSecondary; /* --------- writing to Siebel --------- */ private static final String CLASSNAME_PREFIX_WRITING = "Related"; private final Class<Q> clsWriteProperty; private final Class<?> clsWritePropertiesList; private final Method methodGetRelatedList; private final Method methodSetRelatedListObj; private final Method methodSetRelatedAttr; private final Method methodSetRelatedAttrPrimOrSec; private PrimarySecondaryEmployeeAttribute(final Class<P> readPropertyClass, final Class<Q> writePropertyClass, final String connObjAttrPrimary, final String connObjAttrSecondary) throws NoSuchMethodException, ClassNotFoundException { this(readPropertyClass, writePropertyClass, connObjAttrPrimary, connObjAttrSecondary, null); } private PrimarySecondaryEmployeeAttribute(final Class<P> readPropertyClass, final Class<Q> writePropertyClass, final String connObjAttrPrimary, final String connObjAttrSecondary, final String resourceAttrNameOverride) throws NoSuchMethodException, ClassNotFoundException { /* --------- reading from Siebel --------- */ { final String propertyClassName = readPropertyClass.getSimpleName(); //"EmployeePosition", "EmployeeOrganization", "EmployeeResponsibility" final String getListOfEmployeeMethodName = "getListOf" + propertyClassName; //"getListOfEmployeePosition", ... final String getListMethodName = "get" + propertyClassName; //"getEmployeePosition", ... assert propertyClassName.startsWith(CLASSNAME_PREFIX_READING); final String resourceAttrName = (resourceAttrNameOverride == null) ? propertyClassName.substring(CLASSNAME_PREFIX_READING.length()) //"Position", "Organization", "Responsibility" : resourceAttrNameOverride; final String getPropMethodName = "get" + resourceAttrName; //"getPosition", "getOrganization", "getResponsibility" final String isPrimaryMethodName = "getIsPrimaryMVG"; methodGetListOfEmployee = Employee.class.getDeclaredMethod(getListOfEmployeeMethodName); // Employee.getListOfEmployeePosition() : ListOfEmployeePosition methodGetList = methodGetListOfEmployee.getReturnType().getDeclaredMethod(getListMethodName); // ListOfEmployeePosition.getEmployeePosition() : List<EmployeePosition> methodGetProp = readPropertyClass.getDeclaredMethod(getPropMethodName); // EmployeePosition.getPosition() : String methodIsPrimary = readPropertyClass.getDeclaredMethod(isPrimaryMethodName); // EmployeePosition.getIsPrimaryMVG() : String this.connObjAttrPrimary = connObjAttrPrimary; this.connObjAttrSecondary = connObjAttrSecondary; } /* --------- writing to Siebel --------- */ { final String propertyClassName = writePropertyClass.getSimpleName(); //"RelatedPosition", "RelatedEmployeeOrganization", "RelatedResponsibility" final String getListMethodName = "get" + propertyClassName; //"getRelatedPosition", ... final String setListObjMethodName = "setListOf" + propertyClassName; //"setListOfRelatedPosition", ... assert propertyClassName.startsWith(CLASSNAME_PREFIX_WRITING); final String resourceAttrName = (resourceAttrNameOverride == null) ? propertyClassName.substring(CLASSNAME_PREFIX_WRITING.length()) //"Position", "EmployeeOrganization", "Responsibility" : resourceAttrNameOverride; final String setPropMethodName = "set" + resourceAttrName; //"setPosition", "setEmployeeOrganization", "setResponsibility" final String setIsPrimaryMethodName = "setIsPrimaryMVG"; clsWriteProperty = writePropertyClass; // RelatedPosition, ... clsWritePropertiesList = deriveWritePropertiesListClass(clsWriteProperty); // ListOfRelatedPosition, ... methodGetRelatedList = clsWritePropertiesList.getDeclaredMethod(getListMethodName); // ListOfRelatedPosition.getRelatedPosition() methodSetRelatedListObj = com.siebel.xml.employee_20interface.Employee.class .getDeclaredMethod(setListObjMethodName, clsWritePropertiesList); // Employee.setListOfRelatedPosition(...) methodSetRelatedAttr = writePropertyClass.getDeclaredMethod(setPropMethodName, String.class); //RelatedPosition.setPosition(String) methodSetRelatedAttrPrimOrSec = writePropertyClass.getDeclaredMethod(setIsPrimaryMethodName, String.class); //RelatedPosition.setIsPrimaryMVG(...) } } /** * Finds (and loads) a class that represents a list of the given * properties. For example, given class {@code RelatedResponsibility}, * this method returns class {@code ListOfRelatedResponsibility}. * * @param writePropertyClass type of properties that the returned class should be a list of * @return class reprenting a list of the given type of properties * @throws ClassNotFoundException if the class could not be loaded */ private static Class<?> deriveWritePropertiesListClass(final Class<?> writePropertyClass) throws ClassNotFoundException { final String packageName = writePropertyClass.getPackage().getName(); final String simpleName = writePropertyClass.getSimpleName(); final Class<?> result = Class.forName(packageName + ".ListOf" + simpleName, false, writePropertyClass.getClassLoader()); return result; } void fillConnObjAttributes(final Employee employee, final ConnectorObjectBuilder objBuilder) { try { fillConnObjAttributesImpl(employee, objBuilder); } catch (ReflectiveOperationException ex) { throw new RuntimeException(ex); } } private void fillConnObjAttributesImpl(final Employee employee, final ConnectorObjectBuilder objBuilder) throws ReflectiveOperationException { final Object listOfEmployeeProps = methodGetListOfEmployee.invoke(employee); // Employee.getListOfEmployeePosition() : ListOfEmployeePosition if (listOfEmployeeProps != null) { final List<P> employeeProps = (List<P>) methodGetList.invoke(listOfEmployeeProps); // ListOfEmployeePosition.getEmployeePosition() : List<EmployeePosition> if (!isEmpty(employeeProps)) { final Collection<String> secondaryProps = new ArrayList<>(); for (P empProp : employeeProps) { final String prop = (String) methodGetProp.invoke(empProp); // String position = EmployeePosition.getPosition(); if (isYes((String) methodIsPrimary.invoke(empProp))) { // if (isYes(employeePosition.getIsPrimaryMVG())) ... objBuilder.addAttribute(connObjAttrPrimary, prop); } else { secondaryProps.add(prop); } } objBuilder.addAttribute(connObjAttrSecondary, secondaryProps); } } } void fillEmployeeProperties(final PrimarySecondaryEmployeeAttrValue primarySecondary, final com.siebel.xml.employee_20interface.Employee employee) { if (PrimarySecondaryEmployeeAttrValue.isEmpty(primarySecondary)) { return; } try { fillEmployeePropertiesImpl(primarySecondary, employee); } catch (ReflectiveOperationException ex) { throw new RuntimeException(ex); } } private void fillEmployeePropertiesImpl(final PrimarySecondaryEmployeeAttrValue primarySecondary, final com.siebel.xml.employee_20interface.Employee employee) throws ReflectiveOperationException { if (PrimarySecondaryEmployeeAttrValue.isEmpty(primarySecondary)) { return; } final Object listObj = clsWritePropertiesList.newInstance(); // ListOfRelatedPosition listObj = new ListOfRelatedPosition(); final List<Q> list = (List<Q>) methodGetRelatedList.invoke(listObj); // List<RelatedPosition> list = listObj.getRelatedPosition(); final String primary = primarySecondary.getPrimary(); if (isNotEmpty(primary)) { list.add(createRelatedItem(primary, true)); // list.add(createPosition(primary, true)); } for (String secondary : primarySecondary.getSecondary()) { list.add(createRelatedItem(secondary, false)); // list.add(createPosition(secondary, false)); } methodSetRelatedListObj.invoke(employee, listObj); // employee.setListOfRelatedPosition(listObj); } private Q createRelatedItem(final String connObjAttrValue, // RelatedPosition createPosition(...) final boolean isPrimary) throws ReflectiveOperationException { final Q relatedItem = clsWriteProperty.newInstance(); // RelatedPosition position = new RelatedPosition(); methodSetRelatedAttr.invoke(relatedItem, connObjAttrValue); // position.setPosition(value); methodSetRelatedAttrPrimOrSec.invoke(relatedItem, booleanAsString(isPrimary)); // position.setIsPrimaryMVG(booleanAsString(primary)); return relatedItem; // return position; } private static boolean isYes(final String str) { return RESOURCE_PROP_VALUE_YES.equals(str); } private static String booleanAsString(final boolean value) { return value ? RESOURCE_PROP_VALUE_YES : RESOURCE_PROP_VALUE_NO; } } /** * Represents a complex type of an employee property that consits * of a primary value and a list of secondary values. * It is used for properties <em>positions</em> (where there is a primary * position and a list of secondary positions), <em>responsibilities</em> * (a primary responsibility and a list of secondary responsibilities) * and <em>employee organization</em> (a primary organization and a list of * secondary organizations). */ private static final class PrimarySecondaryEmployeeAttrValue { private static final List<String> EMPTY_LIST = emptyList(); private String primary; private List<String> secondaryList = EMPTY_LIST; void setPrimary(final String primary) { this.primary = primary; } void addSecondary(final String secondary) { if (secondaryList == EMPTY_LIST) { secondaryList = new ArrayList<>(); } secondaryList.add(secondary); } String getPrimary() { return primary; } List<String> getSecondary() { return secondaryList; } boolean isEmpty() { return (primary == null) && (secondaryList == EMPTY_LIST); } static boolean isEmpty(final PrimarySecondaryEmployeeAttrValue primarySecondary) { return (primarySecondary == null) || primarySecondary.isEmpty(); } } /** * Finds whether the given set contains any of the two given elements. * * @param <T> type of the elements * @param set set to be checked for presents of the given elements * @param one one of the two elements * @param two the other of the two elements * @return {@code true} if the given set does contain any of the elements, * {@code false} otherwise */ private static <T> boolean containsAny(final Set<T> set, final T one, final T two) { return set.contains(one) || set.contains(two); } }
src/main/java/com/evolveum/polygon/connector/siebel/SiebelConnector.java
package com.evolveum.polygon.connector.siebel; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.SocketTimeoutException; import java.net.URL; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.EnumMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.ws.WebServiceException; import javax.xml.ws.soap.SOAPFaultException; import javax.xml.xpath.XPathExpressionException; import org.apache.cxf.endpoint.Client; import org.apache.cxf.feature.LoggingFeature; import org.apache.cxf.frontend.ClientProxy; import org.apache.cxf.frontend.ClientProxyFactoryBean; import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; import org.apache.cxf.transport.http.HTTPConduit; import org.apache.cxf.transport.http.HTTPException; import org.apache.cxf.transports.http.configuration.HTTPClientPolicy; import org.identityconnectors.common.logging.Log; import org.identityconnectors.framework.common.exceptions.AlreadyExistsException; import org.identityconnectors.framework.common.exceptions.InvalidAttributeValueException; import org.identityconnectors.framework.common.exceptions.InvalidCredentialException; import org.identityconnectors.framework.common.exceptions.OperationTimeoutException; import org.identityconnectors.framework.common.exceptions.UnknownUidException; import org.identityconnectors.framework.common.objects.Attribute; import org.identityconnectors.framework.common.objects.AttributeInfo; import org.identityconnectors.framework.common.objects.AttributeInfoBuilder; import org.identityconnectors.framework.common.objects.ConnectorObject; import org.identityconnectors.framework.common.objects.ConnectorObjectBuilder; import org.identityconnectors.framework.common.objects.Name; import org.identityconnectors.framework.common.objects.ObjectClass; import org.identityconnectors.framework.common.objects.ObjectClassInfo; import org.identityconnectors.framework.common.objects.ObjectClassInfoBuilder; import org.identityconnectors.framework.common.objects.OperationOptions; import org.identityconnectors.framework.common.objects.OperationalAttributeInfos; import org.identityconnectors.framework.common.objects.OperationalAttributes; import org.identityconnectors.framework.common.objects.ResultsHandler; import org.identityconnectors.framework.common.objects.Schema; import org.identityconnectors.framework.common.objects.SchemaBuilder; import org.identityconnectors.framework.common.objects.SearchResult; import org.identityconnectors.framework.common.objects.Uid; import org.identityconnectors.framework.spi.Configuration; import org.identityconnectors.framework.spi.ConnectorClass; import org.identityconnectors.framework.spi.PoolableConnector; import org.identityconnectors.framework.spi.SearchResultsHandler; import org.identityconnectors.framework.spi.operations.CreateOp; import org.identityconnectors.framework.spi.operations.SchemaOp; import org.identityconnectors.framework.spi.operations.SearchOp; import org.identityconnectors.framework.spi.operations.TestOp; import org.identityconnectors.framework.spi.operations.UpdateOp; import com.evolveum.polygon.connector.siebel.util.Pair; import com.evolveum.polygon.connector.siebel.util.PrimaryXorSecondary; import com.evolveum.polygon.connector.siebel.util.SearchResultLogger; import com.siebel.asi.SWIEmployeeServicesQueryPageInput; import com.siebel.asi.SWIEmployeeServicesQueryPageOutput; import com.siebel.asi.SWISpcEmployeeSpcService; import com.siebel.customui.SiebelEmployeeInsert1Input; import com.siebel.customui.SiebelEmployeeInsert1Output; import com.siebel.customui.SiebelEmployeeUpdate1Input; import com.siebel.customui.SiebelEmployeeUpdate1Output; import com.siebel.customui.SiebelSpcEmployee; import com.siebel.xml.employee_20interface.ListOfEmployeeInterface; import com.siebel.xml.employee_20interface.RelatedEmployeeOrganization; import com.siebel.xml.employee_20interface.RelatedPosition; import com.siebel.xml.employee_20interface.RelatedResponsibility; import com.siebel.xml.swiemployeeio.Employee; import com.siebel.xml.swiemployeeio.EmployeeOrganization; import com.siebel.xml.swiemployeeio.EmployeePosition; import com.siebel.xml.swiemployeeio.EmployeeResponsibility; import com.siebel.xml.swiemployeeio.ListOfSwiemployeeio; import static com.evolveum.polygon.connector.siebel.LogUtils.getAttributeNames; import static com.evolveum.polygon.connector.siebel.Operation.CREATE; import static com.evolveum.polygon.connector.siebel.Operation.UPDATE; import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; import static java.lang.Math.min; import static java.util.Collections.emptyList; import static java.util.EnumSet.of; import static org.identityconnectors.common.CollectionUtil.isEmpty; import static org.identityconnectors.common.StringUtil.isNotEmpty; import static org.identityconnectors.framework.common.objects.AttributeInfo.Flags.MULTIVALUED; import static org.identityconnectors.framework.common.objects.AttributeInfo.Flags.NOT_CREATABLE; import static org.identityconnectors.framework.common.objects.AttributeInfo.Flags.NOT_UPDATEABLE; import static org.identityconnectors.framework.common.objects.AttributeInfo.Flags.REQUIRED; import static org.identityconnectors.framework.common.objects.AttributeUtil.getBooleanValue; import static org.identityconnectors.framework.common.objects.AttributeUtil.getStringValue; import static org.identityconnectors.framework.common.objects.AttributeUtil.isSpecialName; @ConnectorClass(displayNameKey = "siebel.connector.display", configurationClass = SiebelConfiguration.class) public class SiebelConnector implements PoolableConnector, TestOp, SchemaOp, SearchOp<Filter>, CreateOp, UpdateOp { private static final Log LOG = Log.getLog(SiebelConnector.class); private static final int HTTP_STATUS_UNAUTHORIZED = 401; private static final int HTTP_STATUS_REQUEST_TIMEOUT = 408; private static final String EMPLOYEE_ACTIVE = "Active"; private static final String EMPLOYEE_INACTIVE = "Inactive"; private static final String RESOURCE_PROP_VALUE_YES = "Y"; private static final String RESOURCE_PROP_VALUE_NO = "N"; private static final String REQUEST_LOG_FILENAME = "siebel-soap-request.xml"; private static final String RESPONSE_LOG_FILENAME = "siebel-soap-response.xml"; /** * account Id used when testing the connection * * @see #test() test() */ private static final String TEST_ID = "BFLM_DUMMY_HCHKR"; /** * offset passed to the {@code SearchOp} when the first page is requested */ static final int CONNID_SPI_FIRST_PAGE_OFFSET = 1; /** * number of the first row in Siebel */ private static final int SIEBEL_WS_FIRST_ROW_NUMBER = 0; /** * number of the first row in Siebel - as a string */ private static final String SIEBEL_WS_FIRST_ROW_NUMBER_STR = Integer.toString(SIEBEL_WS_FIRST_ROW_NUMBER); /** * constant to be added to the ConnId paged results offset to calculate * the value of the corresponding web service's parameter <i>StartRowNum</i> */ private static final int CONNID_TO_WS_REC_NO_SHIFT = SIEBEL_WS_FIRST_ROW_NUMBER - CONNID_SPI_FIRST_PAGE_OFFSET; private static final Set<AttributeInfo.Flags> F_REQUIRED = of(REQUIRED); private static final Set<AttributeInfo.Flags> F_MULTIVALUED = of(MULTIVALUED); private static final Set<AttributeInfo.Flags> F_MULTIVALUED_READONLY = of(MULTIVALUED, NOT_UPDATEABLE); private static final SearchResult ALL_RESULTS_RETURNED = new SearchResult(); /** * error symbol of a SOAP fault caused by an attempt to create a duplicite * account */ private static final String ERR_SYMBOL_DUPLICITE_LOGIN_NAME = "IDS_ERR_EAI_SA_INSERT_MATCH_FOUND"; private static final String ERR_CODE_SPACE_IN_LOGIN_NAME = "SBL-APS-00195"; /** * error code of a SOAP fault caused by an attempt to change login name * to a login name that is assigned to another account */ private static final String ERR_CODE_DUPLICITE_LOGIN_NAME = "SBL-DAT-00381"; private static final String ERR_CODE_MISSING_LOGIN_NAME = "SBL-DAT-00498"; private static final String ERR_CODE_NOT_FROM_PICKLIST = "SBL-DAT-00225"; private static final String ERR_CODE_NOT_IN_BOUND_LIST = "SBL-EAI-04401"; private static final String ERR_SYMBOL_NOT_IN_BOUND_LIST = "IDS_ERR_EAI_SA_PICK_VALIDATE"; private static final String ERR_CODE_NOT_FROM_LIST_OF_VALUES = "SBL-DAT-00510"; /** * error code of a SOAP fault caused by an invalid value of attribute * &quot;employee position&quot; * * @see #ERR_SYMBOL_INVALID_POSITION */ private static final String ERR_CODE_INVALID_POSITION = "SBL-EAI-04397"; /** * error code of a SOAP fault caused by an invalid value of attribute * &quot;employee organization&quot; or &quot;employee responsibility&quot; * * @see #ERR_SYMBOL_INVALID_ORG_OR_RESP */ private static final String ERR_CODE_INVALID_ORG_OR_RESP = "SBL-EAI-04184"; /** * error symbol of a SOAP fault caused by an invalid value of attribute * &quot;employee position&quot; * * @see #ERR_CODE_INVALID_POSITION */ private static final String ERR_SYMBOL_INVALID_POSITION = "IDS_ERR_EAI_SA_NO_USERKEY"; /** * error symbol of a SOAP fault caused by an invalid value of attribute * &quot;employee organization&quot; or &quot;employee responsibility&quot; * * @see #ERR_CODE_INVALID_ORG_OR_RESP */ private static final String ERR_SYMBOL_INVALID_ORG_OR_RESP = "IDS_EAI_ERR_SA_INT_NOINSERT"; static final String ATTR_ID = "Id"; static final String ATTR_LOGIN_NAME = "LoginName"; static final String ATTR_ALIAS = "Alias"; static final String ATTR_EMPLOYEE_TYPE_CODE = "EmployeeTypeCode"; static final String ATTR_PERSONAL_TITLE = "PersonalTitle"; static final String ATTR_PREFERRED_COMMUNICATION = "PreferredCommunication"; static final String ATTR_TIME_ZONE = "TimeZoneName"; static final String ATTR_USER_TYPE = "UserType"; static final String ATTR_CELL_PHONE = "CellPhone"; static final String ATTR_EMAIL_ADDR = "EMailAddr"; static final String ATTR_FAX = "Fax"; static final String ATTR_FIRST_NAME = "FirstName"; static final String ATTR_JOB_TITLE = "JobTitle"; static final String ATTR_LAST_NAME = "LastName"; static final String ATTR_PHONE = "Phone"; static final String ATTR_SALES_CHANNEL = "SalesChannel"; static final String ATTR_PRIMARY_POSITION = "PrimaryPosition"; static final String ATTR_SECONDARY_POSITIONS = "SecondaryPositions"; static final String ATTR_PRIMARY_ORGANIZATION = "EmployeePrimaryOrganization"; static final String ATTR_SECONDARY_ORGANIZATIONS = "EmployeeSecondaryOrganizations"; static final String ATTR_PRIMARY_RESPONSIBILITY = "PrimaryResponsibility"; static final String ATTR_SECONDARY_RESPONSIBILITIES = "SecondaryResponsibilities"; private static final PrimarySecondaryEmployeeAttribute<EmployeePosition, RelatedPosition> POSITIONS; private static final PrimarySecondaryEmployeeAttribute<EmployeeOrganization, RelatedEmployeeOrganization> ORGANIZATIONS; private static final PrimarySecondaryEmployeeAttribute<EmployeeResponsibility, RelatedResponsibility> RESPONSIBILITIES; static { try { POSITIONS = new PrimarySecondaryEmployeeAttribute<>(EmployeePosition.class, RelatedPosition.class, ATTR_PRIMARY_POSITION, ATTR_SECONDARY_POSITIONS, "PositionId"); ORGANIZATIONS = new PrimarySecondaryEmployeeAttribute<>(EmployeeOrganization.class, RelatedEmployeeOrganization.class, ATTR_PRIMARY_ORGANIZATION, ATTR_SECONDARY_ORGANIZATIONS); RESPONSIBILITIES = new PrimarySecondaryEmployeeAttribute<>(EmployeeResponsibility.class, RelatedResponsibility.class, ATTR_PRIMARY_RESPONSIBILITY, ATTR_SECONDARY_RESPONSIBILITIES); } catch (ReflectiveOperationException ex) { throw new RuntimeException(ex); } } private SiebelConfiguration configuration; private SWISpcEmployeeSpcService queryService; private SiebelSpcEmployee insertUpdateService; private int maxResourcePageSize; private String maxResourcePageSizeStr; /** * contains query input prototypes for each of the search modes * (by Id, by login name, get all) */ private final Map<Filter.Mode, Pair<SWIEmployeeServicesQueryPageInput, Employee>> queryInputPrototypes = new EnumMap<>(Filter.Mode.class); private SoapFaultInspector soapFaultInspector; @Override public Configuration getConfiguration() { return configuration; } @Override public void init(final Configuration configuration) { LOG.info("Initializing connector (connecting to the WS)..."); this.configuration = (SiebelConfiguration) configuration; queryService = createService(SWISpcEmployeeSpcService.class); insertUpdateService = createService(SiebelSpcEmployee.class); setMaxResourcePageSize(this.configuration.getMaxPageSize()); setupQueryInputPrototypes(); try { soapFaultInspector = new SoapFaultInspector(); } catch (XPathExpressionException ex) { throw new RuntimeException(ex); } } private void setMaxResourcePageSize(final int maxResourcePageSize) { this.maxResourcePageSize = maxResourcePageSize; this.maxResourcePageSizeStr = Integer.toString(maxResourcePageSize); } private void setupQueryInputPrototypes() { Pair<SWIEmployeeServicesQueryPageInput, Employee> queryInputPrototype; queryInputPrototype = createQueryInputPrototype(); queryInputPrototypes.put(Filter.Mode.RETURN_ALL, queryInputPrototype); queryInputPrototype = createQueryInputPrototype(); queryInputPrototypes.put(Filter.Mode.SEARCH_BY_ID, queryInputPrototype); queryInputPrototype = createQueryInputPrototype(); queryInputPrototypes.put(Filter.Mode.SEARCH_BY_LOGIN_NAME, queryInputPrototype); } private Pair<SWIEmployeeServicesQueryPageInput, Employee> createQueryInputPrototype() { final SWIEmployeeServicesQueryPageInput queryInput = new SWIEmployeeServicesQueryPageInput(); final Employee employee = new Employee(); final ListOfSwiemployeeio listOfSwiemployeeio = new ListOfSwiemployeeio(); listOfSwiemployeeio.getEmployee().add(employee); queryInput.setListOfSwiemployeeio(listOfSwiemployeeio); return new Pair<>(queryInput, employee); } private <S> S createService(final Class<S> seiClass) { final ClientProxyFactoryBean factory = new JaxWsProxyFactoryBean(); // a new instance must be used for each service final Path soapLogTargetPath = configuration.getSoapLogTargetPath(); if (soapLogTargetPath != null) { try { final Path targetForRequests = soapLogTargetPath.resolve(REQUEST_LOG_FILENAME); final Path targetForResponses = soapLogTargetPath.resolve(RESPONSE_LOG_FILENAME); final URL targetPathURLForRequests = targetForRequests .toUri().toURL(); final URL targetPathURLForResponses = targetForResponses.toUri().toURL(); factory.getFeatures().add(new LoggingFeature(targetPathURLForResponses.toString(), targetPathURLForRequests.toString(), 100_000, true)); } catch (MalformedURLException ex) { LOG.warn(ex, "Couldn't initialize logging of SOAP messages."); } } factory.setAddress (configuration.getWsUrl()); factory.setUsername(configuration.getUsername()); factory.setPassword(configuration.getPassword()); factory.setServiceClass(seiClass); final S result = (S) factory.create(); /* disable chunking: */ final Client client = ClientProxy.getClient(result); final HTTPConduit http = (HTTPConduit) client.getConduit(); final HTTPClientPolicy httpClientPolicy; { httpClientPolicy = new HTTPClientPolicy(); httpClientPolicy.setAllowChunking(false); httpClientPolicy.setConnectionTimeout(configuration.getConnectTimeout()); httpClientPolicy.setReceiveTimeout(configuration.getReceiveTimeout()); } http.setClient(httpClientPolicy); return result; } /** * Used by unit tests. * * @param queryService test query service to be used by this connector */ void init(final SWISpcEmployeeSpcService queryService) { init(queryService, SiebelConfiguration.DEFAULT_MAX_PAGE_SIZE); } /** * Used by unit tests. * * @param queryService test query service to be used by this connector */ void init(final SWISpcEmployeeSpcService queryService, final int maxResourcePageSize) { this.queryService = queryService; setMaxResourcePageSize(maxResourcePageSize); setupQueryInputPrototypes(); } /** * Used by unit tests. * * @param queryService test update service to be used by this connector */ void init(final SiebelSpcEmployee insertUpdateService) { this.insertUpdateService = insertUpdateService; setupQueryInputPrototypes(); } @Override public void dispose() { LOG.info("Disposing connector..."); closeWsClient(insertUpdateService); insertUpdateService = null; closeWsClient(queryService); queryService = null; maxResourcePageSizeStr = null; maxResourcePageSize = -1; queryInputPrototypes.clear(); configuration = null; soapFaultInspector = null; } private static void closeWsClient(final Object service) { if (service != null) { final Client client = ClientProxy.getClient(service); if (client != null) { client.destroy(); } } } @Override public void checkAlive() { } @Override public void test() { LOG.ok("test() ..."); executeQueryById(TEST_ID); LOG.ok("test() finished successfully"); } @Override public Schema schema() { LOG.ok("schema()"); final SchemaBuilder schemaBuilder = new SchemaBuilder(SiebelConnector.class); schemaBuilder.defineObjectClass(getEmployeeInfo()); return schemaBuilder.build(); } private static ObjectClassInfo getEmployeeInfo() { final ObjectClassInfoBuilder builder = new ObjectClassInfoBuilder(); builder.addAttributeInfo(new AttributeInfoBuilder(Uid.NAME) .setFlags(of(NOT_CREATABLE, NOT_UPDATEABLE)) .setNativeName(ATTR_ID) .build()); builder.addAttributeInfo(new AttributeInfoBuilder(Name.NAME) .setFlags(of(REQUIRED)) .setNativeName(ATTR_LOGIN_NAME) .build()); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_ALIAS, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_EMPLOYEE_TYPE_CODE, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_PERSONAL_TITLE, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_PREFERRED_COMMUNICATION, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_TIME_ZONE, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_USER_TYPE, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_CELL_PHONE, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_EMAIL_ADDR, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_FAX, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_FIRST_NAME, String.class, F_REQUIRED)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_JOB_TITLE, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_LAST_NAME, String.class, F_REQUIRED)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_PHONE, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_SALES_CHANNEL, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_PRIMARY_POSITION, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_SECONDARY_POSITIONS, String.class, F_MULTIVALUED_READONLY)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_PRIMARY_ORGANIZATION, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_SECONDARY_ORGANIZATIONS, String.class, F_MULTIVALUED)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_PRIMARY_RESPONSIBILITY, String.class)); builder.addAttributeInfo(AttributeInfoBuilder.build(ATTR_SECONDARY_RESPONSIBILITIES, String.class, F_MULTIVALUED)); builder.addAttributeInfo(OperationalAttributeInfos.ENABLE); return builder.build(); } @Override public org.identityconnectors.framework.common.objects.filter.FilterTranslator<Filter> createFilterTranslator(final ObjectClass objectClass, final OperationOptions options) { return new FilterTranslator(); } @Override public void executeQuery(final ObjectClass objectClass, final Filter query, final ResultsHandler handler, final OperationOptions options) { if (!objectClass.equals(ObjectClass.ACCOUNT)) { return; } LOG.ok("executeQuery(query={0}, options={1})", query, options); final SWIEmployeeServicesQueryPageInput queryInput = setupQueryInput(query); findMatchingObjects(queryInput, handler, options); } private void findMatchingObjects(final SWIEmployeeServicesQueryPageInput queryInput, final ResultsHandler resultsHandler, final OperationOptions options) { SWIEmployeeServicesQueryPageOutput queryResponse; List<Employee> employees; Boolean moreResultsAvailable = TRUE; final Integer requestedPageSize = normalizePagedOption(options.getPageSize()); final Integer requestedOffset = (requestedPageSize != null) ? normalizePagedOption(options.getPagedResultsOffset()) : null; int resourceOffset = (requestedOffset != null) ? requestedOffset + CONNID_TO_WS_REC_NO_SHIFT : 0; final SearchResultLogger employeeLogger = new SearchResultLogger(LOG); if (requestedPageSize == null) { queryInput.setPageSize(maxResourcePageSizeStr); main: do { int employeesCount; queryInput.setStartRowNum(Integer.toString(resourceOffset)); LOG.ok(" - WS input: start row = {0}, page size = {1}", queryInput.getStartRowNum(), queryInput.getPageSize()); queryResponse = executeQuery(queryInput); employees = queryResponse.getListOfSwiemployeeio().getEmployee(); employeesCount = employees.size(); LOG.ok(" - WS output: count = {0}, last page = {1}", employeesCount, queryResponse.getLastPage()); int handledCount = 0; for (Employee employee : employees) { boolean cont = resultsHandler.handle(createAccount(employee)); if (!cont) { LOG.ok(" - the connector only accepted {0} object(s)", handledCount); break main; } handledCount++; employeeLogger.logEmployee(employee); } moreResultsAvailable = isMoreResultsAvailable(queryResponse); resourceOffset += employeesCount; } while (moreResultsAvailable == TRUE); } else { int requestedRecordsRemaining = requestedPageSize; main: do { int resourcePageSize = min(requestedRecordsRemaining, maxResourcePageSize); int employeesCount; queryInput.setStartRowNum(Integer.toString(resourceOffset)); queryInput.setPageSize(Integer.toString(resourcePageSize)); LOG.ok(" - WS input: start row = {0}, page size = {1}", queryInput.getStartRowNum(), queryInput.getPageSize()); queryResponse = executeQuery(queryInput); employees = queryResponse.getListOfSwiemployeeio().getEmployee(); employeesCount = employees.size(); LOG.ok(" - WS output: count = {0}, last page = {1}", employeesCount, queryResponse.getLastPage()); int handledCount = 0; for (Employee employee : employees) { boolean cont = resultsHandler.handle(createAccount(employee)); if (!cont) { LOG.ok(" - the connector only accepted {0} object(s)", handledCount); break main; } handledCount++; employeeLogger.logEmployee(employee); } moreResultsAvailable = isMoreResultsAvailable(queryResponse); if (moreResultsAvailable != TRUE) { break; } resourceOffset += employeesCount; requestedRecordsRemaining -= employeesCount; } while (requestedRecordsRemaining > 0); } employeeLogger.writeResultToLog(); if (moreResultsAvailable == null) { //should be TRUE or FALSE recordInvalidValueOfLastPage(queryResponse); } if (resultsHandler instanceof SearchResultsHandler) { final SearchResultsHandler handler = (SearchResultsHandler) resultsHandler; final SearchResult searchResult = (moreResultsAvailable == TRUE) ? new SearchResult(null, -1, false) : ALL_RESULTS_RETURNED; handler.handleResult(searchResult); } else { LOG.warn("The ResultsHandler doesn't implement interface SearchResultsHandler: {0}", resultsHandler.getClass().getName()); } } private Employee findEmployeeById(final Uid uid) { return findEmployeeById(uid.getUidValue()); } private Employee findEmployeeById(final String id) { final Employee result; final SWIEmployeeServicesQueryPageOutput queryOutput = executeQueryById(id); final List<Employee> employees = queryOutput.getListOfSwiemployeeio().getEmployee(); if (isEmpty(employees)) { result = null; } else if (employees.size() == 1) { result = employees.get(0); } else { LOG.error("There were multiple accounts ({1}) found when searching by Id ({0}).", id, employees.size()); throw new IllegalStateException("Multiple accounts found by Id."); } return result; } private SWIEmployeeServicesQueryPageOutput executeQueryById(final String id) { final SWIEmployeeServicesQueryPageInput testQueryInput; testQueryInput = setupQueryInput(Filter.byId(id)); testQueryInput.setStartRowNum(SIEBEL_WS_FIRST_ROW_NUMBER_STR); testQueryInput.setPageSize("1"); return executeQuery(testQueryInput); } private SWIEmployeeServicesQueryPageOutput executeQuery(final SWIEmployeeServicesQueryPageInput queryInput) { try { return queryService.swiEmployeeServicesQueryPage(queryInput); } catch (WebServiceException ex) { handleWebServiceException(ex); throw ex; } } /** * Determines whether there are (possibly) more matching results available * according to the given response from Siebel. * * @param queryResponse response from the Siebel web service * @return {@code Boolean.TRUE} if more results are (possibly) available, * {@code Boolean.FALSE} if there are no more results available, * {@code null} if the response from Siebel contained an invalid * value */ private static Boolean isMoreResultsAvailable(final SWIEmployeeServicesQueryPageOutput queryResponse) { final String isLastPageStr = getMoreResultsAvailableStr(queryResponse); if (isLastPageStr == null) { return null; } switch (isLastPageStr) { case "true": return FALSE; case "false": return TRUE; } return null; } private static void recordInvalidValueOfLastPage(final SWIEmployeeServicesQueryPageOutput queryResponse) { LOG.warn("Unsupported value of attribute \"LastPage\" in the response: {0}", getMoreResultsAvailableStr(queryResponse)); } private static String getMoreResultsAvailableStr(final SWIEmployeeServicesQueryPageOutput queryResponse) { return queryResponse.getLastPage(); } private SWIEmployeeServicesQueryPageInput setupQueryInput(final Filter query) { final Filter.Mode queryMode = (query == null) ? Filter.Mode.RETURN_ALL : query.mode; final Pair<SWIEmployeeServicesQueryPageInput, Employee> prototype = queryInputPrototypes.get(queryMode); switch (queryMode) { case SEARCH_BY_ID: prototype.b.setId(query.param); break; case SEARCH_BY_LOGIN_NAME: prototype.b.setLoginName(query.param); break; } return prototype.a; } private static ConnectorObject createAccount(final Employee employee) { final ConnectorObjectBuilder builder = new ConnectorObjectBuilder(); builder.setUid (employee.getId()); builder.setName(employee.getLoginName()); builder.addAttribute(ATTR_ALIAS, employee.getAlias()); builder.addAttribute(ATTR_EMPLOYEE_TYPE_CODE, employee.getEmployeeTypeCode()); builder.addAttribute(ATTR_PERSONAL_TITLE, employee.getPersonalTitle()); builder.addAttribute(ATTR_PREFERRED_COMMUNICATION, employee.getPreferredCommunications()); builder.addAttribute(ATTR_TIME_ZONE, employee.getTimeZone()); builder.addAttribute(ATTR_USER_TYPE, employee.getUserType()); builder.addAttribute(ATTR_CELL_PHONE, employee.getCellPhone()); builder.addAttribute(ATTR_EMAIL_ADDR, employee.getEMailAddr()); builder.addAttribute(ATTR_FAX, employee.getFax()); builder.addAttribute(ATTR_FIRST_NAME, employee.getFirstName()); builder.addAttribute(ATTR_JOB_TITLE, employee.getJobTitle()); builder.addAttribute(ATTR_LAST_NAME, employee.getLastName()); builder.addAttribute(ATTR_PHONE, employee.getPhone()); builder.addAttribute(ATTR_SALES_CHANNEL, employee.getSalesChannel()); POSITIONS.fillConnObjAttributes(employee, builder); ORGANIZATIONS.fillConnObjAttributes(employee, builder); RESPONSIBILITIES.fillConnObjAttributes(employee, builder); builder.addAttribute(OperationalAttributes.ENABLE_NAME, isEmployeeActive(employee)); final ConnectorObject account = builder.build(); return account; } private static Boolean isEmployeeActive(final Employee employee) { final String status = employee.getEmployeeStatus(); if (status == null) { LOG.warn("Employee {0} has assigned no employee status.", employee.getId()); return null; } switch (status) { case EMPLOYEE_ACTIVE: return TRUE; case EMPLOYEE_INACTIVE: return FALSE; default: LOG.warn("Invalid employee status ({1}) assigned to employee #{0}.", employee.getId(), status); return null; } } private static String employeeActiveAsString(final Boolean active) { final String result; if (active == null) { result = null; } else { result = active ? EMPLOYEE_ACTIVE : EMPLOYEE_INACTIVE; } return result; } /** * Normalizes the page size such that it is either positive or {@code null}. * * @param pageSize page size to be normalized (possibly {@code null}) * @return the original page size if it is {@code null} or positive; * {@code null} otherwise */ private static Integer normalizePagedOption(final Integer pageSize) { return ((pageSize != null) && (pageSize <= 0)) ? null : pageSize; } @Override public Uid create(final ObjectClass objectClass, final Set<Attribute> createAttributes, final OperationOptions options) { if (!objectClass.equals(ObjectClass.ACCOUNT)) { throw new UnsupportedOperationException("This connector can only create accounts. Requested ObjectClass: " + objectClass.getObjectClassValue()); } if (LOG.isOk()) { LOG.ok("create(attributes = {1})", getAttributeNames(createAttributes)); } final SiebelEmployeeInsert1Input insertInput = createInsertInput(createAttributes); final SiebelEmployeeInsert1Output insertOutput; try { insertOutput = insertUpdateService.siebelEmployeeInsert1(insertInput); } catch (WebServiceException ex) { if (ex instanceof SOAPFaultException) { handleCreateOpSoapFault((SOAPFaultException) ex); } handleWebServiceException(ex); throw ex; } final String id = insertOutput.getListOfEmployeeInterface().getEmployee().get(0).getId(); return new Uid(id); } @Override public Uid update(final ObjectClass objectClass, final Uid uid, final Set<Attribute> replaceAttributes, final OperationOptions options) { if (!objectClass.equals(ObjectClass.ACCOUNT)) { throw new UnsupportedOperationException("This connector can only update accounts. Requested ObjectClass: " + objectClass.getObjectClassValue()); } if (LOG.isOk()) { LOG.ok("update(uid = {0}, attributes = {1})", uid.getUidValue(), getAttributeNames(replaceAttributes)); } final Set<String> missingAttributes = findMissingUpdateAttributes(replaceAttributes); final Set<Attribute> combinedReplaceAttributes; if (isEmpty(missingAttributes)) { combinedReplaceAttributes = replaceAttributes; } else { LOG.ok(" - needs to GET extra attributes: {0}", missingAttributes); final Employee employee = findEmployeeById(uid); if (employee == null) { throw new UnknownUidException(uid, ObjectClass.ACCOUNT); } combinedReplaceAttributes = addMissingAttributes(replaceAttributes, missingAttributes, employee); } final SiebelEmployeeUpdate1Input updateInput = createUpdateInput(uid, combinedReplaceAttributes); final SiebelEmployeeUpdate1Output updateOutput; try { updateOutput = insertUpdateService.siebelEmployeeUpdate1(updateInput); } catch (WebServiceException ex) { if (ex instanceof SOAPFaultException) { handleUpdateOpSoapFault((SOAPFaultException) ex); } handleWebServiceException(ex); throw ex; } final String id = updateOutput.getListOfEmployeeInterface().getEmployee().get(0).getId(); return new Uid(id); } /** * Creates a new set of attributes by combining the current attributes * with new attributes created from a given {@code Employee} object. * The attributes specified by the parameter are left unchanged * in the resulting set. * * @param currentAttributes current set of attributes * @param namesOfMissingAttributes names of attributes whose values are * to be taken from the given employee * @param employee employee to the values of missing attributes from * @return new set of attributes */ private Set<Attribute> addMissingAttributes(final Set<Attribute> currentAttributes, final Set<String> namesOfMissingAttributes, final Employee employee) { /* * Get values of missing attributes: */ final ConnectorObjectBuilder builder = new ConnectorObjectBuilder(); builder.setUid (employee.getId()); //necessary for builder.build() builder.setName(employee.getLoginName());//necessary for builder.build() if (containsAny(namesOfMissingAttributes, ATTR_PRIMARY_POSITION, ATTR_SECONDARY_POSITIONS)) { POSITIONS.fillConnObjAttributes(employee, builder); } if (containsAny(namesOfMissingAttributes, ATTR_PRIMARY_ORGANIZATION, ATTR_SECONDARY_ORGANIZATIONS)) { ORGANIZATIONS.fillConnObjAttributes(employee, builder); } if (containsAny(namesOfMissingAttributes, ATTR_PRIMARY_RESPONSIBILITY, ATTR_SECONDARY_RESPONSIBILITIES)) { RESPONSIBILITIES.fillConnObjAttributes(employee, builder); } final ConnectorObject connObj = builder.build(); /* * Create the combined set of attributes: */ final Set<Attribute> result = new HashSet<>(currentAttributes); for (String attrName : namesOfMissingAttributes) { final Attribute attribute = connObj.getAttributeByName(attrName); if (attribute != null) { result.add(attribute); } } /* * TODO: * Find a solution for the case that the new primary responsibility * (organization, position) is among the current secondary responsibilities * (organizations, positions). */ return result; } /** * Determines attributes whose values are missing for a correct update * of the account. * The reason why some attributes may be missing is the difference between * two different representations of multi-value attributes in Siebel * and in the ConnId framework. * <p>For example, in Siebel, all the employee * positions are considered to be a single set of positions where each * position has a boolean attribute (primary/secondary). In the ConnId * framework, the same set of positions is represented by two separate * attributes - a single-valued attribute &quot;primary position&quot; * and a multi-valued attribute &quot;secondary positions&quot;. * If the user modifies the primary position attribute only, * the UpdateOp operation only receives a single attribute * containing the new value of attribute &quot;primary position&quot;, * but it must pass an updated set of <em>all positions</em> to Siebel. * In such a case, the list of secondary positions must be obtained * (read from Siebel) such that it can be appended to the (updated) primary * position.</p> * * @param presentAttributes attributes whose values are being updated * and whose values are currently known * @return attributes that must be added to the given attributes * to make the update operation correct and successful */ private Set<String> findMissingUpdateAttributes(final Collection<Attribute> presentAttributes) { final Set<String> result = new HashSet<>(); final PrimaryXorSecondary positions = new PrimaryXorSecondary(ATTR_PRIMARY_POSITION, ATTR_SECONDARY_POSITIONS); final PrimaryXorSecondary organizations = new PrimaryXorSecondary(ATTR_PRIMARY_ORGANIZATION, ATTR_SECONDARY_ORGANIZATIONS); final PrimaryXorSecondary responsibilities = new PrimaryXorSecondary(ATTR_PRIMARY_RESPONSIBILITY, ATTR_SECONDARY_RESPONSIBILITIES); for (Attribute attribute : presentAttributes) { final String attrName = attribute.getName(); switch (attrName) { case ATTR_PRIMARY_POSITION: case ATTR_SECONDARY_POSITIONS: positions.markPresent(attrName); break; case ATTR_PRIMARY_ORGANIZATION: case ATTR_SECONDARY_ORGANIZATIONS: organizations.markPresent(attrName); break; case ATTR_PRIMARY_RESPONSIBILITY: case ATTR_SECONDARY_RESPONSIBILITIES: responsibilities.markPresent(attrName); break; } } result.add(positions.getMissing()); //may be null result.add(organizations.getMissing()); //may be null result.add(responsibilities.getMissing()); //may be null result.remove(null); return result; } private void handleCreateOpSoapFault(final SOAPFaultException exception) { final SOAPFaultInfo faultInfo = soapFaultInspector.getSOAPErrorInfo(exception); final SOAPFaultInfo.Error error = faultInfo.getFirstError(); if (error != null) { handleInvalidValue(exception, error); if (ERR_SYMBOL_DUPLICITE_LOGIN_NAME.equals(error.symbol)) { throw new AlreadyExistsException( error.symbol + ": " + error.msg, exception); } } } private void handleUpdateOpSoapFault(final SOAPFaultException exception) { final SOAPFaultInfo faultInfo = soapFaultInspector.getSOAPErrorInfo(exception); final SOAPFaultInfo.Error error = faultInfo.getFirstError(); if (error != null) { handleInvalidValue(exception, error); if (ERR_CODE_DUPLICITE_LOGIN_NAME.equals(error.code)) { throw new AlreadyExistsException(error.msg, exception); } } } private void handleInvalidValue(final SOAPFaultException exception, final SOAPFaultInfo.Error error) { if (isCausedByInvalidValue(error)) { throw new InvalidAttributeValueException(error.msg, exception); } } private static boolean isCausedByInvalidValue(final SOAPFaultInfo.Error error) { if (error.code != null) { switch (error.code) { case ERR_CODE_SPACE_IN_LOGIN_NAME: case ERR_CODE_MISSING_LOGIN_NAME: case ERR_CODE_NOT_FROM_PICKLIST: case ERR_CODE_NOT_IN_BOUND_LIST: case ERR_CODE_NOT_FROM_LIST_OF_VALUES: case ERR_CODE_INVALID_POSITION: case ERR_CODE_INVALID_ORG_OR_RESP: return true; } return false; } if (error.symbol != null) { switch (error.symbol) { case ERR_SYMBOL_NOT_IN_BOUND_LIST: case ERR_SYMBOL_INVALID_POSITION: case ERR_SYMBOL_INVALID_ORG_OR_RESP: return true; } return false; } return false; } private SiebelEmployeeInsert1Input createInsertInput(final Set<Attribute> attributes) { final ListOfEmployeeInterface listOfEmployees = createListOfEmployee(attributes); final SiebelEmployeeInsert1Input input = new SiebelEmployeeInsert1Input(); input.setListOfEmployeeInterface(listOfEmployees); return input; } private SiebelEmployeeUpdate1Input createUpdateInput(final Uid uid, final Set<Attribute> attributes) { final ListOfEmployeeInterface listOfEmployees = createListOfEmployee(attributes, uid); final SiebelEmployeeUpdate1Input input = new SiebelEmployeeUpdate1Input(); input.setListOfEmployeeInterface(listOfEmployees); return input; } private ListOfEmployeeInterface createListOfEmployee(final Set<Attribute> attributes) { return createListOfEmployee(attributes, null); } private ListOfEmployeeInterface createListOfEmployee(final Set<Attribute> attributes, final Uid uid) { final com.siebel.xml.employee_20interface.Employee employee = createEmployee(attributes, uid); final ListOfEmployeeInterface listOfEmployeeInterface = new ListOfEmployeeInterface(); listOfEmployeeInterface.getEmployee().add(employee); return listOfEmployeeInterface; } private com.siebel.xml.employee_20interface.Employee createEmployee(final Set<Attribute> attributes, final Uid uid) { final com.siebel.xml.employee_20interface.Employee employee = new com.siebel.xml.employee_20interface.Employee(); final PrimarySecondaryEmployeeAttrValue positions = new PrimarySecondaryEmployeeAttrValue(); final PrimarySecondaryEmployeeAttrValue organizations = new PrimarySecondaryEmployeeAttrValue(); final PrimarySecondaryEmployeeAttrValue responsibilities = new PrimarySecondaryEmployeeAttrValue(); final Operation operation; if (uid == null) { operation = CREATE; } else { operation = UPDATE; employee.setId(uid.getUidValue()); } for (Attribute attribute : attributes) { final String attrName = attribute.getName(); if (isSpecialName(attrName)) { if (attrName.equals(Name.NAME)) { employee.setLoginName(getStringValue(attribute)); } else if (attrName.equals(OperationalAttributes.ENABLE_NAME)) { employee.setEmployeeStatus(employeeActiveAsString(getBooleanValue(attribute))); } else { LOG.warn("Unsupported attribute ({0}) will not be applied to a new account.", attrName); } } else { switch (attrName) { case ATTR_SECONDARY_POSITIONS: setSecondaryAttrValues(attribute, positions); break; case ATTR_SECONDARY_ORGANIZATIONS: setSecondaryAttrValues(attribute, organizations); break; case ATTR_SECONDARY_RESPONSIBILITIES: setSecondaryAttrValues(attribute, responsibilities); break; default: String stringValue = getStringValue(attribute); if (isEmptyString(stringValue)) { if (operation == CREATE) { continue; } else { stringValue = ""; // if it was null, change it to "" } } switch (attrName) { case ATTR_ALIAS: employee.setAlias(stringValue); break; case ATTR_EMPLOYEE_TYPE_CODE: employee.setEmployeeTypeCode(stringValue); break; case ATTR_PERSONAL_TITLE: employee.setPersonalTitle(stringValue); break; case ATTR_PREFERRED_COMMUNICATION: employee.setPreferredCommunications(stringValue); break; case ATTR_TIME_ZONE: employee.setTimeZoneName(stringValue); break; case ATTR_USER_TYPE: employee.setUserType(stringValue); break; case ATTR_CELL_PHONE: employee.setCellPhone(stringValue); break; case ATTR_EMAIL_ADDR: employee.setEMailAddr(stringValue); break; case ATTR_FAX: employee.setFax(stringValue); break; case ATTR_FIRST_NAME: employee.setFirstName(stringValue); break; case ATTR_JOB_TITLE: employee.setJobTitle(stringValue); break; case ATTR_LAST_NAME: employee.setLastName(stringValue); break; case ATTR_PHONE: employee.setPhone(stringValue); break; case ATTR_SALES_CHANNEL: employee.setSalesChannel(stringValue); break; case ATTR_PRIMARY_POSITION: positions .setPrimary(stringValue); break; case ATTR_PRIMARY_ORGANIZATION: organizations .setPrimary(stringValue); break; case ATTR_PRIMARY_RESPONSIBILITY: responsibilities.setPrimary(stringValue); break; default: LOG.warn("Unsupported attribute ({0}) will not be applied to a new account.", attrName); } } } } POSITIONS .fillEmployeeProperties(positions, employee); ORGANIZATIONS .fillEmployeeProperties(organizations, employee); RESPONSIBILITIES.fillEmployeeProperties(responsibilities, employee); return employee; } /** * Analyses the given web service exception and handles the common causes. * If the given exception is found to be caused by a common scenario * (unauthorized user, request timeout), then the exception is handled * by throwing an appropriate runtime exception. In other cases, * no exception is thrown and no data is changed. * * @param exception exception to be analyzed (and possibly handled) * @exception InvalidCredentialException * if the given exception was caused by invalid credentials * @exception OperationTimeoutException * if the given exception was caused by a timeout during * the network communication */ private static void handleWebServiceException(final WebServiceException exception) { final Throwable cause = exception.getCause(); if (cause instanceof HTTPException) { final HTTPException httpException = (HTTPException) cause; final int responseCode = httpException.getResponseCode(); switch (responseCode) { case HTTP_STATUS_UNAUTHORIZED: throw new InvalidCredentialException(httpException.getMessage()); case HTTP_STATUS_REQUEST_TIMEOUT: throw new OperationTimeoutException(httpException.getMessage()); } } else if (cause instanceof SocketTimeoutException) { throw new OperationTimeoutException(cause.getMessage()); } } private static void setSecondaryAttrValues(final Attribute attribute, final PrimarySecondaryEmployeeAttrValue attrValue) { final List<Object> values = attribute.getValue(); if (!isEmpty(values)) { for (Object value : values) { final String trimmed = trimToNull(value); if (trimmed != null) { attrValue.addSecondary(trimmed); } } } } private static boolean isEmptyString(final String str) { return (str == null) || str.isEmpty(); } private static String trimToNull(final Object obj) { if (obj == null) { return null; } final String string = obj.toString(); if (string == null) { return null; } final String trimmed = string.trim(); if (trimmed.isEmpty()) { return null; } return trimmed; } /** * Helper class that gets/sets values of the following attributes: * <ul> * <li>primary position and secondary positions</li> * <li>primary organization and secondary organizations</li> * <li>primary responsibility and secondary responsibilities</li> * </ul> * The aim of this class is elimination of repetition of code * (now in methods {@link #fillConnObjAttributesImpl fillAttributesImpl(&hellip;)} * and {@link #fillEmployeeProperties fillEmployeeProperties(&hellip;)}). * * @param <P> type of attribute in the source object (<code>Employee</code>) * when employees are being read from Siebel * ({@code EmployeePosition}, {@code EmployeeOrganization}, * {@code EmployeeResponsibility}) * @param <Q> type of attribute in the target object (<code>Employee</code>) * when employees are being written to Siebel * ({@code RelatedPosition}, {@code RelatedEmployeeOrganization}, * {@code RelatedResponsibility}) */ private static final class PrimarySecondaryEmployeeAttribute<P, Q> { /* --------- reading from Siebel --------- */ private static final String CLASSNAME_PREFIX_READING = "Employee"; private final Method methodGetListOfEmployee; private final Method methodGetList; private final Method methodGetProp; private final Method methodIsPrimary; private final String connObjAttrPrimary; private final String connObjAttrSecondary; /* --------- writing to Siebel --------- */ private static final String CLASSNAME_PREFIX_WRITING = "Related"; private final Class<Q> clsWriteProperty; private final Class<?> clsWritePropertiesList; private final Method methodGetRelatedList; private final Method methodSetRelatedListObj; private final Method methodSetRelatedAttr; private final Method methodSetRelatedAttrPrimOrSec; private PrimarySecondaryEmployeeAttribute(final Class<P> readPropertyClass, final Class<Q> writePropertyClass, final String connObjAttrPrimary, final String connObjAttrSecondary) throws NoSuchMethodException, ClassNotFoundException { this(readPropertyClass, writePropertyClass, connObjAttrPrimary, connObjAttrSecondary, null); } private PrimarySecondaryEmployeeAttribute(final Class<P> readPropertyClass, final Class<Q> writePropertyClass, final String connObjAttrPrimary, final String connObjAttrSecondary, final String resourceAttrNameOverride) throws NoSuchMethodException, ClassNotFoundException { /* --------- reading from Siebel --------- */ { final String propertyClassName = readPropertyClass.getSimpleName(); //"EmployeePosition", "EmployeeOrganization", "EmployeeResponsibility" final String getListOfEmployeeMethodName = "getListOf" + propertyClassName; //"getListOfEmployeePosition", ... final String getListMethodName = "get" + propertyClassName; //"getEmployeePosition", ... assert propertyClassName.startsWith(CLASSNAME_PREFIX_READING); final String resourceAttrName = (resourceAttrNameOverride == null) ? propertyClassName.substring(CLASSNAME_PREFIX_READING.length()) //"Position", "Organization", "Responsibility" : resourceAttrNameOverride; final String getPropMethodName = "get" + resourceAttrName; //"getPosition", "getOrganization", "getResponsibility" final String isPrimaryMethodName = "getIsPrimaryMVG"; methodGetListOfEmployee = Employee.class.getDeclaredMethod(getListOfEmployeeMethodName); // Employee.getListOfEmployeePosition() : ListOfEmployeePosition methodGetList = methodGetListOfEmployee.getReturnType().getDeclaredMethod(getListMethodName); // ListOfEmployeePosition.getEmployeePosition() : List<EmployeePosition> methodGetProp = readPropertyClass.getDeclaredMethod(getPropMethodName); // EmployeePosition.getPosition() : String methodIsPrimary = readPropertyClass.getDeclaredMethod(isPrimaryMethodName); // EmployeePosition.getIsPrimaryMVG() : String this.connObjAttrPrimary = connObjAttrPrimary; this.connObjAttrSecondary = connObjAttrSecondary; } /* --------- writing to Siebel --------- */ { final String propertyClassName = writePropertyClass.getSimpleName(); //"RelatedPosition", "RelatedEmployeeOrganization", "RelatedResponsibility" final String getListMethodName = "get" + propertyClassName; //"getRelatedPosition", ... final String setListObjMethodName = "setListOf" + propertyClassName; //"setListOfRelatedPosition", ... assert propertyClassName.startsWith(CLASSNAME_PREFIX_WRITING); final String resourceAttrName = (resourceAttrNameOverride == null) ? propertyClassName.substring(CLASSNAME_PREFIX_WRITING.length()) //"Position", "EmployeeOrganization", "Responsibility" : resourceAttrNameOverride; final String setPropMethodName = "set" + resourceAttrName; //"setPosition", "setEmployeeOrganization", "setResponsibility" final String setIsPrimaryMethodName = "setIsPrimaryMVG"; clsWriteProperty = writePropertyClass; // RelatedPosition, ... clsWritePropertiesList = deriveWritePropertiesListClass(clsWriteProperty); // ListOfRelatedPosition, ... methodGetRelatedList = clsWritePropertiesList.getDeclaredMethod(getListMethodName); // ListOfRelatedPosition.getRelatedPosition() methodSetRelatedListObj = com.siebel.xml.employee_20interface.Employee.class .getDeclaredMethod(setListObjMethodName, clsWritePropertiesList); // Employee.setListOfRelatedPosition(...) methodSetRelatedAttr = writePropertyClass.getDeclaredMethod(setPropMethodName, String.class); //RelatedPosition.setPosition(String) methodSetRelatedAttrPrimOrSec = writePropertyClass.getDeclaredMethod(setIsPrimaryMethodName, String.class); //RelatedPosition.setIsPrimaryMVG(...) } } /** * Finds (and loads) a class that represents a list of the given * properties. For example, given class {@code RelatedResponsibility}, * this method returns class {@code ListOfRelatedResponsibility}. * * @param writePropertyClass type of properties that the returned class should be a list of * @return class reprenting a list of the given type of properties * @throws ClassNotFoundException if the class could not be loaded */ private static Class<?> deriveWritePropertiesListClass(final Class<?> writePropertyClass) throws ClassNotFoundException { final String packageName = writePropertyClass.getPackage().getName(); final String simpleName = writePropertyClass.getSimpleName(); final Class<?> result = Class.forName(packageName + ".ListOf" + simpleName, false, writePropertyClass.getClassLoader()); return result; } void fillConnObjAttributes(final Employee employee, final ConnectorObjectBuilder objBuilder) { try { fillConnObjAttributesImpl(employee, objBuilder); } catch (ReflectiveOperationException ex) { throw new RuntimeException(ex); } } private void fillConnObjAttributesImpl(final Employee employee, final ConnectorObjectBuilder objBuilder) throws ReflectiveOperationException { final Object listOfEmployeeProps = methodGetListOfEmployee.invoke(employee); // Employee.getListOfEmployeePosition() : ListOfEmployeePosition if (listOfEmployeeProps != null) { final List<P> employeeProps = (List<P>) methodGetList.invoke(listOfEmployeeProps); // ListOfEmployeePosition.getEmployeePosition() : List<EmployeePosition> if (!isEmpty(employeeProps)) { final Collection<String> secondaryProps = new ArrayList<>(); for (P empProp : employeeProps) { final String prop = (String) methodGetProp.invoke(empProp); // String position = EmployeePosition.getPosition(); if (isYes((String) methodIsPrimary.invoke(empProp))) { // if (isYes(employeePosition.getIsPrimaryMVG())) ... objBuilder.addAttribute(connObjAttrPrimary, prop); } else { secondaryProps.add(prop); } } objBuilder.addAttribute(connObjAttrSecondary, secondaryProps); } } } void fillEmployeeProperties(final PrimarySecondaryEmployeeAttrValue primarySecondary, final com.siebel.xml.employee_20interface.Employee employee) { if (PrimarySecondaryEmployeeAttrValue.isEmpty(primarySecondary)) { return; } try { fillEmployeePropertiesImpl(primarySecondary, employee); } catch (ReflectiveOperationException ex) { throw new RuntimeException(ex); } } private void fillEmployeePropertiesImpl(final PrimarySecondaryEmployeeAttrValue primarySecondary, final com.siebel.xml.employee_20interface.Employee employee) throws ReflectiveOperationException { if (PrimarySecondaryEmployeeAttrValue.isEmpty(primarySecondary)) { return; } final Object listObj = clsWritePropertiesList.newInstance(); // ListOfRelatedPosition listObj = new ListOfRelatedPosition(); final List<Q> list = (List<Q>) methodGetRelatedList.invoke(listObj); // List<RelatedPosition> list = listObj.getRelatedPosition(); final String primary = primarySecondary.getPrimary(); if (isNotEmpty(primary)) { list.add(createRelatedItem(primary, true)); // list.add(createPosition(primary, true)); } for (String secondary : primarySecondary.getSecondary()) { list.add(createRelatedItem(secondary, false)); // list.add(createPosition(secondary, false)); } methodSetRelatedListObj.invoke(employee, listObj); // employee.setListOfRelatedPosition(listObj); } private Q createRelatedItem(final String connObjAttrValue, // RelatedPosition createPosition(...) final boolean isPrimary) throws ReflectiveOperationException { final Q relatedItem = clsWriteProperty.newInstance(); // RelatedPosition position = new RelatedPosition(); methodSetRelatedAttr.invoke(relatedItem, connObjAttrValue); // position.setPosition(value); methodSetRelatedAttrPrimOrSec.invoke(relatedItem, booleanAsString(isPrimary)); // position.setIsPrimaryMVG(booleanAsString(primary)); return relatedItem; // return position; } private static boolean isYes(final String str) { return RESOURCE_PROP_VALUE_YES.equals(str); } private static String booleanAsString(final boolean value) { return value ? RESOURCE_PROP_VALUE_YES : RESOURCE_PROP_VALUE_NO; } } /** * Represents a complex type of an employee property that consits * of a primary value and a list of secondary values. * It is used for properties <em>positions</em> (where there is a primary * position and a list of secondary positions), <em>responsibilities</em> * (a primary responsibility and a list of secondary responsibilities) * and <em>employee organization</em> (a primary organization and a list of * secondary organizations). */ private static final class PrimarySecondaryEmployeeAttrValue { private static final List<String> EMPTY_LIST = emptyList(); private String primary; private List<String> secondaryList = EMPTY_LIST; void setPrimary(final String primary) { this.primary = primary; } void addSecondary(final String secondary) { if (secondaryList == EMPTY_LIST) { secondaryList = new ArrayList<>(); } secondaryList.add(secondary); } String getPrimary() { return primary; } List<String> getSecondary() { return secondaryList; } boolean isEmpty() { return (primary == null) && (secondaryList == EMPTY_LIST); } static boolean isEmpty(final PrimarySecondaryEmployeeAttrValue primarySecondary) { return (primarySecondary == null) || primarySecondary.isEmpty(); } } /** * Finds whether the given set contains any of the two given elements. * * @param <T> type of the elements * @param set set to be checked for presents of the given elements * @param one one of the two elements * @param two the other of the two elements * @return {@code true} if the given set does contain any of the elements, * {@code false} otherwise */ private static <T> boolean containsAny(final Set<T> set, final T one, final T two) { return set.contains(one) || set.contains(two); } }
Connector's method test() now explicitly calls configuration.validate().
src/main/java/com/evolveum/polygon/connector/siebel/SiebelConnector.java
Connector's method test() now explicitly calls configuration.validate().
Java
apache-2.0
c6b42ac5f91777207064da1a067fa9a0807789a4
0
siempredelao/Distance-From-Me-Android
package gc.david.dfm.ui; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.app.SearchManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.IntentSender; import android.content.res.Configuration; import android.graphics.Color; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.v4.content.ContextCompat; import android.support.v4.view.GravityCompat; import android.support.v4.view.MenuItemCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener; import com.google.android.gms.maps.GoogleMap.OnMapClickListener; import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.UiSettings; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.PolylineOptions; import com.google.common.collect.Lists; import com.inmobi.ads.InMobiAdRequestStatus; import com.inmobi.ads.InMobiBanner; import com.inmobi.ads.InMobiBanner.BannerAdListener; import com.inmobi.sdk.InMobiSdk; import com.jjoe64.graphview.GraphView; import com.jjoe64.graphview.GraphViewSeries; import com.jjoe64.graphview.GraphViewSeries.GraphViewSeriesStyle; import com.jjoe64.graphview.LineGraphView; import java.io.IOException; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.inject.Inject; import butterknife.BindView; import butterknife.OnClick; import dagger.Lazy; import gc.david.dfm.BuildConfig; import gc.david.dfm.DFMApplication; import gc.david.dfm.DFMPreferences; import gc.david.dfm.DeviceInfo; import gc.david.dfm.PackageManager; import gc.david.dfm.R; import gc.david.dfm.Utils; import gc.david.dfm.adapter.MarkerInfoWindowAdapter; import gc.david.dfm.dagger.DaggerMainComponent; import gc.david.dfm.dagger.MainModule; import gc.david.dfm.dagger.RootModule; import gc.david.dfm.dialog.AddressSuggestionsDialogFragment; import gc.david.dfm.dialog.DistanceSelectionDialogFragment; import gc.david.dfm.elevation.Elevation; import gc.david.dfm.elevation.ElevationPresenter; import gc.david.dfm.elevation.ElevationUseCase; import gc.david.dfm.feedback.Feedback; import gc.david.dfm.feedback.FeedbackPresenter; import gc.david.dfm.logger.DFMLogger; import gc.david.dfm.map.Haversine; import gc.david.dfm.map.LocationUtils; import gc.david.dfm.model.DaoSession; import gc.david.dfm.model.Distance; import gc.david.dfm.model.Position; import gc.david.dfm.service.GeofencingService; import static butterknife.ButterKnife.bind; import static gc.david.dfm.Utils.isOnline; import static gc.david.dfm.Utils.showAlertDialog; import static gc.david.dfm.Utils.toastIt; public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, OnMapReadyCallback, OnMapLongClickListener, OnMapClickListener, OnInfoWindowClickListener, Elevation.View { private static final String TAG = MainActivity.class.getSimpleName(); @BindView(R.id.elevationchart) protected RelativeLayout rlElevationChart; @BindView(R.id.closeChart) protected ImageView ivCloseElevationChart; @BindView(R.id.tbMain) protected Toolbar tbMain; @BindView(R.id.banner) protected InMobiBanner banner; @BindView(R.id.drawer_layout) protected DrawerLayout drawerLayout; @BindView(R.id.nvDrawer) protected NavigationView nvDrawer; @BindView(R.id.main_activity_showchart_floatingactionbutton) protected FloatingActionButton fabShowChart; @BindView(R.id.main_activity_mylocation_floatingactionbutton) protected FloatingActionButton fabMyLocation; @Inject protected DaoSession daoSession; @Inject protected Context appContext; @Inject protected Lazy<PackageManager> packageManager; @Inject protected Lazy<DeviceInfo> deviceInfo; @Inject protected ElevationUseCase elevationUseCase; private final BroadcastReceiver locationReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final double latitude = intent.getDoubleExtra(GeofencingService.GEOFENCE_RECEIVER_LATITUDE_KEY, 0D); final double longitude = intent.getDoubleExtra(GeofencingService.GEOFENCE_RECEIVER_LONGITUDE_KEY, 0D); final Location location = new Location(""); location.setLatitude(latitude); location.setLongitude(longitude); onLocationChanged(location); } }; private GoogleMap googleMap = null; private Location currentLocation = null; // Moves to current position if app has just started private boolean appHasJustStarted = true; private String distanceMeasuredAsText = ""; private MenuItem searchMenuItem = null; // Show position if we come from other app (p.e. Whatsapp) private boolean mustShowPositionWhenComingFromOutside = false; private LatLng sendDestinationPosition = null; private boolean bannerShown = false; private GraphView graphView = null; private List<LatLng> coordinates = Lists.newArrayList(); private float DEVICE_DENSITY; // TODO: 09.01.17 get rid of this field private ActionBarDrawerToggle actionBarDrawerToggle; private boolean calculatingDistance; private Elevation.Presenter elevationPresenter; @Override protected void onCreate(Bundle savedInstanceState) { DFMLogger.logMessage(TAG, "onCreate savedInstanceState=" + Utils.dumpBundleToString(savedInstanceState)); super.onCreate(savedInstanceState); InMobiSdk.setLogLevel(BuildConfig.DEBUG ? InMobiSdk.LogLevel.DEBUG : InMobiSdk.LogLevel.NONE); InMobiSdk.init(this, getString(R.string.inmobi_api_key)); setContentView(R.layout.activity_main); DaggerMainComponent.builder() .rootModule(new RootModule((DFMApplication) getApplication())) .mainModule(new MainModule()) .build() .inject(this); bind(this); setSupportActionBar(tbMain); final ActionBar supportActionBar = getSupportActionBar(); if (supportActionBar != null) { supportActionBar.setDisplayHomeAsUpEnabled(true); supportActionBar.setHomeButtonEnabled(true); } elevationPresenter = new ElevationPresenter(this, elevationUseCase); DEVICE_DENSITY = getResources().getDisplayMetrics().density; final SupportMapFragment supportMapFragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)); supportMapFragment.getMapAsync(this); banner.setListener(new BannerAdListener() { @Override public void onAdLoadSucceeded(InMobiBanner inMobiBanner) { DFMLogger.logMessage(TAG, "onAdLoadSucceeded"); banner.setVisibility(View.VISIBLE); bannerShown = true; // TODO: 06.01.17 remove this field then... fixMapPadding(); } @Override public void onAdLoadFailed(InMobiBanner inMobiBanner, InMobiAdRequestStatus inMobiAdRequestStatus) { DFMLogger.logMessage(TAG, String.format("onAdLoadFailed %s %s", inMobiAdRequestStatus.getStatusCode(), inMobiAdRequestStatus.getMessage())); } @Override public void onAdDisplayed(InMobiBanner inMobiBanner) { DFMLogger.logMessage(TAG, "onAdDisplayed"); } @Override public void onAdDismissed(InMobiBanner inMobiBanner) { DFMLogger.logMessage(TAG, "onAdDismissed"); } @Override public void onAdInteraction(InMobiBanner inMobiBanner, Map<Object, Object> map) { DFMLogger.logMessage(TAG, String.format("onAdInteraction %s", map.toString())); DFMLogger.logEvent("Ad tapped"); } @Override public void onUserLeftApplication(InMobiBanner inMobiBanner) { DFMLogger.logMessage(TAG, "onUserLeftApplication"); } @Override public void onAdRewardActionCompleted(InMobiBanner inMobiBanner, Map<Object, Object> map) { DFMLogger.logMessage(TAG, String.format("onAdRewardActionCompleted %s", map.toString())); } }); if (!BuildConfig.DEBUG) { banner.load(); } if (!isOnline(appContext)) { showConnectionProblemsDialog(); } // Iniciando la app if (currentLocation == null) { toastIt(getString(R.string.toast_loading_position), appContext); } handleIntents(getIntent()); nvDrawer.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.menu_current_position: menuItem.setChecked(true); drawerLayout.closeDrawers(); onStartingPointSelected(); return true; case R.id.menu_any_position: menuItem.setChecked(true); drawerLayout.closeDrawers(); onStartingPointSelected(); return true; case R.id.menu_rate_app: drawerLayout.closeDrawers(); showRateDialog(); return true; case R.id.menu_legal_notices: drawerLayout.closeDrawers(); showGooglePlayServiceLicenseDialog(); return true; case R.id.menu_settings: drawerLayout.closeDrawers(); openSettingsActivity(); return true; case R.id.menu_help_feedback: drawerLayout.closeDrawers(); startActivity(new Intent(MainActivity.this, HelpAndFeedbackActivity.class)); return true; } return false; } }); // TODO: 23.08.15 check if this is still needed actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.progressdialog_search_position_message, R.string.progressdialog_search_position_message) { @Override public void onDrawerOpened(View drawerView) { DFMLogger.logMessage(TAG, "onDrawerOpened"); super.onDrawerOpened(drawerView); supportInvalidateOptionsMenu(); } @Override public void onDrawerClosed(View drawerView) { DFMLogger.logMessage(TAG, "onDrawerClosed"); super.onDrawerClosed(drawerView); supportInvalidateOptionsMenu(); } }; drawerLayout.addDrawerListener(actionBarDrawerToggle); } @Override public void onMapReady(final GoogleMap map) { googleMap = map; googleMap.getUiSettings().setMyLocationButtonEnabled(false); googleMap.setMyLocationEnabled(true); googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); googleMap.setOnMapLongClickListener(this); googleMap.setOnMapClickListener(this); googleMap.setOnInfoWindowClickListener(this); googleMap.setInfoWindowAdapter(new MarkerInfoWindowAdapter(this)); onStartingPointSelected(); } @Override public void onMapLongClick(LatLng point) { DFMLogger.logMessage(TAG, "onMapLongClick"); calculatingDistance = true; if (getSelectedDistanceMode() == DistanceMode.DISTANCE_FROM_ANY_POINT) { if (coordinates.isEmpty()) { toastIt(getString(R.string.toast_first_point_needed), appContext); } else { coordinates.add(point); drawAndShowMultipleDistances(coordinates, "", false, true); } } else if (currentLocation != null) { // Without current location, we cannot calculate any distance if (getSelectedDistanceMode() == DistanceMode.DISTANCE_FROM_CURRENT_POINT && coordinates.isEmpty()) { coordinates.add(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude())); } coordinates.add(point); drawAndShowMultipleDistances(coordinates, "", false, true); } calculatingDistance = false; } @Override public void onMapClick(LatLng point) { DFMLogger.logMessage(TAG, "onMapClick"); if (getSelectedDistanceMode() == DistanceMode.DISTANCE_FROM_ANY_POINT) { if (!calculatingDistance) { coordinates.clear(); } calculatingDistance = true; if (coordinates.isEmpty()) { googleMap.clear(); } coordinates.add(point); googleMap.addMarker(new MarkerOptions().position(point)); } else { // Without current location, we cannot calculate any distance if (currentLocation != null) { if (!calculatingDistance) { coordinates.clear(); } calculatingDistance = true; if (coordinates.isEmpty()) { googleMap.clear(); coordinates.add(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude())); } coordinates.add(point); googleMap.addMarker(new MarkerOptions().position(point)); } } } @Override public void onInfoWindowClick(Marker marker) { DFMLogger.logMessage(TAG, "onInfoWindowClick"); ShowInfoActivity.open(this, coordinates, distanceMeasuredAsText); } private void onStartingPointSelected() { if (getSelectedDistanceMode() == DistanceMode.DISTANCE_FROM_CURRENT_POINT) { DFMLogger.logMessage(TAG, "onStartingPointSelected Distance from current point"); } else{ DFMLogger.logMessage(TAG, "onStartingPointSelected Distance from any point"); } calculatingDistance = false; coordinates.clear(); googleMap.clear(); elevationPresenter.onReset(); } private DistanceMode getSelectedDistanceMode() { return nvDrawer.getMenu().findItem(R.id.menu_current_position).isChecked() ? DistanceMode.DISTANCE_FROM_CURRENT_POINT : DistanceMode.DISTANCE_FROM_ANY_POINT; } @Override protected void onPostCreate(Bundle savedInstanceState) { DFMLogger.logMessage(TAG, "onPostCreate savedInstanceState=" + Utils.dumpBundleToString(savedInstanceState)); super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. if (actionBarDrawerToggle != null) { actionBarDrawerToggle.syncState(); } else { DFMLogger.logMessage(TAG, "onPostCreate actionBarDrawerToggle null"); } } @Override public void onConfigurationChanged(Configuration newConfig) { DFMLogger.logMessage(TAG, "onConfigurationChanged"); super.onConfigurationChanged(newConfig); if (actionBarDrawerToggle != null) { actionBarDrawerToggle.onConfigurationChanged(newConfig); } else { DFMLogger.logMessage(TAG, "onConfigurationChanged actionBarDrawerToggle null"); } } @Override protected void onNewIntent(Intent intent) { DFMLogger.logMessage(TAG, "onNewIntent " + Utils.dumpIntentToString(intent)); setIntent(intent); handleIntents(intent); } /** * Handles all Intent types. * * @param intent The input intent. */ private void handleIntents(final Intent intent) { DFMLogger.logMessage(TAG, "handleIntents " + Utils.dumpIntentToString(intent)); if (intent != null) { if (Intent.ACTION_SEARCH.equals(intent.getAction())) { handleSearchIntent(intent); } else if (Intent.ACTION_VIEW.equals(intent.getAction())) { handleViewPositionIntent(intent); } } } /** * Handles a search intent. * * @param intent Input intent. */ private void handleSearchIntent(final Intent intent) { DFMLogger.logMessage(TAG, "handleSearchIntent"); // Para controlar instancias únicas, no queremos que cada vez que // busquemos nos inicie una nueva instancia de la aplicación final String query = intent.getStringExtra(SearchManager.QUERY); if (currentLocation != null) { new SearchPositionByName().execute(query); } if (searchMenuItem != null) { MenuItemCompat.collapseActionView(searchMenuItem); } } /** * Handles a send intent with position data. * * @param intent Input intent with position data. */ private void handleViewPositionIntent(final Intent intent) { DFMLogger.logMessage(TAG, "handleViewPositionIntent"); final Uri uri = intent.getData(); DFMLogger.logMessage(TAG, "handleViewPositionIntent uri=" + uri.toString()); final String uriScheme = uri.getScheme(); if (uriScheme.equals("geo")) { handleGeoSchemeIntent(uri); } else if ((uriScheme.equals("http") || uriScheme.equals("https")) && (uri.getHost().equals("maps.google.com"))) { // Manage maps.google.com?q=latitude,longitude handleMapsHostIntent(uri); } else { final Exception exception = new Exception("Imposible tratar la query " + uri.toString()); DFMLogger.logException(exception); toastIt("Unable to parse address", this); } } private void handleGeoSchemeIntent(final Uri uri) { final String schemeSpecificPart = uri.getSchemeSpecificPart(); final Matcher matcher = getMatcherForUri(schemeSpecificPart); if (matcher.find()) { if (matcher.group(1).equals("0") && matcher.group(2).equals("0")) { if (matcher.find()) { // Manage geo:0,0?q=lat,lng(label) setDestinationPosition(matcher); } else { // Manage geo:0,0?q=my+street+address String destination = Uri.decode(uri.getQuery()).replace('+', ' '); destination = destination.replace("q=", ""); // TODO check this ugly workaround new SearchPositionByName().execute(destination); mustShowPositionWhenComingFromOutside = true; } } else { // Manage geo:latitude,longitude or geo:latitude,longitude?z=zoom setDestinationPosition(matcher); } } else { final NoSuchFieldException noSuchFieldException = new NoSuchFieldException("Error al obtener las coordenadas. Matcher = " + matcher.toString()); DFMLogger.logException(noSuchFieldException); toastIt("Unable to parse address", this); } } private void handleMapsHostIntent(final Uri uri) { final String queryParameter = uri.getQueryParameter("q"); if (queryParameter != null) { final Matcher matcher = getMatcherForUri(queryParameter); if (matcher.find()) { setDestinationPosition(matcher); } else { final NoSuchFieldException noSuchFieldException = new NoSuchFieldException("Error al obtener las coordenadas. Matcher = " + matcher.toString()); DFMLogger.logException(noSuchFieldException); toastIt("Unable to parse address", this); } } else { final NoSuchFieldException noSuchFieldException = new NoSuchFieldException("Query sin parámetro q."); DFMLogger.logException(noSuchFieldException); toastIt("Unable to parse address", this); } } private void setDestinationPosition(final Matcher matcher) { DFMLogger.logMessage(TAG, "setDestinationPosition"); sendDestinationPosition = new LatLng(Double.valueOf(matcher.group(1)), Double.valueOf(matcher.group(2))); mustShowPositionWhenComingFromOutside = true; } private Matcher getMatcherForUri(final String schemeSpecificPart) { DFMLogger.logMessage(TAG, "getMatcherForUri scheme=" + schemeSpecificPart); // http://regex101.com/ // http://www.regexplanet.com/advanced/java/index.html final String regex = "(\\-?\\d+\\.*\\d*),(\\-?\\d+\\.*\\d*)"; final Pattern pattern = Pattern.compile(regex); return pattern.matcher(schemeSpecificPart); } private void showConnectionProblemsDialog() { DFMLogger.logMessage(TAG, "showConnectionProblemsDialog"); showAlertDialog(android.provider.Settings.ACTION_SETTINGS, getString(R.string.dialog_connection_problems_title), getString(R.string.dialog_connection_problems_message), getString(R.string.dialog_connection_problems_positive_button), getString(R.string.dialog_connection_problems_negative_button), MainActivity.this); } @Override public boolean onCreateOptionsMenu(Menu menu) { DFMLogger.logMessage(TAG, "onCreateOptionsMenu"); // Inflate the options menu from XML final MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); // Expandir el EditText de la búsqueda a lo largo del ActionBar searchMenuItem = menu.findItem(R.id.action_search); final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchMenuItem); // Configure the search info and add any event listeners final SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); // Indicamos que la activity actual sea la buscadora searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setSubmitButtonEnabled(false); searchView.setQueryRefinementEnabled(true); searchView.setIconifiedByDefault(true); // Muestra el item de menú de cargar si hay elementos en la BD // TODO hacerlo en segundo plano final List<Distance> allDistances = daoSession.loadAll(Distance.class); if (allDistances.isEmpty()) { final MenuItem loadItem = menu.findItem(R.id.action_load); loadItem.setVisible(false); } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { DFMLogger.logMessage(TAG, "onOptionsItemSelected item=" + item.getItemId()); // The action bar home/up action should open or close the drawer. // ActionBarDrawerToggle will take care of this. if (actionBarDrawerToggle != null && actionBarDrawerToggle.onOptionsItemSelected(item)) { DFMLogger.logMessage(TAG, "onOptionsItemSelected ActionBar home button click"); return true; } switch (item.getItemId()) { case R.id.action_search: return true; case R.id.action_load: loadDistancesFromDB(); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onBackPressed() { DFMLogger.logMessage(TAG, "onBackPressed"); if (drawerLayout != null && drawerLayout.isDrawerOpen(GravityCompat.START)) { drawerLayout.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } /** * Loads all entries stored in the database and show them to the user in a * dialog. */ private void loadDistancesFromDB() { DFMLogger.logMessage(TAG, "loadDistancesFromDB"); // TODO hacer esto en segundo plano final List<Distance> allDistances = daoSession.loadAll(Distance.class); if (allDistances != null && !allDistances.isEmpty()) { final DistanceSelectionDialogFragment distanceSelectionDialogFragment = new DistanceSelectionDialogFragment(); distanceSelectionDialogFragment.setDistanceList(allDistances); distanceSelectionDialogFragment.setOnDialogActionListener(new DistanceSelectionDialogFragment.OnDialogActionListener() { @Override public void onItemClick(int position) { final Distance distance = allDistances.get(position); final List<Position> positionList = daoSession.getPositionDao() ._queryDistance_PositionList(distance.getId()); coordinates.clear(); coordinates.addAll(Utils.convertPositionListToLatLngList(positionList)); drawAndShowMultipleDistances(coordinates, distance.getName() + "\n", true, true); } }); distanceSelectionDialogFragment.show(getSupportFragmentManager(), null); } } /** * Shows settings activity. */ private void openSettingsActivity() { DFMLogger.logMessage(TAG, "openSettingsActivity"); startActivity(new Intent(MainActivity.this, SettingsActivity.class)); } /** * Shows rate dialog. */ private void showRateDialog() { DFMLogger.logMessage(TAG, "showRateDialog"); final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.dialog_rate_app_title) .setMessage(R.string.dialog_rate_app_message) .setPositiveButton(getString(R.string.dialog_rate_app_positive_button), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); openPlayStoreAppPage(); } }) .setNegativeButton(getString(R.string.dialog_rate_app_negative_button), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); openFeedbackActivity(); } }).create().show(); } /** * Opens Google Play Store, in Distance From Me page */ private void openPlayStoreAppPage() { DFMLogger.logMessage(TAG, "openPlayStoreAppPage"); startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=gc.david.dfm"))); } /** * Opens the feedback activity. */ private void openFeedbackActivity() { DFMLogger.logMessage(TAG, "openFeedbackActivity"); new FeedbackPresenter(new Feedback.View() { @Override public void showError() { toastIt(getString(R.string.toast_send_feedback_error), appContext); } @Override public void showEmailClient(final Intent intent) { startActivity(intent); } @Override public Context context() { return appContext; } }, packageManager.get(), deviceInfo.get()).start(); } /** * Shows an AlertDialog with the Google Play Services License. */ private void showGooglePlayServiceLicenseDialog() { DFMLogger.logMessage(TAG, "showGooglePlayServiceLicenseDialog"); final String LicenseInfo = GoogleApiAvailability.getInstance().getOpenSourceSoftwareLicenseInfo(appContext); final AlertDialog.Builder LicenseDialog = new AlertDialog.Builder(MainActivity.this); LicenseDialog.setTitle(R.string.menu_legal_notices_title); LicenseDialog.setMessage(LicenseInfo); LicenseDialog.show(); } /** * Called when the Activity is no longer visible at all. Stop updates and * disconnect. */ @Override public void onStop() { DFMLogger.logMessage(TAG, "onStop"); super.onStop(); unregisterReceiver(locationReceiver); stopService(new Intent(this, GeofencingService.class)); } /** * Called when the Activity is restarted, even before it becomes visible. */ @Override public void onStart() { DFMLogger.logMessage(TAG, "onStart"); super.onStart(); registerReceiver(locationReceiver, new IntentFilter(GeofencingService.GEOFENCE_RECEIVER_ACTION)); startService(new Intent(this, GeofencingService.class)); } /** * Called when the system detects that this Activity is now visible. */ @SuppressLint("NewApi") // TODO: 09.01.17 remove @Override public void onResume() { DFMLogger.logMessage(TAG, "onResume"); super.onResume(); invalidateOptionsMenu(); checkPlayServices(); } @Override public void onDestroy() { DFMLogger.logMessage(TAG, "onDestroy"); elevationPresenter.onReset(); super.onDestroy(); } /** * Handle results returned to this Activity by other Activities started with * startActivityForResult(). In particular, the method onConnectionFailed() * in LocationUpdateRemover and LocationUpdateRequester may call * startResolutionForResult() to start an Activity that handles Google Play * services problems. The result of this call returns here, to * onActivityResult. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { DFMLogger.logMessage(TAG, "onActivityResult requestCode=" + requestCode + ", " + "resultCode=" + resultCode + "intent=" + Utils.dumpIntentToString(intent)); // Choose what to do based on the request code switch (requestCode) { // If the request code matches the code sent in onConnectionFailed case LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST: switch (resultCode) { // If Google Play services resolved the problem case Activity.RESULT_OK: // Log the result // Log.d(LocationUtils.APPTAG, getString(R.string.resolved)); // Display the result // mConnectionState.setText(R.string.connected); // mConnectionStatus.setText(R.string.resolved); break; // If any other result was returned by Google Play services default: // Log the result // Log.d(LocationUtils.APPTAG, // getString(R.string.no_resolution)); // Display the result // mConnectionState.setText(R.string.disconnected); // mConnectionStatus.setText(R.string.no_resolution); break; } // If any other request code was received default: // Report that this Activity received an unknown requestCode // Log.d(LocationUtils.APPTAG, // getString(R.string.unknown_activity_request_code, requestCode)); break; } } /** * Checks if Google Play Services is available on the device. * * @return Returns <code>true</code> if available; <code>false</code> * otherwise. */ private boolean checkPlayServices() { DFMLogger.logMessage(TAG, "checkPlayServices"); final GoogleApiAvailability googleApiAvailabilityInstance = GoogleApiAvailability.getInstance(); // Comprobamos que Google Play Services está disponible en el terminal final int resultCode = googleApiAvailabilityInstance.isGooglePlayServicesAvailable(appContext); // Si está disponible, devolvemos verdadero. Si no, mostramos un mensaje // de error y devolvemos falso if (resultCode == ConnectionResult.SUCCESS) { DFMLogger.logMessage(TAG, "checkPlayServices success"); return true; } else { if (googleApiAvailabilityInstance.isUserResolvableError(resultCode)) { DFMLogger.logMessage(TAG, "checkPlayServices isUserRecoverableError"); final int RQS_GooglePlayServices = 1; googleApiAvailabilityInstance.getErrorDialog(this, resultCode, RQS_GooglePlayServices).show(); } else { DFMLogger.logMessage(TAG, "checkPlayServices device not supported, finishing"); finish(); } return false; } } /** * Called by Location Services if the attempt to Location Services fails. */ @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { DFMLogger.logMessage(TAG, "onConnectionFailed"); /* * Google Play services can resolve some errors it detects. If the error * has a resolution, try sending an Intent to start a Google Play * services activity that can resolve error. */ if (connectionResult.hasResolution()) { DFMLogger.logMessage(TAG, "onConnectionFailed connection has resolution"); try { // Start an Activity that tries to resolve the error connectionResult.startResolutionForResult(this, LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST); /* * Thrown if Google Play services cancelled the original * PendingIntent */ } catch (IntentSender.SendIntentException e) { // Log the error e.printStackTrace(); DFMLogger.logException(e); } } else { DFMLogger.logMessage(TAG, "onConnectionFailed connection does not have resolution"); // If no resolution is available, display a dialog to the user with // the error. showErrorDialog(connectionResult.getErrorCode()); } } public void onLocationChanged(final Location location) { DFMLogger.logMessage(TAG, "onLocationChanged"); if (currentLocation != null) { currentLocation.set(location); } else { currentLocation = new Location(location); } if (appHasJustStarted) { DFMLogger.logMessage(TAG, "onLocationChanged appHasJustStarted"); if (mustShowPositionWhenComingFromOutside) { DFMLogger.logMessage(TAG, "onLocationChanged mustShowPositionWhenComingFromOutside"); if (currentLocation != null && sendDestinationPosition != null) { new SearchPositionByCoordinates().execute(sendDestinationPosition); mustShowPositionWhenComingFromOutside = false; } } else { DFMLogger.logMessage(TAG, "onLocationChanged NOT mustShowPositionWhenComingFromOutside"); final LatLng latlng = new LatLng(location.getLatitude(), location.getLongitude()); // 17 is a good zoom level for this action googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latlng, 17)); } appHasJustStarted = false; } } /** * Shows a dialog returned by Google Play services for the connection error * code * * @param errorCode An error code returned from onConnectionFailed */ private void showErrorDialog(final int errorCode) { DFMLogger.logMessage(TAG, "showErrorDialog errorCode=" + errorCode); // Get the error dialog from Google Play services final Dialog errorDialog = GoogleApiAvailability.getInstance().getErrorDialog(this, errorCode, LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST); // If Google Play services can provide an error dialog if (errorDialog != null) { // Create a new DialogFragment in which to show the error dialog final ErrorDialogFragment errorFragment = new ErrorDialogFragment(); // Set the dialog in the DialogFragment errorFragment.setDialog(errorDialog); // Show the error dialog in the DialogFragment errorFragment.show(getSupportFragmentManager(), "Geofence detection"); } } private void drawAndShowMultipleDistances(final List<LatLng> coordinates, final String message, final boolean isLoadingFromDB, final boolean mustApplyZoomIfNeeded) { DFMLogger.logMessage(TAG, "drawAndShowMultipleDistances"); // Borramos los antiguos marcadores y lineas googleMap.clear(); // Calculamos la distancia distanceMeasuredAsText = calculateDistance(coordinates); // Pintar todos menos el primero si es desde la posición actual addMarkers(coordinates, distanceMeasuredAsText, message, isLoadingFromDB); // Añadimos las líneas addLines(coordinates, isLoadingFromDB); // Aquí hacer la animación de la cámara moveCameraZoom(coordinates.get(0), coordinates.get(coordinates.size() - 1), mustApplyZoomIfNeeded); // Muestra el perfil de elevación si está en las preferencias // y si está conectado a internet // TODO: 06.01.17 move this decision to ElevationPresenter if (DFMPreferences.shouldShowElevationChart(appContext) && isOnline(appContext)) { elevationPresenter.buildChart(coordinates); } } /** * Adds a marker to the map in a specified position and shows its info * window. * * @param coordinates Positions list. * @param distance Distance to destination. * @param message Destination address (if needed). * @param isLoadingFromDB Indicates whether we are loading data from database. */ private void addMarkers(final List<LatLng> coordinates, final String distance, final String message, final boolean isLoadingFromDB) { DFMLogger.logMessage(TAG, "addMarkers"); for (int i = 0; i < coordinates.size(); i++) { if ((i == 0 && (isLoadingFromDB || getSelectedDistanceMode() == DistanceMode.DISTANCE_FROM_ANY_POINT)) || (i == coordinates.size() - 1)) { final LatLng coordinate = coordinates.get(i); final Marker marker = addMarker(coordinate); if (i == coordinates.size() - 1) { marker.setTitle(message + distance); marker.showInfoWindow(); } } } } private Marker addMarker(final LatLng coordinate) { DFMLogger.logMessage(TAG, "addMarker"); return googleMap.addMarker(new MarkerOptions().position(coordinate)); } private void addLines(final List<LatLng> coordinates, final boolean isLoadingFromDB) { DFMLogger.logMessage(TAG, "addLines"); for (int i = 0; i < coordinates.size() - 1; i++) { addLine(coordinates.get(i), coordinates.get(i + 1), isLoadingFromDB); } } /** * Adds a line between start and end positions. * * @param start Start position. * @param end Destination position. */ private void addLine(final LatLng start, final LatLng end, final boolean isLoadingFromDB) { DFMLogger.logMessage(TAG, "addLine"); final PolylineOptions lineOptions = new PolylineOptions().add(start).add(end); lineOptions.width(3 * getResources().getDisplayMetrics().density); lineOptions.color(isLoadingFromDB ? Color.YELLOW : Color.GREEN); googleMap.addPolyline(lineOptions); } /** * Returns the distance between start and end positions normalized by device * locale. * * @param coordinates position list. * @return The normalized distance. */ private String calculateDistance(final List<LatLng> coordinates) { DFMLogger.logMessage(TAG, "calculateDistance"); double distanceInMetres = Utils.calculateDistanceInMetres(coordinates); return Haversine.normalizeDistance(distanceInMetres, getAmericanOrEuropeanLocale()); } /** * Moves camera position and applies zoom if needed. * * @param p1 Start position. * @param p2 Destination position. */ private void moveCameraZoom(final LatLng p1, final LatLng p2, final boolean mustApplyZoomIfNeeded) { DFMLogger.logMessage(TAG, "moveCameraZoom"); double centerLat = 0.0; double centerLon = 0.0; // Diferenciamos según preferencias final String centre = DFMPreferences.getAnimationPreference(getBaseContext()); if (DFMPreferences.ANIMATION_CENTRE_VALUE.equals(centre)) { centerLat = (p1.latitude + p2.latitude) / 2; centerLon = (p1.longitude + p2.longitude) / 2; } else if (DFMPreferences.ANIMATION_DESTINATION_VALUE.equals(centre)) { centerLat = p2.latitude; centerLon = p2.longitude; } else if (centre.equals(DFMPreferences.NO_ANIMATION_DESTINATION_VALUE)) { return; } if (mustApplyZoomIfNeeded) { googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(centerLat, centerLon), Utils.calculateZoom(p1, p2))); } else { googleMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(p2.latitude, p2.longitude))); } } private void fixMapPadding() { if (bannerShown) { DFMLogger.logMessage(TAG, "fixMapPadding bannerShown"); if (rlElevationChart.isShown()) { DFMLogger.logMessage(TAG, "fixMapPadding elevationChartShown"); googleMap.setPadding(0, rlElevationChart.getHeight(), 0, banner.getLayoutParams().height); } else { DFMLogger.logMessage(TAG, "fixMapPadding NOT elevationChartShown"); googleMap.setPadding(0, 0, 0, banner.getLayoutParams().height); } } else { DFMLogger.logMessage(TAG, "fixMapPadding NOT bannerShown"); if (rlElevationChart.isShown()) { DFMLogger.logMessage(TAG, "fixMapPadding elevationChartShown"); googleMap.setPadding(0, rlElevationChart.getHeight(), 0, 0); } else { DFMLogger.logMessage(TAG, "fixMapPadding NOT elevationChartShown"); googleMap.setPadding(0, 0, 0, 0); } } } @Override public void setPresenter(final Elevation.Presenter presenter) { this.elevationPresenter = presenter; } @Override public void hideChart() { rlElevationChart.setVisibility(View.INVISIBLE); fabShowChart.setVisibility(View.INVISIBLE); fixMapPadding(); } @Override public void showChart() { rlElevationChart.setVisibility(View.VISIBLE); fixMapPadding(); } @Override public void buildChart(final List<Double> elevationList) { final Locale locale = getAmericanOrEuropeanLocale(); // Creates the series and adds data to it final GraphViewSeries series = buildGraphViewSeries(elevationList, locale); if (graphView == null) { graphView = new LineGraphView(appContext, getString(R.string.elevation_chart_title, Haversine.getAltitudeUnitByLocale(locale))); graphView.getGraphViewStyle().setGridColor(Color.TRANSPARENT); graphView.getGraphViewStyle().setNumHorizontalLabels(1); // Not working with zero? graphView.getGraphViewStyle().setTextSize(15 * DEVICE_DENSITY); graphView.getGraphViewStyle().setVerticalLabelsWidth((int) (50 * DEVICE_DENSITY)); rlElevationChart.addView(graphView); ivCloseElevationChart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { elevationPresenter.onCloseChart(); } }); } graphView.removeAllSeries(); graphView.addSeries(series); elevationPresenter.onChartBuilt(); } @NonNull private GraphViewSeries buildGraphViewSeries(final List<Double> elevationList, final Locale locale) { final GraphViewSeriesStyle style = new GraphViewSeriesStyle(ContextCompat.getColor(getApplicationContext(), R.color.elevation_chart_line), (int) (3 * DEVICE_DENSITY)); final GraphViewSeries series = new GraphViewSeries(null, style, new GraphView.GraphViewData[]{}); for (int w = 0; w < elevationList.size(); w++) { series.appendData(new GraphView.GraphViewData(w, Haversine.normalizeAltitudeByLocale(elevationList.get(w), locale)), false, elevationList.size()); } return series; } @Override public void animateHideChart() { AnimatorUtil.replaceViews(rlElevationChart, fabShowChart); } @Override public void animateShowChart() { AnimatorUtil.replaceViews(fabShowChart, rlElevationChart); } @Override public boolean isMinimiseButtonShown() { return fabShowChart.isShown(); } @OnClick(R.id.main_activity_showchart_floatingactionbutton) void onShowChartClick() { elevationPresenter.onOpenChart(); } @OnClick(R.id.main_activity_mylocation_floatingactionbutton) void onMyLocationClick() { if (currentLocation != null) { googleMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()))); } } private enum DistanceMode { DISTANCE_FROM_CURRENT_POINT, DISTANCE_FROM_ANY_POINT } private class SearchPositionByName extends AsyncTask<Object, Void, Integer> { private final String TAG = SearchPositionByName.class.getSimpleName(); protected List<Address> addressList; protected StringBuilder fullAddress; protected LatLng selectedPosition; protected ProgressDialog progressDialog; @Override protected void onPreExecute() { DFMLogger.logMessage(TAG, "onPreExecute"); addressList = null; fullAddress = new StringBuilder(); selectedPosition = null; // Comprobamos que haya conexión con internet (WiFi o Datos) if (!isOnline(appContext)) { showConnectionProblemsDialog(); // Restauramos el menú y que vuelva a empezar de nuevo MenuItemCompat.collapseActionView(searchMenuItem); cancel(false); } else { progressDialog = new ProgressDialog(MainActivity.this); progressDialog.setTitle(R.string.progressdialog_search_position_title); progressDialog.setMessage(getString(R.string.progressdialog_search_position_message)); progressDialog.setCancelable(false); progressDialog.setIndeterminate(true); progressDialog.show(); } } @Override protected Integer doInBackground(Object... params) { DFMLogger.logMessage(TAG, "doInBackground"); /* get latitude and longitude from the addressList */ final Geocoder geoCoder = new Geocoder(appContext, Locale.getDefault()); try { addressList = geoCoder.getFromLocationName((String) params[0], 5); } catch (IOException e) { e.printStackTrace(); DFMLogger.logException(e); return -1; // Network is unavailable or any other I/O problem occurs } if (addressList == null) { return -3; // No backend service available } else if (addressList.isEmpty()) { return -2; // No matches were found } else { return 0; } } @Override protected void onPostExecute(Integer result) { DFMLogger.logMessage(TAG, "onPostExecute result=" + result); switch (result) { case 0: if (addressList != null && !addressList.isEmpty()) { // Si hay varios, elegimos uno. Si solo hay uno, mostramos ese if (addressList.size() == 1) { processSelectedAddress(0); handleSelectedAddress(); } else { final AddressSuggestionsDialogFragment addressSuggestionsDialogFragment = new AddressSuggestionsDialogFragment(); addressSuggestionsDialogFragment.setAddressList(addressList); addressSuggestionsDialogFragment.setOnDialogActionListener(new AddressSuggestionsDialogFragment.OnDialogActionListener() { @Override public void onItemClick(int position) { processSelectedAddress(position); handleSelectedAddress(); } }); addressSuggestionsDialogFragment.show(getSupportFragmentManager(), null); } } break; case -1: toastIt(getString(R.string.toast_no_find_address), appContext); break; case -2: toastIt(getString(R.string.toast_no_results), appContext); break; case -3: toastIt(getString(R.string.toast_no_find_address), appContext); break; } progressDialog.dismiss(); if (searchMenuItem != null) { MenuItemCompat.collapseActionView(searchMenuItem); } } private void handleSelectedAddress() { DFMLogger.logMessage(TAG, "handleSelectedAddress" + getSelectedDistanceMode()); if (getSelectedDistanceMode() == DistanceMode.DISTANCE_FROM_ANY_POINT) { coordinates.add(selectedPosition); if (coordinates.isEmpty()) { DFMLogger.logMessage(TAG, "handleSelectedAddress empty coordinates list"); // add marker final Marker marker = addMarker(selectedPosition); marker.setTitle(fullAddress.toString()); marker.showInfoWindow(); // moveCamera moveCameraZoom(selectedPosition, selectedPosition, false); distanceMeasuredAsText = calculateDistance(Lists.newArrayList(selectedPosition, selectedPosition)); // That means we are looking for a first position, so we want to calculate a distance starting // from here calculatingDistance = true; } else { drawAndShowMultipleDistances(coordinates, fullAddress.toString(), false, true); } } else { if (!appHasJustStarted) { DFMLogger.logMessage(TAG, "handleSelectedAddress appHasJustStarted"); if (coordinates.isEmpty()) { DFMLogger.logMessage(TAG, "handleSelectedAddress empty coordinates list"); coordinates.add(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude())); } coordinates.add(selectedPosition); drawAndShowMultipleDistances(coordinates, fullAddress.toString(), false, true); } else { DFMLogger.logMessage(TAG, "handleSelectedAddress NOT appHasJustStarted"); // Coming from View Action Intent sendDestinationPosition = selectedPosition; } } } protected void processSelectedAddress(final int item) { DFMLogger.logMessage(TAG, "processSelectedAddress item=" + item); // Fill address info to show in the marker info window final Address address = addressList.get(item); for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) { fullAddress.append(address.getAddressLine(i)).append("\n"); } selectedPosition = new LatLng(address.getLatitude(), address.getLongitude()); } } private class SearchPositionByCoordinates extends SearchPositionByName { private final String TAG = SearchPositionByCoordinates.class.getSimpleName(); @Override protected Integer doInBackground(Object... params) { DFMLogger.logMessage(TAG, "doInBackground"); /* get latitude and longitude from the addressList */ final Geocoder geoCoder = new Geocoder(appContext, Locale.getDefault()); final LatLng latLng = (LatLng) params[0]; try { addressList = geoCoder.getFromLocation(latLng.latitude, latLng.longitude, 1); } catch (final IOException e) { e.printStackTrace(); DFMLogger.logException(e); return -1; // No encuentra una dirección, no puede conectar con el servidor } catch (final IllegalArgumentException e) { final IllegalArgumentException illegalArgumentException = new IllegalArgumentException(String.format(Locale.getDefault(), "Error en latitud=%f o longitud=%f.\n%s", latLng.latitude, latLng.longitude, e.toString())); DFMLogger.logException(illegalArgumentException); throw illegalArgumentException; } if (addressList == null) { return -3; // empty list if there is no backend service available } else if (addressList.size() > 0) { return 0; } else { return -2; // null if no matches were found // Cuando no hay conexión que sirva } } @Override protected void onPostExecute(Integer result) { DFMLogger.logMessage(TAG, "onPostExecute result=" + result); switch (result) { case 0: processSelectedAddress(0); drawAndShowMultipleDistances(Lists.newArrayList(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()), selectedPosition), fullAddress.toString(), false, true); break; case -1: toastIt(getString(R.string.toast_no_find_address), appContext); break; case -2: toastIt(getString(R.string.toast_no_results), appContext); break; case -3: toastIt(getString(R.string.toast_no_find_address), appContext); break; } progressDialog.dismiss(); } } private Locale getAmericanOrEuropeanLocale() { final String defaultUnit = DFMPreferences.getMeasureUnitPreference(getBaseContext()); return DFMPreferences.MEASURE_AMERICAN_UNIT_VALUE.equals(defaultUnit) ? Locale.US : Locale.FRANCE; } }
app/src/main/java/gc/david/dfm/ui/MainActivity.java
package gc.david.dfm.ui; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.app.SearchManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.IntentSender; import android.content.res.Configuration; import android.graphics.Color; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.v4.content.ContextCompat; import android.support.v4.view.GravityCompat; import android.support.v4.view.MenuItemCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener; import com.google.android.gms.maps.GoogleMap.OnMapClickListener; import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.UiSettings; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.PolylineOptions; import com.google.common.collect.Lists; import com.inmobi.ads.InMobiAdRequestStatus; import com.inmobi.ads.InMobiBanner; import com.inmobi.ads.InMobiBanner.BannerAdListener; import com.inmobi.sdk.InMobiSdk; import com.jjoe64.graphview.GraphView; import com.jjoe64.graphview.GraphViewSeries; import com.jjoe64.graphview.GraphViewSeries.GraphViewSeriesStyle; import com.jjoe64.graphview.LineGraphView; import java.io.IOException; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.inject.Inject; import butterknife.BindView; import butterknife.OnClick; import dagger.Lazy; import gc.david.dfm.BuildConfig; import gc.david.dfm.DFMApplication; import gc.david.dfm.DFMPreferences; import gc.david.dfm.DeviceInfo; import gc.david.dfm.PackageManager; import gc.david.dfm.R; import gc.david.dfm.Utils; import gc.david.dfm.adapter.MarkerInfoWindowAdapter; import gc.david.dfm.dagger.DaggerMainComponent; import gc.david.dfm.dagger.MainModule; import gc.david.dfm.dagger.RootModule; import gc.david.dfm.dialog.AddressSuggestionsDialogFragment; import gc.david.dfm.dialog.DistanceSelectionDialogFragment; import gc.david.dfm.elevation.Elevation; import gc.david.dfm.elevation.ElevationPresenter; import gc.david.dfm.elevation.ElevationUseCase; import gc.david.dfm.feedback.Feedback; import gc.david.dfm.feedback.FeedbackPresenter; import gc.david.dfm.logger.DFMLogger; import gc.david.dfm.map.Haversine; import gc.david.dfm.map.LocationUtils; import gc.david.dfm.model.DaoSession; import gc.david.dfm.model.Distance; import gc.david.dfm.model.Position; import gc.david.dfm.service.GeofencingService; import static butterknife.ButterKnife.bind; import static gc.david.dfm.Utils.isOnline; import static gc.david.dfm.Utils.showAlertDialog; import static gc.david.dfm.Utils.toastIt; public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, OnMapReadyCallback, OnMapLongClickListener, OnMapClickListener, OnInfoWindowClickListener, Elevation.View { private static final String TAG = MainActivity.class.getSimpleName(); @BindView(R.id.elevationchart) protected RelativeLayout rlElevationChart; @BindView(R.id.closeChart) protected ImageView ivCloseElevationChart; @BindView(R.id.tbMain) protected Toolbar tbMain; @BindView(R.id.banner) protected InMobiBanner banner; @BindView(R.id.drawer_layout) protected DrawerLayout drawerLayout; @BindView(R.id.nvDrawer) protected NavigationView nvDrawer; @BindView(R.id.main_activity_showchart_floatingactionbutton) protected FloatingActionButton fabShowChart; @BindView(R.id.main_activity_mylocation_floatingactionbutton) protected FloatingActionButton fabMyLocation; @Inject protected DaoSession daoSession; @Inject protected Context appContext; @Inject protected Lazy<PackageManager> packageManager; @Inject protected Lazy<DeviceInfo> deviceInfo; @Inject protected ElevationUseCase elevationUseCase; private final BroadcastReceiver locationReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final double latitude = intent.getDoubleExtra(GeofencingService.GEOFENCE_RECEIVER_LATITUDE_KEY, 0D); final double longitude = intent.getDoubleExtra(GeofencingService.GEOFENCE_RECEIVER_LONGITUDE_KEY, 0D); final Location location = new Location(""); location.setLatitude(latitude); location.setLongitude(longitude); onLocationChanged(location); } }; private GoogleMap googleMap = null; private Location currentLocation = null; // Moves to current position if app has just started private boolean appHasJustStarted = true; private String distanceMeasuredAsText = ""; private MenuItem searchMenuItem = null; // Show position if we come from other app (p.e. Whatsapp) private boolean mustShowPositionWhenComingFromOutside = false; private LatLng sendDestinationPosition = null; private boolean bannerShown = false; private GraphView graphView = null; private List<LatLng> coordinates = Lists.newArrayList(); private float DEVICE_DENSITY; // TODO: 09.01.17 get rid of this field private ActionBarDrawerToggle actionBarDrawerToggle; private boolean calculatingDistance; private Elevation.Presenter elevationPresenter; @Override protected void onCreate(Bundle savedInstanceState) { DFMLogger.logMessage(TAG, "onCreate savedInstanceState=" + Utils.dumpBundleToString(savedInstanceState)); super.onCreate(savedInstanceState); InMobiSdk.setLogLevel(BuildConfig.DEBUG ? InMobiSdk.LogLevel.DEBUG : InMobiSdk.LogLevel.NONE); InMobiSdk.init(this, getString(R.string.inmobi_api_key)); setContentView(R.layout.activity_main); DaggerMainComponent.builder() .rootModule(new RootModule((DFMApplication) getApplication())) .mainModule(new MainModule()) .build() .inject(this); bind(this); setSupportActionBar(tbMain); final ActionBar supportActionBar = getSupportActionBar(); if (supportActionBar != null) { supportActionBar.setDisplayHomeAsUpEnabled(true); supportActionBar.setHomeButtonEnabled(true); } elevationPresenter = new ElevationPresenter(this, elevationUseCase); DEVICE_DENSITY = getResources().getDisplayMetrics().density; final SupportMapFragment supportMapFragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)); supportMapFragment.getMapAsync(this); banner.setListener(new BannerAdListener() { @Override public void onAdLoadSucceeded(InMobiBanner inMobiBanner) { DFMLogger.logMessage(TAG, "onAdLoadSucceeded"); banner.setVisibility(View.VISIBLE); bannerShown = true; // TODO: 06.01.17 remove this field then... fixMapPadding(); } @Override public void onAdLoadFailed(InMobiBanner inMobiBanner, InMobiAdRequestStatus inMobiAdRequestStatus) { DFMLogger.logMessage(TAG, String.format("onAdLoadFailed %s %s", inMobiAdRequestStatus.getStatusCode(), inMobiAdRequestStatus.getMessage())); } @Override public void onAdDisplayed(InMobiBanner inMobiBanner) { DFMLogger.logMessage(TAG, "onAdDisplayed"); } @Override public void onAdDismissed(InMobiBanner inMobiBanner) { DFMLogger.logMessage(TAG, "onAdDismissed"); } @Override public void onAdInteraction(InMobiBanner inMobiBanner, Map<Object, Object> map) { DFMLogger.logMessage(TAG, String.format("onAdInteraction %s", map.toString())); DFMLogger.logEvent("Ad tapped"); } @Override public void onUserLeftApplication(InMobiBanner inMobiBanner) { DFMLogger.logMessage(TAG, "onUserLeftApplication"); } @Override public void onAdRewardActionCompleted(InMobiBanner inMobiBanner, Map<Object, Object> map) { DFMLogger.logMessage(TAG, String.format("onAdRewardActionCompleted %s", map.toString())); } }); if (!BuildConfig.DEBUG) { banner.load(); } if (!isOnline(appContext)) { showConnectionProblemsDialog(); } // Iniciando la app if (currentLocation == null) { toastIt(getString(R.string.toast_loading_position), appContext); } handleIntents(getIntent()); nvDrawer.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.menu_current_position: menuItem.setChecked(true); drawerLayout.closeDrawers(); onStartingPointSelected(); return true; case R.id.menu_any_position: menuItem.setChecked(true); drawerLayout.closeDrawers(); onStartingPointSelected(); return true; case R.id.menu_rate_app: drawerLayout.closeDrawers(); showRateDialog(); return true; case R.id.menu_legal_notices: drawerLayout.closeDrawers(); showGooglePlayServiceLicenseDialog(); return true; case R.id.menu_settings: drawerLayout.closeDrawers(); openSettingsActivity(); return true; case R.id.menu_help_feedback: drawerLayout.closeDrawers(); startActivity(new Intent(MainActivity.this, HelpAndFeedbackActivity.class)); return true; } return false; } }); // TODO: 23.08.15 check if this is still needed actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.progressdialog_search_position_message, R.string.progressdialog_search_position_message) { @Override public void onDrawerOpened(View drawerView) { DFMLogger.logMessage(TAG, "onDrawerOpened"); super.onDrawerOpened(drawerView); supportInvalidateOptionsMenu(); } @Override public void onDrawerClosed(View drawerView) { DFMLogger.logMessage(TAG, "onDrawerClosed"); super.onDrawerClosed(drawerView); supportInvalidateOptionsMenu(); } }; drawerLayout.addDrawerListener(actionBarDrawerToggle); } @Override public void onMapReady(final GoogleMap map) { googleMap = map; googleMap.getUiSettings().setMyLocationButtonEnabled(false); googleMap.setMyLocationEnabled(true); googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); googleMap.setOnMapLongClickListener(this); googleMap.setOnMapClickListener(this); googleMap.setOnInfoWindowClickListener(this); googleMap.setInfoWindowAdapter(new MarkerInfoWindowAdapter(this)); onStartingPointSelected(); } @Override public void onMapLongClick(LatLng point) { DFMLogger.logMessage(TAG, "onMapLongClick"); calculatingDistance = true; if (getSelectedDistanceMode() == DistanceMode.DISTANCE_FROM_ANY_POINT) { if (coordinates.isEmpty()) { toastIt(getString(R.string.toast_first_point_needed), appContext); } else { coordinates.add(point); drawAndShowMultipleDistances(coordinates, "", false, true); } } else if (currentLocation != null) { // Without current location, we cannot calculate any distance if (getSelectedDistanceMode() == DistanceMode.DISTANCE_FROM_CURRENT_POINT && coordinates.isEmpty()) { coordinates.add(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude())); } coordinates.add(point); drawAndShowMultipleDistances(coordinates, "", false, true); } calculatingDistance = false; } @Override public void onMapClick(LatLng point) { DFMLogger.logMessage(TAG, "onMapClick"); if (getSelectedDistanceMode() == DistanceMode.DISTANCE_FROM_ANY_POINT) { if (!calculatingDistance) { coordinates.clear(); } calculatingDistance = true; if (coordinates.isEmpty()) { googleMap.clear(); } coordinates.add(point); googleMap.addMarker(new MarkerOptions().position(point)); } else { // Without current location, we cannot calculate any distance if (currentLocation != null) { if (!calculatingDistance) { coordinates.clear(); } calculatingDistance = true; if (coordinates.isEmpty()) { googleMap.clear(); coordinates.add(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude())); } coordinates.add(point); googleMap.addMarker(new MarkerOptions().position(point)); } } } @Override public void onInfoWindowClick(Marker marker) { DFMLogger.logMessage(TAG, "onInfoWindowClick"); ShowInfoActivity.open(this, coordinates, distanceMeasuredAsText); } private void onStartingPointSelected() { if (getSelectedDistanceMode() == DistanceMode.DISTANCE_FROM_CURRENT_POINT) { DFMLogger.logMessage(TAG, "onStartingPointSelected Distance from current point"); } else{ DFMLogger.logMessage(TAG, "onStartingPointSelected Distance from any point"); } calculatingDistance = false; coordinates.clear(); googleMap.clear(); elevationPresenter.onReset(); } private DistanceMode getSelectedDistanceMode() { return nvDrawer.getMenu().findItem(R.id.menu_current_position).isChecked() ? DistanceMode.DISTANCE_FROM_CURRENT_POINT : DistanceMode.DISTANCE_FROM_ANY_POINT; } @Override protected void onPostCreate(Bundle savedInstanceState) { DFMLogger.logMessage(TAG, "onPostCreate savedInstanceState=" + Utils.dumpBundleToString(savedInstanceState)); super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. if (actionBarDrawerToggle != null) { actionBarDrawerToggle.syncState(); } else { DFMLogger.logMessage(TAG, "onPostCreate actionBarDrawerToggle null"); } } @Override public void onConfigurationChanged(Configuration newConfig) { DFMLogger.logMessage(TAG, "onConfigurationChanged"); super.onConfigurationChanged(newConfig); if (actionBarDrawerToggle != null) { actionBarDrawerToggle.onConfigurationChanged(newConfig); } else { DFMLogger.logMessage(TAG, "onConfigurationChanged actionBarDrawerToggle null"); } } @Override protected void onNewIntent(Intent intent) { DFMLogger.logMessage(TAG, "onNewIntent " + Utils.dumpIntentToString(intent)); setIntent(intent); handleIntents(intent); } /** * Handles all Intent types. * * @param intent The input intent. */ private void handleIntents(final Intent intent) { DFMLogger.logMessage(TAG, "handleIntents " + Utils.dumpIntentToString(intent)); if (intent != null) { if (Intent.ACTION_SEARCH.equals(intent.getAction())) { handleSearchIntent(intent); } else if (Intent.ACTION_VIEW.equals(intent.getAction())) { handleViewPositionIntent(intent); } } } /** * Handles a search intent. * * @param intent Input intent. */ private void handleSearchIntent(final Intent intent) { DFMLogger.logMessage(TAG, "handleSearchIntent"); // Para controlar instancias únicas, no queremos que cada vez que // busquemos nos inicie una nueva instancia de la aplicación final String query = intent.getStringExtra(SearchManager.QUERY); if (currentLocation != null) { new SearchPositionByName().execute(query); } if (searchMenuItem != null) { MenuItemCompat.collapseActionView(searchMenuItem); } } /** * Handles a send intent with position data. * * @param intent Input intent with position data. */ private void handleViewPositionIntent(final Intent intent) { DFMLogger.logMessage(TAG, "handleViewPositionIntent"); final Uri uri = intent.getData(); DFMLogger.logMessage(TAG, "handleViewPositionIntent uri=" + uri.toString()); final String uriScheme = uri.getScheme(); if (uriScheme.equals("geo")) { handleGeoSchemeIntent(uri); } else if ((uriScheme.equals("http") || uriScheme.equals("https")) && (uri.getHost().equals("maps.google.com"))) { // Manage maps.google.com?q=latitude,longitude handleMapsHostIntent(uri); } else { final Exception exception = new Exception("Imposible tratar la query " + uri.toString()); DFMLogger.logException(exception); toastIt("Unable to parse address", this); } } private void handleGeoSchemeIntent(final Uri uri) { final String schemeSpecificPart = uri.getSchemeSpecificPart(); final Matcher matcher = getMatcherForUri(schemeSpecificPart); if (matcher.find()) { if (matcher.group(1).equals("0") && matcher.group(2).equals("0")) { if (matcher.find()) { // Manage geo:0,0?q=lat,lng(label) setDestinationPosition(matcher); } else { // Manage geo:0,0?q=my+street+address String destination = Uri.decode(uri.getQuery()).replace('+', ' '); destination = destination.replace("q=", ""); // TODO check this ugly workaround new SearchPositionByName().execute(destination); mustShowPositionWhenComingFromOutside = true; } } else { // Manage geo:latitude,longitude or geo:latitude,longitude?z=zoom setDestinationPosition(matcher); } } else { final NoSuchFieldException noSuchFieldException = new NoSuchFieldException("Error al obtener las coordenadas. Matcher = " + matcher.toString()); DFMLogger.logException(noSuchFieldException); toastIt("Unable to parse address", this); } } private void handleMapsHostIntent(final Uri uri) { final String queryParameter = uri.getQueryParameter("q"); if (queryParameter != null) { final Matcher matcher = getMatcherForUri(queryParameter); if (matcher.find()) { setDestinationPosition(matcher); } else { final NoSuchFieldException noSuchFieldException = new NoSuchFieldException("Error al obtener las coordenadas. Matcher = " + matcher.toString()); DFMLogger.logException(noSuchFieldException); toastIt("Unable to parse address", this); } } else { final NoSuchFieldException noSuchFieldException = new NoSuchFieldException("Query sin parámetro q."); DFMLogger.logException(noSuchFieldException); toastIt("Unable to parse address", this); } } private void setDestinationPosition(final Matcher matcher) { DFMLogger.logMessage(TAG, "setDestinationPosition"); sendDestinationPosition = new LatLng(Double.valueOf(matcher.group(1)), Double.valueOf(matcher.group(2))); mustShowPositionWhenComingFromOutside = true; } private Matcher getMatcherForUri(final String schemeSpecificPart) { DFMLogger.logMessage(TAG, "getMatcherForUri scheme=" + schemeSpecificPart); // http://regex101.com/ // http://www.regexplanet.com/advanced/java/index.html final String regex = "(\\-?\\d+\\.*\\d*),(\\-?\\d+\\.*\\d*)"; final Pattern pattern = Pattern.compile(regex); return pattern.matcher(schemeSpecificPart); } private void showConnectionProblemsDialog() { DFMLogger.logMessage(TAG, "showConnectionProblemsDialog"); showAlertDialog(android.provider.Settings.ACTION_SETTINGS, getString(R.string.dialog_connection_problems_title), getString(R.string.dialog_connection_problems_message), getString(R.string.dialog_connection_problems_positive_button), getString(R.string.dialog_connection_problems_negative_button), MainActivity.this); } @Override public boolean onCreateOptionsMenu(Menu menu) { DFMLogger.logMessage(TAG, "onCreateOptionsMenu"); // Inflate the options menu from XML final MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); // Expandir el EditText de la búsqueda a lo largo del ActionBar searchMenuItem = menu.findItem(R.id.action_search); final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchMenuItem); // Configure the search info and add any event listeners final SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); // Indicamos que la activity actual sea la buscadora searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setSubmitButtonEnabled(false); searchView.setQueryRefinementEnabled(true); searchView.setIconifiedByDefault(true); // Muestra el item de menú de cargar si hay elementos en la BD // TODO hacerlo en segundo plano final List<Distance> allDistances = daoSession.loadAll(Distance.class); if (allDistances.isEmpty()) { final MenuItem loadItem = menu.findItem(R.id.action_load); loadItem.setVisible(false); } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { DFMLogger.logMessage(TAG, "onOptionsItemSelected item=" + item.getItemId()); // The action bar home/up action should open or close the drawer. // ActionBarDrawerToggle will take care of this. if (actionBarDrawerToggle != null && actionBarDrawerToggle.onOptionsItemSelected(item)) { DFMLogger.logMessage(TAG, "onOptionsItemSelected ActionBar home button click"); return true; } switch (item.getItemId()) { case R.id.action_search: return true; case R.id.action_load: loadDistancesFromDB(); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onBackPressed() { DFMLogger.logMessage(TAG, "onBackPressed"); if (drawerLayout != null && drawerLayout.isDrawerOpen(GravityCompat.START)) { drawerLayout.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } /** * Loads all entries stored in the database and show them to the user in a * dialog. */ private void loadDistancesFromDB() { DFMLogger.logMessage(TAG, "loadDistancesFromDB"); // TODO hacer esto en segundo plano final List<Distance> allDistances = daoSession.loadAll(Distance.class); if (allDistances != null && !allDistances.isEmpty()) { final DistanceSelectionDialogFragment distanceSelectionDialogFragment = new DistanceSelectionDialogFragment(); distanceSelectionDialogFragment.setDistanceList(allDistances); distanceSelectionDialogFragment.setOnDialogActionListener(new DistanceSelectionDialogFragment.OnDialogActionListener() { @Override public void onItemClick(int position) { final Distance distance = allDistances.get(position); final List<Position> positionList = daoSession.getPositionDao() ._queryDistance_PositionList(distance.getId()); coordinates.clear(); coordinates.addAll(Utils.convertPositionListToLatLngList(positionList)); drawAndShowMultipleDistances(coordinates, distance.getName() + "\n", true, true); } }); distanceSelectionDialogFragment.show(getSupportFragmentManager(), null); } } /** * Shows settings activity. */ private void openSettingsActivity() { DFMLogger.logMessage(TAG, "openSettingsActivity"); startActivity(new Intent(MainActivity.this, SettingsActivity.class)); } /** * Shows rate dialog. */ private void showRateDialog() { DFMLogger.logMessage(TAG, "showRateDialog"); final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.dialog_rate_app_title) .setMessage(R.string.dialog_rate_app_message) .setPositiveButton(getString(R.string.dialog_rate_app_positive_button), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); openPlayStoreAppPage(); } }) .setNegativeButton(getString(R.string.dialog_rate_app_negative_button), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); openFeedbackActivity(); } }).create().show(); } /** * Opens Google Play Store, in Distance From Me page */ private void openPlayStoreAppPage() { DFMLogger.logMessage(TAG, "openPlayStoreAppPage"); startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=gc.david.dfm"))); } /** * Opens the feedback activity. */ private void openFeedbackActivity() { DFMLogger.logMessage(TAG, "openFeedbackActivity"); new FeedbackPresenter(new Feedback.View() { @Override public void showError() { toastIt(getString(R.string.toast_send_feedback_error), appContext); } @Override public void showEmailClient(final Intent intent) { startActivity(intent); } @Override public Context context() { return appContext; } }, packageManager.get(), deviceInfo.get()).start(); } /** * Shows an AlertDialog with the Google Play Services License. */ private void showGooglePlayServiceLicenseDialog() { DFMLogger.logMessage(TAG, "showGooglePlayServiceLicenseDialog"); final String LicenseInfo = GoogleApiAvailability.getInstance().getOpenSourceSoftwareLicenseInfo(appContext); final AlertDialog.Builder LicenseDialog = new AlertDialog.Builder(MainActivity.this); LicenseDialog.setTitle(R.string.menu_legal_notices_title); LicenseDialog.setMessage(LicenseInfo); LicenseDialog.show(); } /** * Called when the Activity is no longer visible at all. Stop updates and * disconnect. */ @Override public void onStop() { DFMLogger.logMessage(TAG, "onStop"); super.onStop(); unregisterReceiver(locationReceiver); stopService(new Intent(this, GeofencingService.class)); } /** * Called when the Activity is restarted, even before it becomes visible. */ @Override public void onStart() { DFMLogger.logMessage(TAG, "onStart"); super.onStart(); registerReceiver(locationReceiver, new IntentFilter(GeofencingService.GEOFENCE_RECEIVER_ACTION)); startService(new Intent(this, GeofencingService.class)); } /** * Called when the system detects that this Activity is now visible. */ @SuppressLint("NewApi") // TODO: 09.01.17 remove @Override public void onResume() { DFMLogger.logMessage(TAG, "onResume"); super.onResume(); invalidateOptionsMenu(); checkPlayServices(); } @Override public void onDestroy() { DFMLogger.logMessage(TAG, "onDestroy"); elevationPresenter.onReset(); super.onDestroy(); } /** * Handle results returned to this Activity by other Activities started with * startActivityForResult(). In particular, the method onConnectionFailed() * in LocationUpdateRemover and LocationUpdateRequester may call * startResolutionForResult() to start an Activity that handles Google Play * services problems. The result of this call returns here, to * onActivityResult. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { DFMLogger.logMessage(TAG, "onActivityResult requestCode=" + requestCode + ", " + "resultCode=" + resultCode + "intent=" + Utils.dumpIntentToString(intent)); // Choose what to do based on the request code switch (requestCode) { // If the request code matches the code sent in onConnectionFailed case LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST: switch (resultCode) { // If Google Play services resolved the problem case Activity.RESULT_OK: // Log the result // Log.d(LocationUtils.APPTAG, getString(R.string.resolved)); // Display the result // mConnectionState.setText(R.string.connected); // mConnectionStatus.setText(R.string.resolved); break; // If any other result was returned by Google Play services default: // Log the result // Log.d(LocationUtils.APPTAG, // getString(R.string.no_resolution)); // Display the result // mConnectionState.setText(R.string.disconnected); // mConnectionStatus.setText(R.string.no_resolution); break; } // If any other request code was received default: // Report that this Activity received an unknown requestCode // Log.d(LocationUtils.APPTAG, // getString(R.string.unknown_activity_request_code, requestCode)); break; } } /** * Checks if Google Play Services is available on the device. * * @return Returns <code>true</code> if available; <code>false</code> * otherwise. */ private boolean checkPlayServices() { DFMLogger.logMessage(TAG, "checkPlayServices"); final GoogleApiAvailability googleApiAvailabilityInstance = GoogleApiAvailability.getInstance(); // Comprobamos que Google Play Services está disponible en el terminal final int resultCode = googleApiAvailabilityInstance.isGooglePlayServicesAvailable(appContext); // Si está disponible, devolvemos verdadero. Si no, mostramos un mensaje // de error y devolvemos falso if (resultCode == ConnectionResult.SUCCESS) { DFMLogger.logMessage(TAG, "checkPlayServices success"); return true; } else { if (googleApiAvailabilityInstance.isUserResolvableError(resultCode)) { DFMLogger.logMessage(TAG, "checkPlayServices isUserRecoverableError"); final int RQS_GooglePlayServices = 1; googleApiAvailabilityInstance.getErrorDialog(this, resultCode, RQS_GooglePlayServices).show(); } else { DFMLogger.logMessage(TAG, "checkPlayServices device not supported, finishing"); finish(); } return false; } } /** * Called by Location Services if the attempt to Location Services fails. */ @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { DFMLogger.logMessage(TAG, "onConnectionFailed"); /* * Google Play services can resolve some errors it detects. If the error * has a resolution, try sending an Intent to start a Google Play * services activity that can resolve error. */ if (connectionResult.hasResolution()) { DFMLogger.logMessage(TAG, "onConnectionFailed connection has resolution"); try { // Start an Activity that tries to resolve the error connectionResult.startResolutionForResult(this, LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST); /* * Thrown if Google Play services cancelled the original * PendingIntent */ } catch (IntentSender.SendIntentException e) { // Log the error e.printStackTrace(); DFMLogger.logException(e); } } else { DFMLogger.logMessage(TAG, "onConnectionFailed connection does not have resolution"); // If no resolution is available, display a dialog to the user with // the error. showErrorDialog(connectionResult.getErrorCode()); } } public void onLocationChanged(final Location location) { DFMLogger.logMessage(TAG, "onLocationChanged"); if (currentLocation != null) { currentLocation.set(location); } else { currentLocation = new Location(location); } if (appHasJustStarted) { DFMLogger.logMessage(TAG, "onLocationChanged appHasJustStarted"); if (mustShowPositionWhenComingFromOutside) { DFMLogger.logMessage(TAG, "onLocationChanged mustShowPositionWhenComingFromOutside"); if (currentLocation != null && sendDestinationPosition != null) { new SearchPositionByCoordinates().execute(sendDestinationPosition); mustShowPositionWhenComingFromOutside = false; } } else { DFMLogger.logMessage(TAG, "onLocationChanged NOT mustShowPositionWhenComingFromOutside"); final LatLng latlng = new LatLng(location.getLatitude(), location.getLongitude()); // 17 is a good zoom level for this action googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latlng, 17)); } appHasJustStarted = false; } } /** * Shows a dialog returned by Google Play services for the connection error * code * * @param errorCode An error code returned from onConnectionFailed */ private void showErrorDialog(final int errorCode) { DFMLogger.logMessage(TAG, "showErrorDialog errorCode=" + errorCode); // Get the error dialog from Google Play services final Dialog errorDialog = GoogleApiAvailability.getInstance().getErrorDialog(this, errorCode, LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST); // If Google Play services can provide an error dialog if (errorDialog != null) { // Create a new DialogFragment in which to show the error dialog final ErrorDialogFragment errorFragment = new ErrorDialogFragment(); // Set the dialog in the DialogFragment errorFragment.setDialog(errorDialog); // Show the error dialog in the DialogFragment errorFragment.show(getSupportFragmentManager(), "Geofence detection"); } } private void drawAndShowMultipleDistances(final List<LatLng> coordinates, final String message, final boolean isLoadingFromDB, final boolean mustApplyZoomIfNeeded) { DFMLogger.logMessage(TAG, "drawAndShowMultipleDistances"); // Borramos los antiguos marcadores y lineas googleMap.clear(); // Calculamos la distancia distanceMeasuredAsText = calculateDistance(coordinates); // Pintar todos menos el primero si es desde la posición actual addMarkers(coordinates, distanceMeasuredAsText, message, isLoadingFromDB); // Añadimos las líneas addLines(coordinates, isLoadingFromDB); // Aquí hacer la animación de la cámara moveCameraZoom(coordinates.get(0), coordinates.get(coordinates.size() - 1), mustApplyZoomIfNeeded); // Muestra el perfil de elevación si está en las preferencias // y si está conectado a internet // TODO: 06.01.17 move this decision to ElevationPresenter if (DFMPreferences.shouldShowElevationChart(appContext) && isOnline(appContext)) { elevationPresenter.buildChart(coordinates); } } /** * Adds a marker to the map in a specified position and shows its info * window. * * @param coordinates Positions list. * @param distance Distance to destination. * @param message Destination address (if needed). * @param isLoadingFromDB Indicates whether we are loading data from database. */ private void addMarkers(final List<LatLng> coordinates, final String distance, final String message, final boolean isLoadingFromDB) { DFMLogger.logMessage(TAG, "addMarkers"); for (int i = 0; i < coordinates.size(); i++) { if ((i == 0 && (isLoadingFromDB || getSelectedDistanceMode() == DistanceMode.DISTANCE_FROM_ANY_POINT)) || (i == coordinates.size() - 1)) { final LatLng coordinate = coordinates.get(i); final Marker marker = addMarker(coordinate); if (i == coordinates.size() - 1) { marker.setTitle(message + distance); marker.showInfoWindow(); } } } } private Marker addMarker(final LatLng coordinate) { DFMLogger.logMessage(TAG, "addMarker"); return googleMap.addMarker(new MarkerOptions().position(coordinate)); } private void addLines(final List<LatLng> coordinates, final boolean isLoadingFromDB) { DFMLogger.logMessage(TAG, "addLines"); for (int i = 0; i < coordinates.size() - 1; i++) { addLine(coordinates.get(i), coordinates.get(i + 1), isLoadingFromDB); } } /** * Adds a line between start and end positions. * * @param start Start position. * @param end Destination position. */ private void addLine(final LatLng start, final LatLng end, final boolean isLoadingFromDB) { DFMLogger.logMessage(TAG, "addLine"); final PolylineOptions lineOptions = new PolylineOptions().add(start).add(end); lineOptions.width(3 * getResources().getDisplayMetrics().density); lineOptions.color(isLoadingFromDB ? Color.YELLOW : Color.GREEN); googleMap.addPolyline(lineOptions); } /** * Returns the distance between start and end positions normalized by device * locale. * * @param coordinates position list. * @return The normalized distance. */ private String calculateDistance(final List<LatLng> coordinates) { DFMLogger.logMessage(TAG, "calculateDistance"); double distanceInMetres = Utils.calculateDistanceInMetres(coordinates); return Haversine.normalizeDistance(distanceInMetres, getAmericanOrEuropeanLocale()); } /** * Moves camera position and applies zoom if needed. * * @param p1 Start position. * @param p2 Destination position. */ private void moveCameraZoom(final LatLng p1, final LatLng p2, final boolean mustApplyZoomIfNeeded) { DFMLogger.logMessage(TAG, "moveCameraZoom"); double centerLat = 0.0; double centerLon = 0.0; // Diferenciamos según preferencias final String centre = DFMPreferences.getAnimationPreference(getBaseContext()); if (DFMPreferences.ANIMATION_CENTRE_VALUE.equals(centre)) { centerLat = (p1.latitude + p2.latitude) / 2; centerLon = (p1.longitude + p2.longitude) / 2; } else if (DFMPreferences.ANIMATION_DESTINATION_VALUE.equals(centre)) { centerLat = p2.latitude; centerLon = p2.longitude; } else if (centre.equals(DFMPreferences.NO_ANIMATION_DESTINATION_VALUE)) { return; } if (mustApplyZoomIfNeeded) { googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(centerLat, centerLon), Utils.calculateZoom(p1, p2))); } else { googleMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(p2.latitude, p2.longitude))); } } private void fixMapPadding() { if (bannerShown) { DFMLogger.logMessage(TAG, "fixMapPadding bannerShown"); if (rlElevationChart.isShown()) { DFMLogger.logMessage(TAG, "fixMapPadding elevationChartShown"); googleMap.setPadding(0, rlElevationChart.getHeight(), 0, banner.getLayoutParams().height); } else { DFMLogger.logMessage(TAG, "fixMapPadding NOT elevationChartShown"); googleMap.setPadding(0, 0, 0, banner.getLayoutParams().height); } } else { DFMLogger.logMessage(TAG, "fixMapPadding NOT bannerShown"); if (rlElevationChart.isShown()) { DFMLogger.logMessage(TAG, "fixMapPadding elevationChartShown"); googleMap.setPadding(0, rlElevationChart.getHeight(), 0, 0); } else { DFMLogger.logMessage(TAG, "fixMapPadding NOT elevationChartShown"); googleMap.setPadding(0, 0, 0, 0); } } } @Override public void setPresenter(final Elevation.Presenter presenter) { this.elevationPresenter = presenter; } @Override public void hideChart() { rlElevationChart.setVisibility(View.INVISIBLE); fabShowChart.setVisibility(View.INVISIBLE); fixMapPadding(); } @Override public void showChart() { rlElevationChart.setVisibility(View.VISIBLE); fixMapPadding(); } @Override public void buildChart(final List<Double> elevationList) { final Locale locale = getAmericanOrEuropeanLocale(); // Creates the series and adds data to it final GraphViewSeries series = buildGraphViewSeries(elevationList, locale); if (graphView == null) { graphView = new LineGraphView(appContext, getString(R.string.elevation_chart_title, Haversine.getAltitudeUnitByLocale(locale))); graphView.getGraphViewStyle().setGridColor(Color.TRANSPARENT); graphView.getGraphViewStyle().setNumHorizontalLabels(1); // Not working with zero? graphView.getGraphViewStyle().setTextSize(15 * DEVICE_DENSITY); graphView.getGraphViewStyle().setVerticalLabelsWidth((int) (50 * DEVICE_DENSITY)); rlElevationChart.addView(graphView); ivCloseElevationChart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { elevationPresenter.onCloseChart(); } }); } graphView.removeAllSeries(); graphView.addSeries(series); elevationPresenter.onChartBuilt(); } @NonNull private GraphViewSeries buildGraphViewSeries(final List<Double> elevationList, final Locale locale) { final GraphViewSeriesStyle style = new GraphViewSeriesStyle(ContextCompat.getColor(getApplicationContext(), R.color.elevation_chart_line), (int) (3 * DEVICE_DENSITY)); final GraphViewSeries series = new GraphViewSeries(null, style, new GraphView.GraphViewData[]{}); for (int w = 0; w < elevationList.size(); w++) { series.appendData(new GraphView.GraphViewData(w, Haversine.normalizeAltitudeByLocale(elevationList.get(w), locale)), false, elevationList.size()); } return series; } @Override public void animateHideChart() { AnimatorUtil.replaceViews(rlElevationChart, fabShowChart); } @Override public void animateShowChart() { AnimatorUtil.replaceViews(fabShowChart, rlElevationChart); } @Override public boolean isMinimiseButtonShown() { return fabShowChart.isShown(); } @OnClick(R.id.main_activity_showchart_floatingactionbutton) void onShowChartClick() { elevationPresenter.onOpenChart(); } private enum DistanceMode { DISTANCE_FROM_CURRENT_POINT, DISTANCE_FROM_ANY_POINT } private class SearchPositionByName extends AsyncTask<Object, Void, Integer> { private final String TAG = SearchPositionByName.class.getSimpleName(); protected List<Address> addressList; protected StringBuilder fullAddress; protected LatLng selectedPosition; protected ProgressDialog progressDialog; @Override protected void onPreExecute() { DFMLogger.logMessage(TAG, "onPreExecute"); addressList = null; fullAddress = new StringBuilder(); selectedPosition = null; // Comprobamos que haya conexión con internet (WiFi o Datos) if (!isOnline(appContext)) { showConnectionProblemsDialog(); // Restauramos el menú y que vuelva a empezar de nuevo MenuItemCompat.collapseActionView(searchMenuItem); cancel(false); } else { progressDialog = new ProgressDialog(MainActivity.this); progressDialog.setTitle(R.string.progressdialog_search_position_title); progressDialog.setMessage(getString(R.string.progressdialog_search_position_message)); progressDialog.setCancelable(false); progressDialog.setIndeterminate(true); progressDialog.show(); } } @Override protected Integer doInBackground(Object... params) { DFMLogger.logMessage(TAG, "doInBackground"); /* get latitude and longitude from the addressList */ final Geocoder geoCoder = new Geocoder(appContext, Locale.getDefault()); try { addressList = geoCoder.getFromLocationName((String) params[0], 5); } catch (IOException e) { e.printStackTrace(); DFMLogger.logException(e); return -1; // Network is unavailable or any other I/O problem occurs } if (addressList == null) { return -3; // No backend service available } else if (addressList.isEmpty()) { return -2; // No matches were found } else { return 0; } } @Override protected void onPostExecute(Integer result) { DFMLogger.logMessage(TAG, "onPostExecute result=" + result); switch (result) { case 0: if (addressList != null && !addressList.isEmpty()) { // Si hay varios, elegimos uno. Si solo hay uno, mostramos ese if (addressList.size() == 1) { processSelectedAddress(0); handleSelectedAddress(); } else { final AddressSuggestionsDialogFragment addressSuggestionsDialogFragment = new AddressSuggestionsDialogFragment(); addressSuggestionsDialogFragment.setAddressList(addressList); addressSuggestionsDialogFragment.setOnDialogActionListener(new AddressSuggestionsDialogFragment.OnDialogActionListener() { @Override public void onItemClick(int position) { processSelectedAddress(position); handleSelectedAddress(); } }); addressSuggestionsDialogFragment.show(getSupportFragmentManager(), null); } } break; case -1: toastIt(getString(R.string.toast_no_find_address), appContext); break; case -2: toastIt(getString(R.string.toast_no_results), appContext); break; case -3: toastIt(getString(R.string.toast_no_find_address), appContext); break; } progressDialog.dismiss(); if (searchMenuItem != null) { MenuItemCompat.collapseActionView(searchMenuItem); } } private void handleSelectedAddress() { DFMLogger.logMessage(TAG, "handleSelectedAddress" + getSelectedDistanceMode()); if (getSelectedDistanceMode() == DistanceMode.DISTANCE_FROM_ANY_POINT) { coordinates.add(selectedPosition); if (coordinates.isEmpty()) { DFMLogger.logMessage(TAG, "handleSelectedAddress empty coordinates list"); // add marker final Marker marker = addMarker(selectedPosition); marker.setTitle(fullAddress.toString()); marker.showInfoWindow(); // moveCamera moveCameraZoom(selectedPosition, selectedPosition, false); distanceMeasuredAsText = calculateDistance(Lists.newArrayList(selectedPosition, selectedPosition)); // That means we are looking for a first position, so we want to calculate a distance starting // from here calculatingDistance = true; } else { drawAndShowMultipleDistances(coordinates, fullAddress.toString(), false, true); } } else { if (!appHasJustStarted) { DFMLogger.logMessage(TAG, "handleSelectedAddress appHasJustStarted"); if (coordinates.isEmpty()) { DFMLogger.logMessage(TAG, "handleSelectedAddress empty coordinates list"); coordinates.add(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude())); } coordinates.add(selectedPosition); drawAndShowMultipleDistances(coordinates, fullAddress.toString(), false, true); } else { DFMLogger.logMessage(TAG, "handleSelectedAddress NOT appHasJustStarted"); // Coming from View Action Intent sendDestinationPosition = selectedPosition; } } } protected void processSelectedAddress(final int item) { DFMLogger.logMessage(TAG, "processSelectedAddress item=" + item); // Fill address info to show in the marker info window final Address address = addressList.get(item); for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) { fullAddress.append(address.getAddressLine(i)).append("\n"); } selectedPosition = new LatLng(address.getLatitude(), address.getLongitude()); } } private class SearchPositionByCoordinates extends SearchPositionByName { private final String TAG = SearchPositionByCoordinates.class.getSimpleName(); @Override protected Integer doInBackground(Object... params) { DFMLogger.logMessage(TAG, "doInBackground"); /* get latitude and longitude from the addressList */ final Geocoder geoCoder = new Geocoder(appContext, Locale.getDefault()); final LatLng latLng = (LatLng) params[0]; try { addressList = geoCoder.getFromLocation(latLng.latitude, latLng.longitude, 1); } catch (final IOException e) { e.printStackTrace(); DFMLogger.logException(e); return -1; // No encuentra una dirección, no puede conectar con el servidor } catch (final IllegalArgumentException e) { final IllegalArgumentException illegalArgumentException = new IllegalArgumentException(String.format(Locale.getDefault(), "Error en latitud=%f o longitud=%f.\n%s", latLng.latitude, latLng.longitude, e.toString())); DFMLogger.logException(illegalArgumentException); throw illegalArgumentException; } if (addressList == null) { return -3; // empty list if there is no backend service available } else if (addressList.size() > 0) { return 0; } else { return -2; // null if no matches were found // Cuando no hay conexión que sirva } } @Override protected void onPostExecute(Integer result) { DFMLogger.logMessage(TAG, "onPostExecute result=" + result); switch (result) { case 0: processSelectedAddress(0); drawAndShowMultipleDistances(Lists.newArrayList(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()), selectedPosition), fullAddress.toString(), false, true); break; case -1: toastIt(getString(R.string.toast_no_find_address), appContext); break; case -2: toastIt(getString(R.string.toast_no_results), appContext); break; case -3: toastIt(getString(R.string.toast_no_find_address), appContext); break; } progressDialog.dismiss(); } } private Locale getAmericanOrEuropeanLocale() { final String defaultUnit = DFMPreferences.getMeasureUnitPreference(getBaseContext()); return DFMPreferences.MEASURE_AMERICAN_UNIT_VALUE.equals(defaultUnit) ? Locale.US : Locale.FRANCE; } }
Adding my location button behaviour
app/src/main/java/gc/david/dfm/ui/MainActivity.java
Adding my location button behaviour
Java
apache-2.0
524cad1629edf6d0fe13d30f17ca893bae155568
0
stalehd/cloudname,stalehd/cloudname,stalehd/cloudname
package org.cloudname.flags; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import javax.annotation.PostConstruct; import junit.framework.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.isA; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; /** * Test class for Flags. * * @author acidmoose * */ public class FlagsTest { /** * Test all supported field types. */ @Test public void testSimpleRun() { Flags flags = new Flags() .loadOpts(FlagsAllLegalFields.class) .parse(new String[]{}); assertFalse("Help seems to have been called. It should not have been.", flags.helpFlagged()); assertEquals(false, FlagsAllLegalFields.bool); assertEquals(new Boolean(false), FlagsAllLegalFields.bool2); assertEquals("NA", FlagsAllLegalFields.string); assertEquals(1, FlagsAllLegalFields.getValueForPrivateInteger()); assertEquals(new Integer(1), FlagsAllLegalFields.integer2); assertEquals(1, FlagsAllLegalFields.longNum); assertEquals(1, FlagsAllLegalFields.longNum2); assertEquals(FlagsAllLegalFields.SimpleEnum.OPTION1, FlagsAllLegalFields.option); flags.printFlags(); flags.printHelp(System.out); flags.parse(new String[]{"--boolean", "true", "--Boolean", "true", "--string", "stringtest", "--int", "10", "--Integer", "20", "--long", "30", "--Long", "40", "--option", "OPTION2"}); assertFalse("Help seems to have been called. It should not have been.", flags.helpFlagged()); assertEquals(true, FlagsAllLegalFields.bool); assertEquals(new Boolean(true), FlagsAllLegalFields.bool2); assertEquals("stringtest", FlagsAllLegalFields.string); assertEquals(10, FlagsAllLegalFields.getValueForPrivateInteger()); assertEquals(new Integer(20), FlagsAllLegalFields.integer2); assertEquals(30, FlagsAllLegalFields.longNum); assertEquals(40, FlagsAllLegalFields.longNum2); assertEquals(FlagsAllLegalFields.SimpleEnum.OPTION2, FlagsAllLegalFields.option); // Just make sure that printHelp() produces something. Since // the format should change to something more sensible we do // not do any checks on content just yet. ByteArrayOutputStream baos = new ByteArrayOutputStream(); flags.printHelp(baos); assertTrue(baos.size() > 0); } /** * Test all supported field types with an instanced flagged class. */ @Test public void testInstanceConfiguration() { final FlagsInstanced flaggedClass = new FlagsInstanced(); Flags flags = new Flags() .loadOpts(flaggedClass) .parse(new String[]{}); assertEquals(false, flaggedClass.bool); assertEquals(new Boolean(false), flaggedClass.bool2); assertEquals("NA", flaggedClass.string); assertEquals(1, flaggedClass.getValueForPrivateInteger()); assertEquals(new Integer(1), flaggedClass.integer2); assertEquals(1, flaggedClass.longNum); assertEquals(1, flaggedClass.longNum2); assertEquals(FlagsInstanced.SimpleEnum.OPTION1, flaggedClass.option); flags.parse(new String[]{"--boolean", "true", "--Boolean", "true", "--string", "stringtest", "--int", "10", "--Integer", "20", "--long", "30", "--Long", "40", "--option", "OPTION2"}); assertEquals(true, flaggedClass.bool); assertEquals(new Boolean(true), flaggedClass.bool2); assertEquals("stringtest", flaggedClass.string); assertEquals(10, flaggedClass.getValueForPrivateInteger()); assertEquals(new Integer(20), flaggedClass.integer2); assertEquals(30, flaggedClass.longNum); assertEquals(40, flaggedClass.longNum2); assertEquals(FlagsInstanced.SimpleEnum.OPTION2, flaggedClass.option); // Check that a new config class does not inherent parses from the first. final FlagsInstanced flaggedClass2 = new FlagsInstanced(); assertEquals(false, flaggedClass2.bool); assertEquals(new Boolean(false), flaggedClass2.bool2); assertEquals("NA", flaggedClass2.string); assertEquals(1, flaggedClass2.getValueForPrivateInteger()); assertEquals(new Integer(1), flaggedClass2.integer2); assertEquals(1, flaggedClass2.longNum); assertEquals(1, flaggedClass2.longNum2); assertEquals(FlagsInstanced.SimpleEnum.OPTION1, flaggedClass2.option); } /** * Test all supported field types with an instanced flagged class. */ @Test public void testInstanceAndClassConfiguration() { final InstancedFlags instancedFlags = new InstancedFlags(); Flags flags = new Flags() .loadOpts(instancedFlags) .loadOpts(ClassFlags.class) .parse(new String[]{}); assertEquals("NA", instancedFlags.string); assertEquals("NA", ClassFlags.string); flags.parse(new String[]{"--classString", "A", "--instanceString", "A"}); assertEquals("A", instancedFlags.string); assertEquals("A", ClassFlags.string); // Check that printHelp does not crash. flags.printHelp(System.out); flags.printVersion(System.out); } /** * Boolean flags should be set to true if no parameter is set, or parameter is set to true. * False otherwise. */ @Test public void testBooleanFlag() { Flags flags = new Flags() .loadOpts(FlagsBooleanFlag.class) .parse(new String[] {"--boolean", "--Boolean"}); assertEquals(true, FlagsBooleanFlag.bool); assertEquals(true, FlagsBooleanFlag.bool2); flags.parse(new String[] {"--boolean", "false", "--Boolean=false"}); assertEquals(false, FlagsBooleanFlag.bool); assertEquals(false, FlagsBooleanFlag.bool2); } /** * Test that printing help does not crash on various cases. */ @Test public void testPrintHelp() { try { Flags flags = new Flags() .loadOpts(FlagsHelpTest.class); flags.printHelp(System.out); } catch (Exception e) { assertFalse("Cought exception.", true); } } /** * Flagged enum option should not work with wrong case. */ @Test (expected = IllegalArgumentException.class) public void testEnumFlagWithWrongCase() { Flags flags = new Flags() .loadOpts(FlagsEnum.class) .parse(new String[]{"--option", "option2"}); } /** * Test flags.getNonOptionArguments(). */ @Test public void testNonOptionArgs() { Flags flags = new Flags() .loadOpts(FlagsOptionTest.class) .parse(new String[]{"--int", "10", "--Integer", "20", "nonoptionarg1", "nonoptionarg2"}); assertEquals(true, flags.getNonOptionArguments().contains("nonoptionarg1")); assertEquals(true, flags.getNonOptionArguments().contains("nonoptionarg2")); } /** * Test flags.getFlagsAsSet. */ @Test public void testFlagsAsList() { Flags flags = new Flags() .loadOpts(FlagsOptionTest.class); assertEquals(flags.getFlagsAsList().size(), 2); assertEquals(flags.getFlagsAsList().get(0).name(), "int"); assertEquals(flags.getFlagsAsList().get(1).name(), "Integer"); } /** * Two flags with the same name should not work. */ @Test (expected = IllegalArgumentException.class) public void testMultipleFlagsWithSameName() { Flags flags = new Flags() .loadOpts(FlagsAllLegalFields.class) .loadOpts(FlagsDoubleName.class); } /** * Test the fail event when a required parameter is not supplied. */ @Test (expected = IllegalArgumentException.class) public void testRequiredArg() { Flags flags = new Flags() .loadOpts(FlagsRequiredArg.class) .parse(new String[]{}); } /** * Test that --help and --version does not trigger ArgumentException when parsing flags are required. */ @Test public void testRequiredArgWithHelp() { try { Flags helpFlags = new Flags() .loadOpts(FlagsRequiredArg.class) .parse(new String[]{"--help"}); helpFlags.printHelp(System.out); Flags versionFlags = new Flags() .loadOpts(FlagsRequiredArg.class) .parse(new String[]{"--version"}); versionFlags.printVersion(System.out); } catch (Exception e) { e.printStackTrace(); assertFalse("Should not throw exceptions", true); } } /** * Test unsupported argument. */ @Test (expected = IllegalArgumentException.class) public void testUnsupportedVariable() { Flags flags = new Flags() .loadOpts(FlagsWrongVariable.class); } /** * Test non static field. */ @Test (expected = IllegalArgumentException.class) public void testNotStaticVariable() { Flags flags = new Flags() .loadOpts(FlagsNonStaticVariable.class); } /** * Test no default value and not given in argument. * Should not do anything, and of course not crash. */ @Test public void testArgumentNotGivenForValueWithoutDefault() { Assert.assertNull(FlagsArgumentNPE.argWithoutDefault); Flags flags = new Flags() .loadOpts(FlagsArgumentNPE.class) .parse(new String[] {}); Assert.assertNull(FlagsArgumentNPE.argWithoutDefault); } /** * Test that --properties-file loads flags from a file */ @Test public void testLoadingFromPropertiesFile() throws Exception { File propertiesFile = File.createTempFile("test", "properties"); propertiesFile.setWritable(true); FileOutputStream fio = new FileOutputStream(propertiesFile); String properties = "integer=1\n\n" + "#comments=not included\n" + "not-in-options=abc\n" + "name=myName\n" + "help\n" + "version\n"; fio.write(properties.getBytes()); fio.close(); Flags flags = new Flags() .loadOpts(FlagsPropertiesFile.class) .parse(new String[]{"--properties-file", propertiesFile.getAbsolutePath()}); assertFalse("Help seems to have been called. It should not have been.", flags.helpFlagged()); assertFalse("Version seems to have been called. It should not have been.", flags.versionFlagged()); assertEquals("myName", FlagsPropertiesFile.name); assertEquals(1, FlagsPropertiesFile.integer); Assert.assertNull(FlagsPropertiesFile.comments); } /** * Test that properties are loaded from two files using two --properties-files options */ @Test public void testLoadingFromMultiplePropertyFiles() throws Exception { File propertiesFile1 = File.createTempFile("test1", "properties"); propertiesFile1.setWritable(true); FileOutputStream fio1 = new FileOutputStream(propertiesFile1); String properties1 = "integer=1\n\n" + "help\n" + "version\n"; fio1.write(properties1.getBytes()); fio1.close(); File propertiesFile2 = File.createTempFile("test2", "properties"); propertiesFile2.setWritable(true); FileOutputStream fio2 = new FileOutputStream(propertiesFile2); String properties2 = "name=myName\n\n" + "help\n" + "version\n"; fio2.write(properties2.getBytes()); fio2.close(); Flags flags = new Flags() .loadOpts(FlagsPropertiesFile.class) .parse(new String[]{"--properties-file", propertiesFile1.getAbsolutePath(), "--properties-file", propertiesFile2.getAbsolutePath() }); assertFalse("Help seems to have been called. It should not have been.", flags.helpFlagged()); assertFalse("Version seems to have been called. It should not have been.", flags.versionFlagged()); assertEquals("myName", FlagsPropertiesFile.name); assertEquals(1, FlagsPropertiesFile.integer); Assert.assertNull(FlagsPropertiesFile.comments); } /** * Test that properties are loaded from two files seperated by ';' */ @Test public void testLoadingFromMultiplePropertyFiles2() throws Exception { File propertiesFile1 = File.createTempFile("test1", "properties"); propertiesFile1.setWritable(true); FileOutputStream fio1 = new FileOutputStream(propertiesFile1); String properties1 = "integer=1\n\n" + "help\n" + "version\n"; fio1.write(properties1.getBytes()); fio1.close(); File propertiesFile2 = File.createTempFile("test2", "properties"); propertiesFile2.setWritable(true); FileOutputStream fio2 = new FileOutputStream(propertiesFile2); String properties2 = "name=myName\n\n" + "help\n" + "version\n"; fio2.write(properties2.getBytes()); fio2.close(); Flags flags = new Flags() .loadOpts(FlagsPropertiesFile.class) .parse(new String[]{"--properties-file", propertiesFile1.getAbsolutePath() + ';' +propertiesFile2.getAbsolutePath() }); assertFalse("Help seems to have been called. It should not have been.", flags.helpFlagged()); assertFalse("Version seems to have been called. It should not have been.", flags.versionFlagged()); assertEquals("myName", FlagsPropertiesFile.name); assertEquals(1, FlagsPropertiesFile.integer); Assert.assertNull(FlagsPropertiesFile.comments); } static class BaseFlaggedTestClass { static int baseCallCounter; @PostConstruct protected void base1() {baseCallCounter++;} @PostConstruct private void base2() {baseCallCounter++;} } static class FlaggedTestClass extends BaseFlaggedTestClass { @Flag (name="flag-one") private String flagOne; static int callCounter; @PostConstruct public void instance1() { callCounter++; } @PostConstruct private void instance2() { callCounter++; } @PostConstruct protected void instance3() { callCounter++;} @PostConstruct static void instance4() { callCounter++; } } static class FlaggedTestStaticClass { @Flag (name="flag-two") private static String flagTwo; public static int callCounter; @PostConstruct public static void static1() { callCounter++; } // check that instance methods are ignored @PostConstruct public void instsance1() { callCounter++; } } @Test public void testPostConstructForInstanceConfiguration() { final String[] args = new String[] { "--flag-one", "xyz"}; final FlaggedTestClass instance = new FlaggedTestClass(); new Flags().loadOpts(instance).parse(args); assertThat(instance.flagOne, is("xyz")); assertThat(FlaggedTestClass.callCounter, is(3)); // check that we don't support inherited methods for now assertThat(BaseFlaggedTestClass.baseCallCounter, is(0)); } @Test public void testPostConstructForСlassConfiguration() { final String[] args = new String[] { "--flag-two", "abc"}; new Flags().loadOpts(FlaggedTestStaticClass.class).parse(args); assertThat(FlaggedTestStaticClass.flagTwo, is("abc")); assertThat(FlaggedTestStaticClass.callCounter, is(1)); // don't support i methods. assertThat(BaseFlaggedTestClass.baseCallCounter, is(0)); } static class FlaggedTestClassInvalidMethod { @PostConstruct public void i1(final String string) { } } @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void testPostConstructInvalidMethod() { final FlaggedTestClassInvalidMethod invalidMethod = new FlaggedTestClassInvalidMethod(); expectedException.expect(IllegalArgumentException.class); new Flags().loadOpts(invalidMethod).parse(new String[0]); } static class FlaggedTestClassThrowsException { @Flag (name="flag-one") private String flagOne; @PostConstruct public void i1() { throw new UnsupportedOperationException(); } } @Test public void testPostConstructExceptionInMethod() { final FlaggedTestClassThrowsException invalidMethod = new FlaggedTestClassThrowsException(); expectedException.expectCause(isA(UnsupportedOperationException.class)); new Flags().loadOpts(invalidMethod).parse(new String[0]); } }
flags/src/test/java/org/cloudname/flags/FlagsTest.java
package org.cloudname.flags; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import javax.annotation.PostConstruct; import junit.framework.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.isA; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; /** * Test class for Flags. * * @author acidmoose * */ public class FlagsTest { /** * Test all supported field types. */ @Test public void testSimpleRun() { Flags flags = new Flags() .loadOpts(FlagsAllLegalFields.class) .parse(new String[]{}); assertFalse("Help seems to have been called. It should not have been.", flags.helpFlagged()); assertEquals(false, FlagsAllLegalFields.bool); assertEquals(new Boolean(false), FlagsAllLegalFields.bool2); assertEquals("NA", FlagsAllLegalFields.string); assertEquals(1, FlagsAllLegalFields.getValueForPrivateInteger()); assertEquals(new Integer(1), FlagsAllLegalFields.integer2); assertEquals(1, FlagsAllLegalFields.longNum); assertEquals(1, FlagsAllLegalFields.longNum2); assertEquals(FlagsAllLegalFields.SimpleEnum.OPTION1, FlagsAllLegalFields.option); flags.printFlags(); flags.printHelp(System.out); flags.parse(new String[]{"--boolean", "true", "--Boolean", "true", "--string", "stringtest", "--int", "10", "--Integer", "20", "--long", "30", "--Long", "40", "--option", "OPTION2"}); assertFalse("Help seems to have been called. It should not have been.", flags.helpFlagged()); assertEquals(true, FlagsAllLegalFields.bool); assertEquals(new Boolean(true), FlagsAllLegalFields.bool2); assertEquals("stringtest", FlagsAllLegalFields.string); assertEquals(10, FlagsAllLegalFields.getValueForPrivateInteger()); assertEquals(new Integer(20), FlagsAllLegalFields.integer2); assertEquals(30, FlagsAllLegalFields.longNum); assertEquals(40, FlagsAllLegalFields.longNum2); assertEquals(FlagsAllLegalFields.SimpleEnum.OPTION2, FlagsAllLegalFields.option); // Just make sure that printHelp() produces something. Since // the format should change to something more sensible we do // not do any checks on content just yet. ByteArrayOutputStream baos = new ByteArrayOutputStream(); flags.printHelp(baos); assertTrue(baos.size() > 0); } /** * Test all supported field types with an instanced flagged class. */ @Test public void testInstanceConfiguration() { final FlagsInstanced flaggedClass = new FlagsInstanced(); Flags flags = new Flags() .loadOpts(flaggedClass) .parse(new String[]{}); assertEquals(false, flaggedClass.bool); assertEquals(new Boolean(false), flaggedClass.bool2); assertEquals("NA", flaggedClass.string); assertEquals(1, flaggedClass.getValueForPrivateInteger()); assertEquals(new Integer(1), flaggedClass.integer2); assertEquals(1, flaggedClass.longNum); assertEquals(1, flaggedClass.longNum2); assertEquals(FlagsInstanced.SimpleEnum.OPTION1, flaggedClass.option); flags.parse(new String[]{"--boolean", "true", "--Boolean", "true", "--string", "stringtest", "--int", "10", "--Integer", "20", "--long", "30", "--Long", "40", "--option", "OPTION2"}); assertEquals(true, flaggedClass.bool); assertEquals(new Boolean(true), flaggedClass.bool2); assertEquals("stringtest", flaggedClass.string); assertEquals(10, flaggedClass.getValueForPrivateInteger()); assertEquals(new Integer(20), flaggedClass.integer2); assertEquals(30, flaggedClass.longNum); assertEquals(40, flaggedClass.longNum2); assertEquals(FlagsInstanced.SimpleEnum.OPTION2, flaggedClass.option); // Check that a new config class does not inherent parses from the first. final FlagsInstanced flaggedClass2 = new FlagsInstanced(); assertEquals(false, flaggedClass2.bool); assertEquals(new Boolean(false), flaggedClass2.bool2); assertEquals("NA", flaggedClass2.string); assertEquals(1, flaggedClass2.getValueForPrivateInteger()); assertEquals(new Integer(1), flaggedClass2.integer2); assertEquals(1, flaggedClass2.longNum); assertEquals(1, flaggedClass2.longNum2); assertEquals(FlagsInstanced.SimpleEnum.OPTION1, flaggedClass2.option); } /** * Test all supported field types with an instanced flagged class. */ @Test public void testInstanceAndClassConfiguration() { final InstancedFlags instancedFlags = new InstancedFlags(); Flags flags = new Flags() .loadOpts(instancedFlags) .loadOpts(ClassFlags.class) .parse(new String[]{}); assertEquals("NA", instancedFlags.string); assertEquals("NA", ClassFlags.string); flags.parse(new String[]{"--classString", "A", "--instanceString", "A"}); assertEquals("A", instancedFlags.string); assertEquals("A", ClassFlags.string); // Check that printHelp does not crash. flags.printHelp(System.out); flags.printVersion(System.out); } /** * Boolean flags should be set to true if no parameter is set, or parameter is set to true. * False otherwise. */ @Test public void testBooleanFlag() { Flags flags = new Flags() .loadOpts(FlagsBooleanFlag.class) .parse(new String[] {"--boolean", "--Boolean"}); assertEquals(true, FlagsBooleanFlag.bool); assertEquals(true, FlagsBooleanFlag.bool2); flags.parse(new String[] {"--boolean", "false", "--Boolean=false"}); assertEquals(false, FlagsBooleanFlag.bool); assertEquals(false, FlagsBooleanFlag.bool2); } /** * Test that printing help does not crash on various cases. */ @Test public void testPrintHelp() { try { Flags flags = new Flags() .loadOpts(FlagsHelpTest.class); flags.printHelp(System.out); } catch (Exception e) { assertFalse("Cought exception.", true); } } /** * Flagged enum option should not work with wrong case. */ @Test (expected = IllegalArgumentException.class) public void testEnumFlagWithWrongCase() { Flags flags = new Flags() .loadOpts(FlagsEnum.class) .parse(new String[]{"--option", "option2"}); } /** * Test flags.getNonOptionArguments(). */ @Test public void testNonOptionArgs() { Flags flags = new Flags() .loadOpts(FlagsOptionTest.class) .parse(new String[]{"--int", "10", "--Integer", "20", "nonoptionarg1", "nonoptionarg2"}); assertEquals(true, flags.getNonOptionArguments().contains("nonoptionarg1")); assertEquals(true, flags.getNonOptionArguments().contains("nonoptionarg2")); } /** * Test flags.getFlagsAsSet. */ @Test public void testFlagsAsList() { Flags flags = new Flags() .loadOpts(FlagsOptionTest.class); assertEquals(flags.getFlagsAsList().size(), 2); assertEquals(flags.getFlagsAsList().get(0).name(), "int"); assertEquals(flags.getFlagsAsList().get(1).name(), "Integer"); } /** * Two flags with the same name should not work. */ @Test (expected = IllegalArgumentException.class) public void testMultipleFlagsWithSameName() { Flags flags = new Flags() .loadOpts(FlagsAllLegalFields.class) .loadOpts(FlagsDoubleName.class); } /** * Test the fail event when a required parameter is not supplied. */ @Test (expected = IllegalArgumentException.class) public void testRequiredArg() { Flags flags = new Flags() .loadOpts(FlagsRequiredArg.class) .parse(new String[]{}); } /** * Test that --help and --version does not trigger ArgumentException when parsing flags are required. */ @Test public void testRequiredArgWithHelp() { try { Flags helpFlags = new Flags() .loadOpts(FlagsRequiredArg.class) .parse(new String[]{"--help"}); helpFlags.printHelp(System.out); Flags versionFlags = new Flags() .loadOpts(FlagsRequiredArg.class) .parse(new String[]{"--version"}); versionFlags.printVersion(System.out); } catch (Exception e) { e.printStackTrace(); assertFalse("Should not throw exceptions", true); } } /** * Test unsupported argument. */ @Test (expected = IllegalArgumentException.class) public void testUnsupportedVariable() { Flags flags = new Flags() .loadOpts(FlagsWrongVariable.class); } /** * Test non static field. */ @Test (expected = IllegalArgumentException.class) public void testNotStaticVariable() { Flags flags = new Flags() .loadOpts(FlagsNonStaticVariable.class); } /** * Test no default value and not given in argument. * Should not do anything, and of course not crash. */ @Test public void testArgumentNotGivenForValueWithoutDefault() { Assert.assertNull(FlagsArgumentNPE.argWithoutDefault); Flags flags = new Flags() .loadOpts(FlagsArgumentNPE.class) .parse(new String[] {}); Assert.assertNull(FlagsArgumentNPE.argWithoutDefault); } /** * Test that --properties-file loads flags from a file */ @Test public void testLoadingFromPropertiesFile() throws Exception { File propertiesFile = File.createTempFile("test", "properties"); propertiesFile.setWritable(true); FileOutputStream fio = new FileOutputStream(propertiesFile); String properties = "integer=1\n\n" + "#comments=not included\n" + "not-in-options=abc\n" + "name=myName\n" + "help\n" + "version\n"; fio.write(properties.getBytes()); fio.close(); Flags flags = new Flags() .loadOpts(FlagsPropertiesFile.class) .parse(new String[]{"--properties-file", propertiesFile.getAbsolutePath()}); assertFalse("Help seems to have been called. It should not have been.", flags.helpFlagged()); assertFalse("Version seems to have been called. It should not have been.", flags.versionFlagged()); assertEquals("myName", FlagsPropertiesFile.name); assertEquals(1, FlagsPropertiesFile.integer); Assert.assertNull(FlagsPropertiesFile.comments); } /** * Test that properties are loaded from two files using two --properties-files options */ @Test public void testLoadingFromMultiplePropertyFiles() throws Exception { File propertiesFile1 = File.createTempFile("test1", "properties"); propertiesFile1.setWritable(true); FileOutputStream fio1 = new FileOutputStream(propertiesFile1); String properties1 = "integer=1\n\n" + "help\n" + "version\n"; fio1.write(properties1.getBytes()); fio1.close(); File propertiesFile2 = File.createTempFile("test2", "properties"); propertiesFile2.setWritable(true); FileOutputStream fio2 = new FileOutputStream(propertiesFile2); String properties2 = "name=myName\n\n" + "help\n" + "version\n"; fio2.write(properties2.getBytes()); fio2.close(); Flags flags = new Flags() .loadOpts(FlagsPropertiesFile.class) .parse(new String[]{"--properties-file", propertiesFile1.getAbsolutePath(), "--properties-file", propertiesFile2.getAbsolutePath() }); assertFalse("Help seems to have been called. It should not have been.", flags.helpFlagged()); assertFalse("Version seems to have been called. It should not have been.", flags.versionFlagged()); assertEquals("myName", FlagsPropertiesFile.name); assertEquals(1, FlagsPropertiesFile.integer); Assert.assertNull(FlagsPropertiesFile.comments); } /** * Test that properties are loaded from two files seperated by ';' */ @Test public void testLoadingFromMultiplePropertyFiles2() throws Exception { File propertiesFile1 = File.createTempFile("test1", "properties"); propertiesFile1.setWritable(true); FileOutputStream fio1 = new FileOutputStream(propertiesFile1); String properties1 = "integer=1\n\n" + "help\n" + "version\n"; fio1.write(properties1.getBytes()); fio1.close(); File propertiesFile2 = File.createTempFile("test2", "properties"); propertiesFile2.setWritable(true); FileOutputStream fio2 = new FileOutputStream(propertiesFile2); String properties2 = "name=myName\n\n" + "help\n" + "version\n"; fio2.write(properties2.getBytes()); fio2.close(); Flags flags = new Flags() .loadOpts(FlagsPropertiesFile.class) .parse(new String[]{"--properties-file", propertiesFile1.getAbsolutePath() + ';' +propertiesFile2.getAbsolutePath() }); assertFalse("Help seems to have been called. It should not have been.", flags.helpFlagged()); assertFalse("Version seems to have been called. It should not have been.", flags.versionFlagged()); assertEquals("myName", FlagsPropertiesFile.name); assertEquals(1, FlagsPropertiesFile.integer); Assert.assertNull(FlagsPropertiesFile.comments); } static class BaseFlaggedTestClass { static int baseCallCounter; @PostConstruct protected void b0() {baseCallCounter++;} @PostConstruct private void b1() {baseCallCounter++;} } static class FlaggedTestClass extends BaseFlaggedTestClass { @Flag (name="flag-one") private String flagOne; static int callCounter; @PostConstruct public void i1() { callCounter++; } @PostConstruct private void i2() { callCounter++; } @PostConstruct protected void i3() { callCounter++;} @PostConstruct static void i4() { callCounter++; } } static class FlaggedTestStaticClass { @Flag (name="flag-two") private static String flagTwo; public static int callCounter; @PostConstruct public static void c1() { callCounter++; } // check that instance methods are ignored @PostConstruct public void i2() { callCounter++; } } @Test public void testPostConstructForInstanceConfiguration() { final String[] args = new String[] { "--flag-one", "xyz"}; final FlaggedTestClass instance = new FlaggedTestClass(); new Flags().loadOpts(instance).parse(args); assertThat(instance.flagOne, is("xyz")); assertThat(FlaggedTestClass.callCounter, is(3)); // check that we don't support inherited methods for now assertThat(BaseFlaggedTestClass.baseCallCounter, is(0)); } @Test public void testPostConstructForСlassConfiguration() { final String[] args = new String[] { "--flag-two", "abc"}; new Flags().loadOpts(FlaggedTestStaticClass.class).parse(args); assertThat(FlaggedTestStaticClass.flagTwo, is("abc")); assertThat(FlaggedTestStaticClass.callCounter, is(1)); // don't support i methods. assertThat(BaseFlaggedTestClass.baseCallCounter, is(0)); } static class FlaggedTestClassInvalidMethod { @PostConstruct public void i1(final String string) { } } @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void testPostConstructInvalidMethod() { final FlaggedTestClassInvalidMethod invalidMethod = new FlaggedTestClassInvalidMethod(); expectedException.expect(IllegalArgumentException.class); new Flags().loadOpts(invalidMethod).parse(new String[0]); } static class FlaggedTestClassThrowsException { @Flag (name="flag-one") private String flagOne; @PostConstruct public void i1() { throw new UnsupportedOperationException(); } } @Test public void testPostConstructExceptionInMethod() { final FlaggedTestClassThrowsException invalidMethod = new FlaggedTestClassThrowsException(); expectedException.expectCause(isA(UnsupportedOperationException.class)); new Flags().loadOpts(invalidMethod).parse(new String[0]); } }
Address more review comments
flags/src/test/java/org/cloudname/flags/FlagsTest.java
Address more review comments
Java
apache-2.0
7fe7f8db7a4118c2f79df08b17271a0c9d561e72
0
mapsme/omim,bykoianko/omim,mpimenov/omim,rokuz/omim,bykoianko/omim,darina/omim,rokuz/omim,VladiMihaylenko/omim,darina/omim,milchakov/omim,rokuz/omim,milchakov/omim,VladiMihaylenko/omim,mapsme/omim,bykoianko/omim,VladiMihaylenko/omim,darina/omim,matsprea/omim,milchakov/omim,alexzatsepin/omim,matsprea/omim,mapsme/omim,darina/omim,darina/omim,mapsme/omim,VladiMihaylenko/omim,VladiMihaylenko/omim,bykoianko/omim,VladiMihaylenko/omim,bykoianko/omim,bykoianko/omim,VladiMihaylenko/omim,alexzatsepin/omim,mpimenov/omim,mpimenov/omim,mapsme/omim,alexzatsepin/omim,matsprea/omim,matsprea/omim,mpimenov/omim,matsprea/omim,alexzatsepin/omim,rokuz/omim,milchakov/omim,VladiMihaylenko/omim,alexzatsepin/omim,VladiMihaylenko/omim,milchakov/omim,milchakov/omim,rokuz/omim,VladiMihaylenko/omim,milchakov/omim,darina/omim,bykoianko/omim,darina/omim,milchakov/omim,rokuz/omim,rokuz/omim,rokuz/omim,matsprea/omim,mpimenov/omim,matsprea/omim,darina/omim,mapsme/omim,mapsme/omim,milchakov/omim,VladiMihaylenko/omim,alexzatsepin/omim,rokuz/omim,mpimenov/omim,mapsme/omim,alexzatsepin/omim,milchakov/omim,mpimenov/omim,mpimenov/omim,rokuz/omim,bykoianko/omim,mpimenov/omim,mapsme/omim,bykoianko/omim,mpimenov/omim,mpimenov/omim,rokuz/omim,matsprea/omim,darina/omim,darina/omim,alexzatsepin/omim,milchakov/omim,VladiMihaylenko/omim,mpimenov/omim,matsprea/omim,mapsme/omim,matsprea/omim,milchakov/omim,VladiMihaylenko/omim,bykoianko/omim,bykoianko/omim,darina/omim,milchakov/omim,alexzatsepin/omim,mapsme/omim,bykoianko/omim,mapsme/omim,alexzatsepin/omim,bykoianko/omim,mapsme/omim,mpimenov/omim,alexzatsepin/omim,darina/omim,alexzatsepin/omim,darina/omim,alexzatsepin/omim,rokuz/omim,rokuz/omim
package com.mapswithme.maps; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentManager; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.mapswithme.maps.ads.Banner; import com.mapswithme.maps.analytics.ExternalLibrariesMediator; import com.mapswithme.maps.base.BaseActivity; import com.mapswithme.maps.base.BaseActivityDelegate; import com.mapswithme.maps.downloader.UpdaterDialogFragment; import com.mapswithme.maps.editor.ViralFragment; import com.mapswithme.maps.news.BaseNewsFragment; import com.mapswithme.maps.news.NewsFragment; import com.mapswithme.maps.news.WelcomeDialogFragment; import com.mapswithme.maps.permissions.PermissionsDialogFragment; import com.mapswithme.maps.permissions.StoragePermissionsDialogFragment; import com.mapswithme.util.Config; import com.mapswithme.util.Counters; import com.mapswithme.util.PermissionsUtils; import com.mapswithme.util.ThemeUtils; import com.mapswithme.util.UiUtils; import com.mapswithme.util.concurrency.UiThread; import com.mapswithme.util.log.Logger; import com.mapswithme.util.log.LoggerFactory; import com.mapswithme.util.statistics.PushwooshHelper; public class SplashActivity extends AppCompatActivity implements BaseNewsFragment.NewsDialogListener, BaseActivity { private static final Logger LOGGER = LoggerFactory.INSTANCE.getLogger(LoggerFactory.Type.MISC); private static final String TAG = SplashActivity.class.getSimpleName(); private static final String EXTRA_CORE_INITIALIZED = "extra_core_initialized"; private static final String EXTRA_ACTIVITY_TO_START = "extra_activity_to_start"; public static final String EXTRA_INITIAL_INTENT = "extra_initial_intent"; private static final int REQUEST_PERMISSIONS = 1; private static final long FIRST_START_DELAY = 1000; private static final long DELAY = 100; // The first launch of application ever - onboarding screen will be shown. private static boolean sFirstStart; private View mIvLogo; private View mAppName; private boolean mPermissionsGranted; private boolean mNeedStoragePermission; private boolean mCanceled; @NonNull private final Runnable mPermissionsDelayedTask = new Runnable() { @Override public void run() { PermissionsDialogFragment.show(SplashActivity.this, REQUEST_PERMISSIONS); } }; @NonNull private final Runnable mInitCoreDelayedTask = new Runnable() { @Override public void run() { MwmApplication app = (MwmApplication) getApplication(); if (app.arePlatformAndCoreInitialized()) { UiThread.runLater(mFinalDelayedTask); return; } ExternalLibrariesMediator mediator = ((MwmApplication) getApplicationContext()).getMediator(); if (!mediator.isAdvertisingInfoObtained()) { UiThread.runLater(mInitCoreDelayedTask, DELAY); return; } if (!mediator.isLimitAdTrackingEnabled()) { LOGGER.i(TAG, "Limit ad tracking disabled, sensitive tracking initialized"); mediator.initSensitiveEventLogger(); } else { LOGGER.i(TAG, "Limit ad tracking enabled, sensitive tracking not initialized"); } init(); LOGGER.i(TAG, "Core initialized: " + app.arePlatformAndCoreInitialized()); if (app.arePlatformAndCoreInitialized()) { if (mediator.isLimitAdTrackingEnabled()) { LOGGER.i(TAG, "Limit ad tracking enabled, rb banners disabled."); mediator.disableAdProvider(Banner.Type.TYPE_RB); } } // Run delayed task because resumeDialogs() must see the actual value of mCanceled flag, // since onPause() callback can be blocked because of UI thread is busy with framework // initialization. UiThread.runLater(mFinalDelayedTask); } }; @NonNull private final Runnable mFinalDelayedTask = new Runnable() { @Override public void run() { resumeDialogs(); } }; @NonNull private final BaseActivityDelegate mBaseDelegate = new BaseActivityDelegate(this); public static void start(@NonNull Context context, @Nullable Class<? extends Activity> activityToStart, @Nullable Intent initialIntent) { Intent intent = new Intent(context, SplashActivity.class); if (activityToStart != null) intent.putExtra(EXTRA_ACTIVITY_TO_START, activityToStart); if (initialIntent != null) intent.putExtra(EXTRA_INITIAL_INTENT, initialIntent); context.startActivity(intent); } public static boolean isFirstStart() { boolean res = sFirstStart; sFirstStart = false; return res; } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBaseDelegate.onCreate(); handleUpdateMapsFragmentCorrectly(savedInstanceState); UiThread.cancelDelayedTasks(mPermissionsDelayedTask); UiThread.cancelDelayedTasks(mInitCoreDelayedTask); UiThread.cancelDelayedTasks(mFinalDelayedTask); Counters.initCounters(this); initView(); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); mBaseDelegate.onNewIntent(intent); } private void handleUpdateMapsFragmentCorrectly(@Nullable Bundle savedInstanceState) { if (savedInstanceState == null) return; FragmentManager fm = getSupportFragmentManager(); DialogFragment updaterFragment = (DialogFragment) fm .findFragmentByTag(UpdaterDialogFragment.class.getName()); if (updaterFragment == null) return; // If the user revoked the external storage permission while the app was killed // we can't update maps automatically during recovering process, so just dismiss updater fragment // and ask the user to grant the permission. if (!PermissionsUtils.isExternalStorageGranted()) { fm.beginTransaction().remove(updaterFragment).commitAllowingStateLoss(); fm.executePendingTransactions(); StoragePermissionsDialogFragment.show(this); } else { // If external permissions are still granted we just need to check platform // and core initialization, because we may be in the recovering process, // i.e. method onResume() may not be invoked in that case. if (!MwmApplication.get().arePlatformAndCoreInitialized()) { init(); } } } @Override protected void onStart() { super.onStart(); mBaseDelegate.onStart(); } @Override protected void onResume() { super.onResume(); mBaseDelegate.onResume(); mCanceled = false; mPermissionsGranted = PermissionsUtils.isExternalStorageGranted(); DialogFragment storagePermissionsDialog = StoragePermissionsDialogFragment.find(this); DialogFragment permissionsDialog = PermissionsDialogFragment.find(this); if (!mPermissionsGranted) { if (mNeedStoragePermission || storagePermissionsDialog != null) { if (permissionsDialog != null) permissionsDialog.dismiss(); if (storagePermissionsDialog == null) StoragePermissionsDialogFragment.show(this); return; } permissionsDialog = PermissionsDialogFragment.find(this); if (permissionsDialog == null) UiThread.runLater(mPermissionsDelayedTask, FIRST_START_DELAY); return; } if (permissionsDialog != null) permissionsDialog.dismiss(); if (storagePermissionsDialog != null) storagePermissionsDialog.dismiss(); UiThread.runLater(mInitCoreDelayedTask, DELAY); } @Override protected void onPause() { super.onPause(); mBaseDelegate.onPause(); mCanceled = true; UiThread.cancelDelayedTasks(mPermissionsDelayedTask); UiThread.cancelDelayedTasks(mInitCoreDelayedTask); UiThread.cancelDelayedTasks(mFinalDelayedTask); } @Override protected void onStop() { super.onStop(); mBaseDelegate.onStop(); } @Override protected void onDestroy() { super.onDestroy(); mBaseDelegate.onDestroy(); } private void resumeDialogs() { if (mCanceled) return; MwmApplication app = (MwmApplication) getApplication(); if (!app.arePlatformAndCoreInitialized()) { showExternalStorageErrorDialog(); return; } if (Counters.isMigrationNeeded()) { Config.migrateCountersToSharedPrefs(); Counters.setMigrationExecuted(); } sFirstStart = WelcomeDialogFragment.showOn(this); if (sFirstStart) { PushwooshHelper.nativeProcessFirstLaunch(); UiUtils.hide(mIvLogo, mAppName); return; } boolean showNews = NewsFragment.showOn(this, this); if (!showNews) { if (ViralFragment.shouldDisplay()) { UiUtils.hide(mIvLogo, mAppName); ViralFragment dialog = new ViralFragment(); dialog.onDismissListener(new Runnable() { @Override public void run() { onDialogDone(); } }); dialog.show(getSupportFragmentManager(), ""); } else { processNavigation(); } } else { UiUtils.hide(mIvLogo, mAppName); } } private void showExternalStorageErrorDialog() { AlertDialog dialog = new AlertDialog.Builder(this) .setTitle(R.string.dialog_error_storage_title) .setMessage(R.string.dialog_error_storage_message) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { SplashActivity.this.finish(); } }) .setCancelable(false) .create(); dialog.show(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (grantResults.length == 0) return; mPermissionsGranted = PermissionsUtils.computePermissionsResult(permissions, grantResults) .isExternalStorageGranted(); mNeedStoragePermission = !mPermissionsGranted; } @Override public void onDialogDone() { processNavigation(); } private void initView() { UiUtils.setupStatusBar(this); setContentView(R.layout.activity_splash); mIvLogo = findViewById(R.id.iv__logo); mAppName = findViewById(R.id.tv__app_name); } private void init() { MwmApplication.get().initCore(); } @SuppressWarnings("unchecked") private void processNavigation() { Intent input = getIntent(); Intent result = new Intent(this, DownloadResourcesLegacyActivity.class); if (input != null) { if (input.hasExtra(EXTRA_ACTIVITY_TO_START)) { result = new Intent(this, (Class<? extends Activity>) input.getSerializableExtra(EXTRA_ACTIVITY_TO_START)); } Intent initialIntent = input.hasExtra(EXTRA_INITIAL_INTENT) ? input.getParcelableExtra(EXTRA_INITIAL_INTENT) : input; result.putExtra(EXTRA_INITIAL_INTENT, initialIntent); } startActivity(result); finish(); } @Override @NonNull public Activity get() { return this; } @Override public int getThemeResourceId(@NonNull String theme) { if (ThemeUtils.isDefaultTheme(theme)) return R.style.MwmTheme; if (ThemeUtils.isNightTheme(theme)) return R.style.MwmTheme_Night; throw new IllegalArgumentException("Attempt to apply unsupported theme: " + theme); } }
android/src/com/mapswithme/maps/SplashActivity.java
package com.mapswithme.maps; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentManager; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.mapswithme.maps.ads.Banner; import com.mapswithme.maps.analytics.ExternalLibrariesMediator; import com.mapswithme.maps.base.BaseActivity; import com.mapswithme.maps.base.BaseActivityDelegate; import com.mapswithme.maps.downloader.UpdaterDialogFragment; import com.mapswithme.maps.editor.ViralFragment; import com.mapswithme.maps.news.BaseNewsFragment; import com.mapswithme.maps.news.NewsFragment; import com.mapswithme.maps.news.WelcomeDialogFragment; import com.mapswithme.maps.permissions.PermissionsDialogFragment; import com.mapswithme.maps.permissions.StoragePermissionsDialogFragment; import com.mapswithme.util.Config; import com.mapswithme.util.Counters; import com.mapswithme.util.PermissionsUtils; import com.mapswithme.util.ThemeUtils; import com.mapswithme.util.UiUtils; import com.mapswithme.util.concurrency.UiThread; import com.mapswithme.util.log.Logger; import com.mapswithme.util.log.LoggerFactory; import com.mapswithme.util.statistics.PushwooshHelper; public class SplashActivity extends AppCompatActivity implements BaseNewsFragment.NewsDialogListener, BaseActivity { private static final Logger LOGGER = LoggerFactory.INSTANCE.getLogger(LoggerFactory.Type.MISC); private static final String TAG = SplashActivity.class.getSimpleName(); private static final String EXTRA_CORE_INITIALIZED = "extra_core_initialized"; private static final String EXTRA_ACTIVITY_TO_START = "extra_activity_to_start"; public static final String EXTRA_INITIAL_INTENT = "extra_initial_intent"; private static final int REQUEST_PERMISSIONS = 1; private static final long FIRST_START_DELAY = 1000; private static final long DELAY = 100; // The first launch of application ever - onboarding screen will be shown. private static boolean sFirstStart; private View mIvLogo; private View mAppName; private boolean mPermissionsGranted; private boolean mNeedStoragePermission; private boolean mCanceled; private boolean mCoreInitialized; @NonNull private final Runnable mPermissionsDelayedTask = new Runnable() { @Override public void run() { PermissionsDialogFragment.show(SplashActivity.this, REQUEST_PERMISSIONS); } }; @NonNull private final Runnable mInitCoreDelayedTask = new Runnable() { @Override public void run() { if (mCoreInitialized) { UiThread.runLater(mFinalDelayedTask); return; } ExternalLibrariesMediator mediator = ((MwmApplication) getApplicationContext()).getMediator(); if (!mediator.isAdvertisingInfoObtained()) { UiThread.runLater(mInitCoreDelayedTask, DELAY); return; } if (!mediator.isLimitAdTrackingEnabled()) { LOGGER.i(TAG, "Limit ad tracking disabled, sensitive tracking initialized"); mediator.initSensitiveEventLogger(); } else { LOGGER.i(TAG, "Limit ad tracking enabled, sensitive tracking not initialized"); } init(); LOGGER.i(TAG, "Core initialized: " + mCoreInitialized); if (mCoreInitialized) { if (mediator.isLimitAdTrackingEnabled()) { LOGGER.i(TAG, "Limit ad tracking enabled, rb banners disabled."); mediator.disableAdProvider(Banner.Type.TYPE_RB); } } // Run delayed task because resumeDialogs() must see the actual value of mCanceled flag, // since onPause() callback can be blocked because of UI thread is busy with framework // initialization. UiThread.runLater(mFinalDelayedTask); } }; @NonNull private final Runnable mFinalDelayedTask = new Runnable() { @Override public void run() { resumeDialogs(); } }; @NonNull private final BaseActivityDelegate mBaseDelegate = new BaseActivityDelegate(this); public static void start(@NonNull Context context, @Nullable Class<? extends Activity> activityToStart, @Nullable Intent initialIntent) { Intent intent = new Intent(context, SplashActivity.class); if (activityToStart != null) intent.putExtra(EXTRA_ACTIVITY_TO_START, activityToStart); if (initialIntent != null) intent.putExtra(EXTRA_INITIAL_INTENT, initialIntent); context.startActivity(intent); } public static boolean isFirstStart() { boolean res = sFirstStart; sFirstStart = false; return res; } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBaseDelegate.onCreate(); if (savedInstanceState != null) mCoreInitialized = savedInstanceState.getBoolean(EXTRA_CORE_INITIALIZED); handleUpdateMapsFragmentCorrectly(savedInstanceState); UiThread.cancelDelayedTasks(mPermissionsDelayedTask); UiThread.cancelDelayedTasks(mInitCoreDelayedTask); UiThread.cancelDelayedTasks(mFinalDelayedTask); Counters.initCounters(this); initView(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(EXTRA_CORE_INITIALIZED, mCoreInitialized); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); mBaseDelegate.onNewIntent(intent); } private void handleUpdateMapsFragmentCorrectly(@Nullable Bundle savedInstanceState) { if (savedInstanceState == null) return; FragmentManager fm = getSupportFragmentManager(); DialogFragment updaterFragment = (DialogFragment) fm .findFragmentByTag(UpdaterDialogFragment.class.getName()); if (updaterFragment == null) return; // If the user revoked the external storage permission while the app was killed // we can't update maps automatically during recovering process, so just dismiss updater fragment // and ask the user to grant the permission. if (!PermissionsUtils.isExternalStorageGranted()) { fm.beginTransaction().remove(updaterFragment).commitAllowingStateLoss(); fm.executePendingTransactions(); StoragePermissionsDialogFragment.show(this); } else { // If external permissions are still granted we just need to check platform // and core initialization, because we may be in the recovering process, // i.e. method onResume() may not be invoked in that case. if (!MwmApplication.get().arePlatformAndCoreInitialized()) { init(); } } } @Override protected void onStart() { super.onStart(); mBaseDelegate.onStart(); } @Override protected void onResume() { super.onResume(); mBaseDelegate.onResume(); mCanceled = false; mPermissionsGranted = PermissionsUtils.isExternalStorageGranted(); DialogFragment storagePermissionsDialog = StoragePermissionsDialogFragment.find(this); DialogFragment permissionsDialog = PermissionsDialogFragment.find(this); if (!mPermissionsGranted) { if (mNeedStoragePermission || storagePermissionsDialog != null) { if (permissionsDialog != null) permissionsDialog.dismiss(); if (storagePermissionsDialog == null) StoragePermissionsDialogFragment.show(this); return; } permissionsDialog = PermissionsDialogFragment.find(this); if (permissionsDialog == null) UiThread.runLater(mPermissionsDelayedTask, FIRST_START_DELAY); return; } if (permissionsDialog != null) permissionsDialog.dismiss(); if (storagePermissionsDialog != null) storagePermissionsDialog.dismiss(); UiThread.runLater(mInitCoreDelayedTask, DELAY); } @Override protected void onPause() { super.onPause(); mBaseDelegate.onPause(); mCanceled = true; UiThread.cancelDelayedTasks(mPermissionsDelayedTask); UiThread.cancelDelayedTasks(mInitCoreDelayedTask); UiThread.cancelDelayedTasks(mFinalDelayedTask); } @Override protected void onStop() { super.onStop(); mBaseDelegate.onStop(); } @Override protected void onDestroy() { super.onDestroy(); mBaseDelegate.onDestroy(); } private void resumeDialogs() { if (mCanceled) return; if (!mCoreInitialized) { showExternalStorageErrorDialog(); return; } if (Counters.isMigrationNeeded()) { Config.migrateCountersToSharedPrefs(); Counters.setMigrationExecuted(); } sFirstStart = WelcomeDialogFragment.showOn(this); if (sFirstStart) { PushwooshHelper.nativeProcessFirstLaunch(); UiUtils.hide(mIvLogo, mAppName); return; } boolean showNews = NewsFragment.showOn(this, this); if (!showNews) { if (ViralFragment.shouldDisplay()) { UiUtils.hide(mIvLogo, mAppName); ViralFragment dialog = new ViralFragment(); dialog.onDismissListener(new Runnable() { @Override public void run() { onDialogDone(); } }); dialog.show(getSupportFragmentManager(), ""); } else { processNavigation(); } } else { UiUtils.hide(mIvLogo, mAppName); } } private void showExternalStorageErrorDialog() { AlertDialog dialog = new AlertDialog.Builder(this) .setTitle(R.string.dialog_error_storage_title) .setMessage(R.string.dialog_error_storage_message) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { SplashActivity.this.finish(); } }) .setCancelable(false) .create(); dialog.show(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (grantResults.length == 0) return; mPermissionsGranted = PermissionsUtils.computePermissionsResult(permissions, grantResults) .isExternalStorageGranted(); mNeedStoragePermission = !mPermissionsGranted; } @Override public void onDialogDone() { processNavigation(); } private void initView() { UiUtils.setupStatusBar(this); setContentView(R.layout.activity_splash); mIvLogo = findViewById(R.id.iv__logo); mAppName = findViewById(R.id.tv__app_name); } private void init() { mCoreInitialized = MwmApplication.get().initCore(); } @SuppressWarnings("unchecked") private void processNavigation() { Intent input = getIntent(); Intent result = new Intent(this, DownloadResourcesLegacyActivity.class); if (input != null) { if (input.hasExtra(EXTRA_ACTIVITY_TO_START)) { result = new Intent(this, (Class<? extends Activity>) input.getSerializableExtra(EXTRA_ACTIVITY_TO_START)); } Intent initialIntent = input.hasExtra(EXTRA_INITIAL_INTENT) ? input.getParcelableExtra(EXTRA_INITIAL_INTENT) : input; result.putExtra(EXTRA_INITIAL_INTENT, initialIntent); } startActivity(result); finish(); } @Override @NonNull public Activity get() { return this; } @Override public int getThemeResourceId(@NonNull String theme) { if (ThemeUtils.isDefaultTheme(theme)) return R.style.MwmTheme; if (ThemeUtils.isNightTheme(theme)) return R.style.MwmTheme_Night; throw new IllegalArgumentException("Attempt to apply unsupported theme: " + theme); } }
[android] Fixed core initialization for splash screen, replaced init core flag to Application method call
android/src/com/mapswithme/maps/SplashActivity.java
[android] Fixed core initialization for splash screen, replaced init core flag to Application method call
Java
apache-2.0
410090fd6ce15f3f10f42d948dfaf309d0d208be
0
rpmoore/ds3_java_sdk,DenverM80/ds3_java_sdk,RachelTucker/ds3_java_sdk,DenverM80/ds3_java_sdk,DenverM80/ds3_java_sdk,rpmoore/ds3_java_sdk,SpectraLogic/ds3_java_sdk,SpectraLogic/ds3_java_sdk,SpectraLogic/ds3_java_sdk,rpmoore/ds3_java_sdk,RachelTucker/ds3_java_sdk,RachelTucker/ds3_java_sdk,SpectraLogic/ds3_java_sdk,DenverM80/ds3_java_sdk,RachelTucker/ds3_java_sdk,rpmoore/ds3_java_sdk
/* * ****************************************************************************** * Copyright 2014-2015 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ // This code is auto-generated, do not modify package com.spectralogic.ds3client.commands.spectrads3; import com.spectralogic.ds3client.networking.HttpVerb; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.charset.Charset; import com.spectralogic.ds3client.utils.Guard; import com.spectralogic.ds3client.commands.AbstractRequest; import com.spectralogic.ds3client.models.ReplicationConflictResolutionMode; import com.spectralogic.ds3client.models.Priority; import com.google.common.net.UrlEscapers; public class ReplicatePutJobSpectraS3Request extends AbstractRequest { // Variables private final String bucketName; private final String requestPayload; private ReplicationConflictResolutionMode conflictResolutionMode; private Priority priority; private long size = 0; // Constructor public ReplicatePutJobSpectraS3Request(final String bucketName, final String requestPayload) { this.bucketName = bucketName; this.requestPayload = requestPayload; this.getQueryParams().put("operation", "start_bulk_put"); this.getQueryParams().put("replicate", null); } public ReplicatePutJobSpectraS3Request withConflictResolutionMode(final ReplicationConflictResolutionMode conflictResolutionMode) { this.conflictResolutionMode = conflictResolutionMode; this.updateQueryParam("conflict_resolution_mode", conflictResolutionMode); return this; } public ReplicatePutJobSpectraS3Request withPriority(final Priority priority) { this.priority = priority; this.updateQueryParam("priority", priority); return this; } @Override public HttpVerb getVerb() { return HttpVerb.PUT; } @Override public String getPath() { return "/_rest_/bucket/" + this.bucketName; } @Override public InputStream getStream() { if (Guard.isStringNullOrEmpty(requestPayload)) { return null; } final byte[] stringBytes = requestPayload.getBytes(Charset.forName("UTF-8")); this.size = stringBytes.length; return new ByteArrayInputStream(stringBytes); } @Override public long getSize() { return this.size; } public String getBucketName() { return this.bucketName; } public String getRequestPayload() { return this.requestPayload; } public ReplicationConflictResolutionMode getConflictResolutionMode() { return this.conflictResolutionMode; } public Priority getPriority() { return this.priority; } }
ds3-sdk/src/main/java/com/spectralogic/ds3client/commands/spectrads3/ReplicatePutJobSpectraS3Request.java
/* * ****************************************************************************** * Copyright 2014-2015 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ // This code is auto-generated, do not modify package com.spectralogic.ds3client.commands.spectrads3; import com.spectralogic.ds3client.networking.HttpVerb; import java.io.ByteArrayInputStream; import java.io.InputStream; import com.spectralogic.ds3client.utils.Guard; import com.spectralogic.ds3client.commands.AbstractRequest; import com.spectralogic.ds3client.models.ReplicationConflictResolutionMode; import com.spectralogic.ds3client.models.Priority; import com.google.common.net.UrlEscapers; public class ReplicatePutJobSpectraS3Request extends AbstractRequest { // Variables private final String bucketName; private final String requestPayload; private ReplicationConflictResolutionMode conflictResolutionMode; private Priority priority; private long size = 0; // Constructor public ReplicatePutJobSpectraS3Request(final String bucketName, final String requestPayload) { this.bucketName = bucketName; this.requestPayload = requestPayload; this.getQueryParams().put("operation", "start_bulk_put"); this.getQueryParams().put("replicate", null); } public ReplicatePutJobSpectraS3Request withConflictResolutionMode(final ReplicationConflictResolutionMode conflictResolutionMode) { this.conflictResolutionMode = conflictResolutionMode; this.updateQueryParam("conflict_resolution_mode", conflictResolutionMode); return this; } public ReplicatePutJobSpectraS3Request withPriority(final Priority priority) { this.priority = priority; this.updateQueryParam("priority", priority); return this; } @Override public HttpVerb getVerb() { return HttpVerb.PUT; } @Override public String getPath() { return "/_rest_/bucket/" + this.bucketName; } @Override public InputStream getStream() { if (Guard.isStringNullOrEmpty(requestPayload)) { return null; } final byte[] stringBytes = requestPayload.getBytes(); this.size = stringBytes.length; return new ByteArrayInputStream(stringBytes); } @Override public long getSize() { return this.size; } public String getBucketName() { return this.bucketName; } public String getRequestPayload() { return this.requestPayload; } public ReplicationConflictResolutionMode getConflictResolutionMode() { return this.conflictResolutionMode; } public Priority getPriority() { return this.priority; } }
Specified charset of UTF-8
ds3-sdk/src/main/java/com/spectralogic/ds3client/commands/spectrads3/ReplicatePutJobSpectraS3Request.java
Specified charset of UTF-8
Java
apache-2.0
84224bd93a68bfa924d721b3b91996efd8701ce8
0
JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse
package edu.harvard.iq.dataverse; import edu.harvard.iq.dataverse.util.MarkupChecker; import edu.harvard.iq.dataverse.DatasetFieldType.FieldType; import edu.harvard.iq.dataverse.util.StringUtil; import edu.harvard.iq.dataverse.util.SystemConfig; import edu.harvard.iq.dataverse.workflows.WorkflowComment; import java.io.Serializable; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.json.Json; import javax.json.JsonArrayBuilder; import javax.json.JsonObjectBuilder; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Index; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.OrderBy; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import javax.persistence.UniqueConstraint; import javax.persistence.Version; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; /** * * @author skraffmiller */ @Entity @Table(indexes = {@Index(columnList="dataset_id")}, uniqueConstraints = @UniqueConstraint(columnNames = {"dataset_id,versionnumber,minorversionnumber"})) public class DatasetVersion implements Serializable { private static final Logger logger = Logger.getLogger(DatasetVersion.class.getCanonicalName()); /** * Convenience comparator to compare dataset versions by their version number. * The draft version is considered the latest. */ public static final Comparator<DatasetVersion> compareByVersion = new Comparator<DatasetVersion>() { @Override public int compare(DatasetVersion o1, DatasetVersion o2) { if ( o1.isDraft() ) { return o2.isDraft() ? 0 : 1; } else { return (int)Math.signum( (o1.getVersionNumber().equals(o2.getVersionNumber())) ? o1.getMinorVersionNumber() - o2.getMinorVersionNumber() : o1.getVersionNumber() - o2.getVersionNumber() ); } } }; // TODO: Determine the UI implications of various version states //IMPORTANT: If you add a new value to this enum, you will also have to modify the // StudyVersionsFragment.xhtml in order to display the correct value from a Resource Bundle public enum VersionState { DRAFT, RELEASED, ARCHIVED, DEACCESSIONED }; public enum License { NONE, CC0 } public static final int ARCHIVE_NOTE_MAX_LENGTH = 1000; public static final int VERSION_NOTE_MAX_LENGTH = 1000; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String UNF; @Version private Long version; private Long versionNumber; private Long minorVersionNumber; @Column(length = VERSION_NOTE_MAX_LENGTH) private String versionNote; /* * @todo versionState should never be null so when we are ready, uncomment * the `nullable = false` below. */ // @Column(nullable = false) @Enumerated(EnumType.STRING) private VersionState versionState; @ManyToOne private Dataset dataset; @OneToMany(mappedBy = "datasetVersion", cascade = {CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST}) @OrderBy("label") // this is not our preferred ordering, which is with the AlphaNumericComparator, but does allow the files to be grouped by category private List<FileMetadata> fileMetadatas = new ArrayList(); @OneToOne(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REMOVE}, orphanRemoval=true) @JoinColumn(name = "termsOfUseAndAccess_id") private TermsOfUseAndAccess termsOfUseAndAccess; @OneToMany(mappedBy = "datasetVersion", orphanRemoval = true, cascade = {CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST}) private List<DatasetField> datasetFields = new ArrayList(); @Temporal(value = TemporalType.TIMESTAMP) @Column( nullable=false ) private Date createTime; @Temporal(value = TemporalType.TIMESTAMP) @Column( nullable=false ) private Date lastUpdateTime; @Temporal(value = TemporalType.TIMESTAMP) private Date releaseTime; @Temporal(value = TemporalType.TIMESTAMP) private Date archiveTime; @Column(length = ARCHIVE_NOTE_MAX_LENGTH) private String archiveNote; private String deaccessionLink; @Transient private String contributorNames; @Transient private String jsonLd; @OneToMany(mappedBy="datasetVersion", cascade={CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST}) private List<DatasetVersionUser> datasetVersionUsers; // Is this the right mapping and cascading for when the workflowcomments table is being used for objects other than DatasetVersion? @OneToMany(mappedBy = "datasetVersion", cascade={CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST}) private List<WorkflowComment> workflowComments; public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getUNF() { return UNF; } public void setUNF(String UNF) { this.UNF = UNF; } /** * This is JPA's optimistic locking mechanism, and has no semantic meaning in the DV object model. * @return the object db version */ public Long getVersion() { return this.version; } public void setVersion(Long version) { } public List<FileMetadata> getFileMetadatas() { return fileMetadatas; } public List<FileMetadata> getFileMetadatasSorted() { Collections.sort(fileMetadatas, FileMetadata.compareByLabel); return fileMetadatas; } public void setFileMetadatas(List<FileMetadata> fileMetadatas) { this.fileMetadatas = fileMetadatas; } public TermsOfUseAndAccess getTermsOfUseAndAccess() { return termsOfUseAndAccess; } public void setTermsOfUseAndAccess(TermsOfUseAndAccess termsOfUseAndAccess) { this.termsOfUseAndAccess = termsOfUseAndAccess; } public List<DatasetField> getDatasetFields() { return datasetFields; } /** * Sets the dataset fields for this version. Also updates the fields to * have @{code this} as their dataset version. * @param datasetFields */ public void setDatasetFields(List<DatasetField> datasetFields) { for ( DatasetField dsf : datasetFields ) { dsf.setDatasetVersion(this); } this.datasetFields = datasetFields; } /** * The only time a dataset can be in review is when it is in draft. * @return if the dataset is being reviewed */ public boolean isInReview() { if (versionState != null && versionState.equals(VersionState.DRAFT)) { return getDataset().isLockedFor(DatasetLock.Reason.InReview); } else { return false; } } public Date getArchiveTime() { return archiveTime; } public void setArchiveTime(Date archiveTime) { this.archiveTime = archiveTime; } public String getArchiveNote() { return archiveNote; } public void setArchiveNote(String note) { // @todo should this be using bean validation for trsting note length? if (note != null && note.length() > ARCHIVE_NOTE_MAX_LENGTH) { throw new IllegalArgumentException("Error setting archiveNote: String length is greater than maximum (" + ARCHIVE_NOTE_MAX_LENGTH + ")." + " StudyVersion id=" + id + ", archiveNote=" + note); } this.archiveNote = note; } public String getDeaccessionLink() { return deaccessionLink; } public void setDeaccessionLink(String deaccessionLink) { this.deaccessionLink = deaccessionLink; } public GlobalId getDeaccessionLinkAsGlobalId() { return new GlobalId(deaccessionLink); } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getLastUpdateTime() { return lastUpdateTime; } public void setLastUpdateTime(Date lastUpdateTime) { if (createTime == null) { createTime = lastUpdateTime; } this.lastUpdateTime = lastUpdateTime; } public String getVersionDate() { if (this.lastUpdateTime == null){ return null; } return new SimpleDateFormat("MMMM d, yyyy").format(lastUpdateTime); } public String getVersionYear() { return new SimpleDateFormat("yyyy").format(lastUpdateTime); } public Date getReleaseTime() { return releaseTime; } public void setReleaseTime(Date releaseTime) { this.releaseTime = releaseTime; } public List<DatasetVersionUser> getDatasetVersionUsers() { return datasetVersionUsers; } public void setUserDatasets(List<DatasetVersionUser> datasetVersionUsers) { this.datasetVersionUsers = datasetVersionUsers; } public List<String> getVersionContributorIdentifiers() { if (this.getDatasetVersionUsers() == null) { return Collections.emptyList(); } List<String> ret = new LinkedList<>(); for (DatasetVersionUser contributor : this.getDatasetVersionUsers()) { ret.add(contributor.getAuthenticatedUser().getIdentifier()); } return ret; } public String getContributorNames() { return contributorNames; } public void setContributorNames(String contributorNames) { this.contributorNames = contributorNames; } public String getVersionNote() { return versionNote; } public DatasetVersionDifference getDefaultVersionDifference() { // if version is deaccessioned ignore it for differences purposes int index = 0; int size = this.getDataset().getVersions().size(); if (this.isDeaccessioned()) { return null; } for (DatasetVersion dsv : this.getDataset().getVersions()) { if (this.equals(dsv)) { if ((index + 1) <= (size - 1)) { for (DatasetVersion dvTest : this.getDataset().getVersions().subList(index + 1, size)) { if (!dvTest.isDeaccessioned()) { DatasetVersionDifference dvd = new DatasetVersionDifference(this, dvTest); return dvd; } } } } index++; } return null; } public VersionState getPriorVersionState() { int index = 0; int size = this.getDataset().getVersions().size(); if (this.isDeaccessioned()) { return null; } for (DatasetVersion dsv : this.getDataset().getVersions()) { if (this.equals(dsv)) { if ((index + 1) <= (size - 1)) { for (DatasetVersion dvTest : this.getDataset().getVersions().subList(index + 1, size)) { return dvTest.getVersionState(); } } } index++; } return null; } public void setVersionNote(String note) { if (note != null && note.length() > VERSION_NOTE_MAX_LENGTH) { throw new IllegalArgumentException("Error setting versionNote: String length is greater than maximum (" + VERSION_NOTE_MAX_LENGTH + ")." + " StudyVersion id=" + id + ", versionNote=" + note); } this.versionNote = note; } public Long getVersionNumber() { return versionNumber; } public void setVersionNumber(Long versionNumber) { this.versionNumber = versionNumber; } public Long getMinorVersionNumber() { return minorVersionNumber; } public void setMinorVersionNumber(Long minorVersionNumber) { this.minorVersionNumber = minorVersionNumber; } public String getFriendlyVersionNumber(){ if (this.isDraft()) { return "DRAFT"; } else { return versionNumber.toString() + "." + minorVersionNumber.toString(); } } public VersionState getVersionState() { return versionState; } public void setVersionState(VersionState versionState) { this.versionState = versionState; } public boolean isReleased() { return versionState.equals(VersionState.RELEASED); } public boolean isPublished() { return isReleased(); } public boolean isDraft() { return versionState.equals(VersionState.DRAFT); } public boolean isWorkingCopy() { return versionState.equals(VersionState.DRAFT); } public boolean isArchived() { return versionState.equals(VersionState.ARCHIVED); } public boolean isDeaccessioned() { return versionState.equals(VersionState.DEACCESSIONED); } public boolean isRetiredCopy() { return (versionState.equals(VersionState.ARCHIVED) || versionState.equals(VersionState.DEACCESSIONED)); } public boolean isMinorUpdate() { if (this.dataset.getLatestVersion().isWorkingCopy()) { if (this.dataset.getVersions().size() > 1 && this.dataset.getVersions().get(1) != null) { if (this.dataset.getVersions().get(1).isDeaccessioned()) { return false; } } } if (this.getDataset().getReleasedVersion() != null) { if (this.getFileMetadatas().size() != this.getDataset().getReleasedVersion().getFileMetadatas().size()){ return false; } else { List <DataFile> current = new ArrayList<>(); List <DataFile> previous = new ArrayList<>(); for (FileMetadata fmdc : this.getFileMetadatas()){ current.add(fmdc.getDataFile()); } for (FileMetadata fmdc : this.getDataset().getReleasedVersion().getFileMetadatas()){ previous.add(fmdc.getDataFile()); } for (DataFile fmd: current){ previous.remove(fmd); } return previous.isEmpty(); } } return true; } public void updateDefaultValuesFromTemplate(Template template) { if (!template.getDatasetFields().isEmpty()) { this.setDatasetFields(this.copyDatasetFields(template.getDatasetFields())); } if (template.getTermsOfUseAndAccess() != null) { TermsOfUseAndAccess terms = template.getTermsOfUseAndAccess().copyTermsOfUseAndAccess(); terms.setDatasetVersion(this); this.setTermsOfUseAndAccess(terms); } else { TermsOfUseAndAccess terms = new TermsOfUseAndAccess(); terms.setDatasetVersion(this); terms.setLicense(TermsOfUseAndAccess.License.CC0); terms.setDatasetVersion(this); this.setTermsOfUseAndAccess(terms); } } public void initDefaultValues() { //first clear then initialize - in case values were present // from template or user entry this.setDatasetFields(new ArrayList<>()); this.setDatasetFields(this.initDatasetFields()); TermsOfUseAndAccess terms = new TermsOfUseAndAccess(); terms.setDatasetVersion(this); terms.setLicense(TermsOfUseAndAccess.License.CC0); this.setTermsOfUseAndAccess(terms); } public DatasetVersion getMostRecentlyReleasedVersion() { if (this.isReleased()) { return this; } else { if (this.getDataset().isReleased()) { for (DatasetVersion testVersion : this.dataset.getVersions()) { if (testVersion.isReleased()) { return testVersion; } } } } return null; } public DatasetVersion getLargestMinorRelease() { if (this.getDataset().isReleased()) { for (DatasetVersion testVersion : this.dataset.getVersions()) { if (testVersion.getVersionNumber() != null && testVersion.getVersionNumber().equals(this.getVersionNumber())) { return testVersion; } } } return this; } public Dataset getDataset() { return dataset; } public void setDataset(Dataset dataset) { this.dataset = dataset; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof DatasetVersion)) { return false; } DatasetVersion other = (DatasetVersion) object; return !((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))); } @Override public String toString() { return "[DatasetVersion id:" + getId() + "]"; } public boolean isLatestVersion() { return this.equals(this.getDataset().getLatestVersion()); } public String getTitle() { String retVal = ""; for (DatasetField dsfv : this.getDatasetFields()) { if (dsfv.getDatasetFieldType().getName().equals(DatasetFieldConstant.title)) { retVal = dsfv.getDisplayValue(); } } return retVal; } public String getProductionDate() { //todo get "Production Date" from datasetfieldvalue table return "Production Date"; } /** * @return A string with the description of the dataset as-is from the * database (if available, or empty string) without passing it through * methods such as stripAllTags, sanitizeBasicHTML or similar. */ public String getDescription() { for (DatasetField dsf : this.getDatasetFields()) { if (dsf.getDatasetFieldType().getName().equals(DatasetFieldConstant.description)) { String descriptionString = ""; if (dsf.getDatasetFieldCompoundValues() != null && dsf.getDatasetFieldCompoundValues().get(0) != null) { DatasetFieldCompoundValue descriptionValue = dsf.getDatasetFieldCompoundValues().get(0); for (DatasetField subField : descriptionValue.getChildDatasetFields()) { if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.descriptionText) && !subField.isEmptyForDisplay()) { descriptionString = subField.getValue(); } } } logger.fine("pristine description: " + descriptionString); return descriptionString; } } return ""; } /** * @return Strip out all A string with the description of the dataset that * has been passed through the stripAllTags method to remove all HTML tags. */ public String getDescriptionPlainText() { return MarkupChecker.stripAllTags(getDescription()); } /** * @return A string with the description of the dataset that has been passed * through the escapeHtml method to change the "less than" sign to "&lt;" * for example. */ public String getDescriptionHtmlEscaped() { return MarkupChecker.escapeHtml(getDescription()); } public List<String[]> getDatasetContacts(){ List <String[]> retList = new ArrayList<>(); for (DatasetField dsf : this.getDatasetFields()) { Boolean addContributor = true; String contributorName = ""; String contributorAffiliation = ""; if (dsf.getDatasetFieldType().getName().equals(DatasetFieldConstant.datasetContact)) { for (DatasetFieldCompoundValue authorValue : dsf.getDatasetFieldCompoundValues()) { for (DatasetField subField : authorValue.getChildDatasetFields()) { if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.datasetContactName)) { if (subField.isEmptyForDisplay()) { addContributor = false; } contributorName = subField.getDisplayValue(); } if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.datasetContactAffiliation)) { contributorAffiliation = subField.getDisplayValue(); } } if (addContributor) { String[] datasetContributor = new String[] {contributorName, contributorAffiliation}; retList.add(datasetContributor); } } } } return retList; } public List<String[]> getDatasetProducers(){ List <String[]> retList = new ArrayList<>(); for (DatasetField dsf : this.getDatasetFields()) { Boolean addContributor = true; String contributorName = ""; String contributorAffiliation = ""; if (dsf.getDatasetFieldType().getName().equals(DatasetFieldConstant.producer)) { for (DatasetFieldCompoundValue authorValue : dsf.getDatasetFieldCompoundValues()) { for (DatasetField subField : authorValue.getChildDatasetFields()) { if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.producerName)) { if (subField.isEmptyForDisplay()) { addContributor = false; } contributorName = subField.getDisplayValue(); } if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.producerAffiliation)) { contributorAffiliation = subField.getDisplayValue(); } } if (addContributor) { String[] datasetContributor = new String[] {contributorName, contributorAffiliation}; retList.add(datasetContributor); } } } } return retList; } public List<DatasetAuthor> getDatasetAuthors() { //TODO get "List of Authors" from datasetfieldvalue table List <DatasetAuthor> retList = new ArrayList<>(); for (DatasetField dsf : this.getDatasetFields()) { Boolean addAuthor = true; if (dsf.getDatasetFieldType().getName().equals(DatasetFieldConstant.author)) { for (DatasetFieldCompoundValue authorValue : dsf.getDatasetFieldCompoundValues()) { DatasetAuthor datasetAuthor = new DatasetAuthor(); for (DatasetField subField : authorValue.getChildDatasetFields()) { if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.authorName)) { if (subField.isEmptyForDisplay()) { addAuthor = false; } datasetAuthor.setName(subField); } if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.authorAffiliation)) { datasetAuthor.setAffiliation(subField); } if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.authorIdType)){ datasetAuthor.setIdType(subField.getDisplayValue()); } if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.authorIdValue)){ datasetAuthor.setIdValue(subField.getDisplayValue()); } } if (addAuthor) { retList.add(datasetAuthor); } } } } return retList; } public List<String> getTimePeriodsCovered() { List <String> retList = new ArrayList<>(); for (DatasetField dsf : this.getDatasetFields()) { if (dsf.getDatasetFieldType().getName().equals(DatasetFieldConstant.timePeriodCovered)) { for (DatasetFieldCompoundValue timePeriodValue : dsf.getDatasetFieldCompoundValues()) { String start = ""; String end = ""; for (DatasetField subField : timePeriodValue.getChildDatasetFields()) { if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.timePeriodCoveredStart)) { if (subField.isEmptyForDisplay()) { start = null; } else { // we want to use "getValue()", as opposed to "getDisplayValue()" here - // as the latter method prepends the value with the word "Start:"! start = subField.getValue(); } } if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.timePeriodCoveredEnd)) { if (subField.isEmptyForDisplay()) { end = null; } else { // see the comment above end = subField.getValue(); } } } if (start != null && end != null) { retList.add(start + "/" + end); } } } } return retList; } /** * @return List of Strings containing the names of the authors. */ public List<String> getDatasetAuthorNames() { List<String> authors = new ArrayList<>(); for (DatasetAuthor author : this.getDatasetAuthors()) { authors.add(author.getName().getValue()); } return authors; } /** * @return List of Strings containing the dataset's subjects */ public List<String> getDatasetSubjects() { List<String> subjects = new ArrayList<>(); for (DatasetField dsf : this.getDatasetFields()) { if (dsf.getDatasetFieldType().getName().equals(DatasetFieldConstant.subject)) { subjects.addAll(dsf.getValues()); } } return subjects; } /** * @return List of Strings containing the version's Topic Classifications */ public List<String> getTopicClassifications() { return getCompoundChildFieldValues(DatasetFieldConstant.topicClassification, DatasetFieldConstant.topicClassValue); } /** * @return List of Strings containing the version's Keywords */ public List<String> getKeywords() { return getCompoundChildFieldValues(DatasetFieldConstant.keyword, DatasetFieldConstant.keywordValue); } /** * @return List of Strings containing the version's PublicationCitations */ public List<String> getPublicationCitationValues() { return getCompoundChildFieldValues(DatasetFieldConstant.publication, DatasetFieldConstant.publicationCitation); } /** * @param parentFieldName compound dataset field A (from DatasetFieldConstant.*) * @param childFieldName dataset field B, child field of A (from DatasetFieldConstant.*) * @return List of values of the child field */ public List<String> getCompoundChildFieldValues(String parentFieldName, String childFieldName) { List<String> keywords = new ArrayList<>(); for (DatasetField dsf : this.getDatasetFields()) { if (dsf.getDatasetFieldType().getName().equals(parentFieldName)) { for (DatasetFieldCompoundValue keywordFieldValue : dsf.getDatasetFieldCompoundValues()) { for (DatasetField subField : keywordFieldValue.getChildDatasetFields()) { if (subField.getDatasetFieldType().getName().equals(childFieldName)) { String keyword = subField.getValue(); // Field values should NOT be empty or, especially, null, // - in the ideal world. But as we are realizing, they CAN // be null in real life databases. So, a check, just in case: if (!StringUtil.isEmpty(keyword)) { keywords.add(subField.getValue()); } } } } } } return keywords; } public String getDatasetProducersString(){ String retVal = ""; for (DatasetField dsf : this.getDatasetFields()) { if (dsf.getDatasetFieldType().getName().equals(DatasetFieldConstant.producer)) { for (DatasetFieldCompoundValue authorValue : dsf.getDatasetFieldCompoundValues()) { for (DatasetField subField : authorValue.getChildDatasetFields()) { if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.producerName)) { if (retVal.isEmpty()){ retVal = subField.getDisplayValue(); } else { retVal += ", " + subField.getDisplayValue(); } } } } } } return retVal; } public void setDatasetAuthors(List<DatasetAuthor> authors) { // FIXME add the authors to the relevant fields } public String getCitation() { return getCitation(false); } public String getCitation(boolean html) { return new DataCitation(this).toString(html); } public Date getCitationDate() { DatasetField citationDate = getDatasetField(this.getDataset().getCitationDateDatasetFieldType()); if (citationDate != null && citationDate.getDatasetFieldType().getFieldType().equals(FieldType.DATE)){ try { return new SimpleDateFormat("yyyy").parse( citationDate.getValue() ); } catch (ParseException ex) { Logger.getLogger(DatasetVersion.class.getName()).log(Level.SEVERE, null, ex); } } return null; } /** * @param dsfType The type of DatasetField required * @return the first field of type dsfType encountered. */ public DatasetField getDatasetField(DatasetFieldType dsfType) { if (dsfType != null) { for (DatasetField dsf : this.getFlatDatasetFields()) { if (dsf.getDatasetFieldType().equals(dsfType)) { return dsf; } } } return null; } public String getDistributionDate() { //todo get dist date from datasetfieldvalue table for (DatasetField dsf : this.getDatasetFields()) { if (DatasetFieldConstant.distributionDate.equals(dsf.getDatasetFieldType().getName())) { String date = dsf.getValue(); return date; } } return null; } public String getDistributorName() { for (DatasetField dsf : this.getFlatDatasetFields()) { if (DatasetFieldConstant.distributorName.equals(dsf.getDatasetFieldType().getName())) { return dsf.getValue(); } } return null; } public String getRootDataverseNameforCitation(){ //Get root dataverse name for Citation Dataverse root = this.getDataset().getOwner(); while (root.getOwner() != null) { root = root.getOwner(); } String rootDataverseName = root.getName(); if (!StringUtil.isEmpty(rootDataverseName)) { return rootDataverseName; } else { return ""; } } public List<DatasetDistributor> getDatasetDistributors() { //todo get distributors from DatasetfieldValues return new ArrayList<>(); } public void setDatasetDistributors(List<DatasetDistributor> distributors) { //todo implement } public String getDistributorNames() { String str = ""; for (DatasetDistributor sd : this.getDatasetDistributors()) { if (str.trim().length() > 1) { str += ";"; } str += sd.getName(); } return str; } public String getAuthorsStr() { return getAuthorsStr(true); } public String getAuthorsStr(boolean affiliation) { String str = ""; for (DatasetAuthor sa : getDatasetAuthors()) { if (sa.getName() == null) { break; } if (str.trim().length() > 1) { str += "; "; } str += sa.getName().getValue(); if (affiliation) { if (sa.getAffiliation() != null) { if (!StringUtil.isEmpty(sa.getAffiliation().getValue())) { str += " (" + sa.getAffiliation().getValue() + ")"; } } } } return str; } // TODO: clean up init methods and get them to work, cascading all the way down. // right now, only work for one level of compound objects private DatasetField initDatasetField(DatasetField dsf) { if (dsf.getDatasetFieldType().isCompound()) { for (DatasetFieldCompoundValue cv : dsf.getDatasetFieldCompoundValues()) { // for each compound value; check the datasetfieldTypes associated with its type for (DatasetFieldType dsfType : dsf.getDatasetFieldType().getChildDatasetFieldTypes()) { boolean add = true; for (DatasetField subfield : cv.getChildDatasetFields()) { if (dsfType.equals(subfield.getDatasetFieldType())) { add = false; break; } } if (add) { cv.getChildDatasetFields().add(DatasetField.createNewEmptyChildDatasetField(dsfType, cv)); } } } } return dsf; } public List<DatasetField> initDatasetFields() { //retList - Return List of values List<DatasetField> retList = new ArrayList<>(); //Running into null on create new dataset if (this.getDatasetFields() != null) { for (DatasetField dsf : this.getDatasetFields()) { retList.add(initDatasetField(dsf)); } } //Test to see that there are values for // all fields in this dataset via metadata blocks //only add if not added above for (MetadataBlock mdb : this.getDataset().getOwner().getMetadataBlocks()) { for (DatasetFieldType dsfType : mdb.getDatasetFieldTypes()) { if (!dsfType.isSubField()) { boolean add = true; //don't add if already added as a val for (DatasetField dsf : retList) { if (dsfType.equals(dsf.getDatasetFieldType())) { add = false; break; } } if (add) { retList.add(DatasetField.createNewEmptyDatasetField(dsfType, this)); } } } } //sort via display order on dataset field Collections.sort(retList, DatasetField.DisplayOrder); return retList; } /** * For the current server, create link back to this Dataset * * example: * http://dvn-build.hmdc.harvard.edu/dataset.xhtml?id=72&versionId=25 * * @param serverName * @param dset * @return */ public String getReturnToDatasetURL(String serverName, Dataset dset) { if (serverName == null) { return null; } if (dset == null) { dset = this.getDataset(); if (dset == null) { // currently postgres allows this, see https://github.com/IQSS/dataverse/issues/828 return null; } } return serverName + "/dataset.xhtml?id=" + dset.getId() + "&versionId=" + this.getId(); } /* Per #3511 we are returning all users to the File Landing page If we in the future we are going to return them to the referring page we will need the getReturnToDatasetURL method and add something to the call to the api to pass the referring page and some kind of decision point in the getWorldMapDatafileInfo method in WorldMapRelatedData SEK 3/24/2017 */ public String getReturnToFilePageURL (String serverName, Dataset dset, DataFile dataFile){ if (serverName == null || dataFile == null) { return null; } if (dset == null) { dset = this.getDataset(); if (dset == null) { return null; } } return serverName + "/file.xhtml?fileId=" + dataFile.getId() + "&version=" + this.getSemanticVersion(); } public List<DatasetField> copyDatasetFields(List<DatasetField> copyFromList) { List<DatasetField> retList = new ArrayList<>(); for (DatasetField sourceDsf : copyFromList) { //the copy needs to have the current version retList.add(sourceDsf.copy(this)); } return retList; } public List<DatasetField> getFlatDatasetFields() { return getFlatDatasetFields(getDatasetFields()); } private List<DatasetField> getFlatDatasetFields(List<DatasetField> dsfList) { List<DatasetField> retList = new LinkedList<>(); for (DatasetField dsf : dsfList) { retList.add(dsf); if (dsf.getDatasetFieldType().isCompound()) { for (DatasetFieldCompoundValue compoundValue : dsf.getDatasetFieldCompoundValues()) { retList.addAll(getFlatDatasetFields(compoundValue.getChildDatasetFields())); } } } return retList; } public String getSemanticVersion() { /** * Not prepending a "v" like "v1.1" or "v2.0" because while SemVerTag * was in http://semver.org/spec/v1.0.0.html but later removed in * http://semver.org/spec/v2.0.0.html * * See also to v or not to v · Issue #1 · mojombo/semver - * https://github.com/mojombo/semver/issues/1#issuecomment-2605236 */ if (this.isReleased()) { return versionNumber + "." + minorVersionNumber; } else if (this.isDraft()){ return VersionState.DRAFT.toString(); } else if (this.isDeaccessioned()){ return versionNumber + "." + minorVersionNumber; } else{ return versionNumber + "." + minorVersionNumber; } // return VersionState.DEACCESSIONED.name(); // } else { // return "-unkwn semantic version-"; // } } public List<ConstraintViolation<DatasetField>> validateRequired() { List<ConstraintViolation<DatasetField>> returnListreturnList = new ArrayList<>(); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); for (DatasetField dsf : this.getFlatDatasetFields()) { dsf.setValidationMessage(null); // clear out any existing validation message Set<ConstraintViolation<DatasetField>> constraintViolations = validator.validate(dsf); for (ConstraintViolation<DatasetField> constraintViolation : constraintViolations) { dsf.setValidationMessage(constraintViolation.getMessage()); returnListreturnList.add(constraintViolation); break; // currently only support one message, so we can break out of the loop after the first constraint violation } } return returnListreturnList; } public Set<ConstraintViolation> validate() { Set<ConstraintViolation> returnSet = new HashSet<>(); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); for (DatasetField dsf : this.getFlatDatasetFields()) { dsf.setValidationMessage(null); // clear out any existing validation message Set<ConstraintViolation<DatasetField>> constraintViolations = validator.validate(dsf); for (ConstraintViolation<DatasetField> constraintViolation : constraintViolations) { dsf.setValidationMessage(constraintViolation.getMessage()); returnSet.add(constraintViolation); break; // currently only support one message, so we can break out of the loop after the first constraint violation } for (DatasetFieldValue dsfv : dsf.getDatasetFieldValues()) { dsfv.setValidationMessage(null); // clear out any existing validation message Set<ConstraintViolation<DatasetFieldValue>> constraintViolations2 = validator.validate(dsfv); for (ConstraintViolation<DatasetFieldValue> constraintViolation : constraintViolations2) { dsfv.setValidationMessage(constraintViolation.getMessage()); returnSet.add(constraintViolation); break; // currently only support one message, so we can break out of the loop after the first constraint violation } } } List<FileMetadata> dsvfileMetadatas = this.getFileMetadatas(); if (dsvfileMetadatas != null) { for (FileMetadata fileMetadata : dsvfileMetadatas) { Set<ConstraintViolation<FileMetadata>> constraintViolations = validator.validate(fileMetadata); if (constraintViolations.size() > 0) { // currently only support one message ConstraintViolation<FileMetadata> violation = constraintViolations.iterator().next(); /** * @todo How can we expose this more detailed message * containing the invalid value to the user? */ String message = "Constraint violation found in FileMetadata. " + violation.getMessage() + " " + "The invalid value is \"" + violation.getInvalidValue().toString() + "\"."; logger.info(message); returnSet.add(violation); break; // currently only support one message, so we can break out of the loop after the first constraint violation } } } return returnSet; } public List<WorkflowComment> getWorkflowComments() { return workflowComments; } /** * dataset publication date unpublished datasets will return an empty * string. * * @return String dataset publication date in ISO 8601 format (yyyy-MM-dd). */ public String getPublicationDateAsString() { if (DatasetVersion.VersionState.DRAFT == this.getVersionState()) { return ""; } Date rel_date = this.getReleaseTime(); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd"); String r = fmt.format(rel_date.getTime()); return r; } // TODO: Make this more performant by writing the output to the database or a file? // Agree - now that this has grown into a somewhat complex chunk of formatted // metadata - and not just a couple of values inserted into the page html - // it feels like it would make more sense to treat it as another supported // export format, that can be produced once and cached. // The problem with that is that the export subsystem assumes there is only // one metadata export in a given format per dataset (it uses the current // released (published) version. This JSON fragment is generated for a // specific released version - and we can have multiple released versions. // So something will need to be modified to accommodate this. -- L.A. public String getJsonLd() { // We show published datasets only for "datePublished" field below. if (!this.isPublished()) { return ""; } if (jsonLd != null) { return jsonLd; } JsonObjectBuilder job = Json.createObjectBuilder(); job.add("@context", "http://schema.org"); job.add("@type", "Dataset"); job.add("identifier", this.getDataset().getPersistentURL()); job.add("name", this.getTitle()); JsonArrayBuilder authors = Json.createArrayBuilder(); for (DatasetAuthor datasetAuthor : this.getDatasetAuthors()) { JsonObjectBuilder author = Json.createObjectBuilder(); String name = datasetAuthor.getName().getValue(); String affiliation = datasetAuthor.getAffiliation().getValue(); // We are aware of "givenName" and "familyName" but instead of a person it might be an organization such as "Gallup Organization". //author.add("@type", "Person"); author.add("name", name); // We are aware that the following error is thrown by https://search.google.com/structured-data/testing-tool // "The property affiliation is not recognized by Google for an object of type Thing." // Someone at Google has said this is ok. if (!StringUtil.isEmpty(affiliation)) { author.add("affiliation", affiliation); } authors.add(author); } job.add("author", authors); /** * We are aware that there is a "datePublished" field but it means "Date * of first broadcast/publication." This only makes sense for a 1.0 * version. */ String datePublished = this.getDataset().getPublicationDateFormattedYYYYMMDD(); if (datePublished != null) { job.add("datePublished", datePublished); } /** * "dateModified" is more appropriate for a version: "The date on which * the CreativeWork was most recently modified or when the item's entry * was modified within a DataFeed." */ job.add("dateModified", this.getPublicationDateAsString()); job.add("version", this.getVersionNumber().toString()); job.add("description", this.getDescriptionPlainText()); /** * "keywords" - contains subject(s), datasetkeyword(s) and topicclassification(s) * metadata fields for the version. -- L.A. * (see #2243 for details/discussion/feedback from Google) */ JsonArrayBuilder keywords = Json.createArrayBuilder(); for (String subject : this.getDatasetSubjects()) { keywords.add(subject); } for (String topic : this.getTopicClassifications()) { keywords.add(topic); } for (String keyword : this.getKeywords()) { keywords.add(keyword); } job.add("keywords", keywords); /** * citation: * (multiple) publicationCitation values, if present: */ List<String> publicationCitations = getPublicationCitationValues(); if (publicationCitations.size() > 0) { JsonArrayBuilder citation = Json.createArrayBuilder(); for (String pubCitation : publicationCitations) { //citationEntry.add("@type", "Dataset"); //citationEntry.add("text", pubCitation); citation.add(pubCitation); } job.add("citation", citation); } /** * temporalCoverage: * (if available) */ List<String> timePeriodsCovered = this.getTimePeriodsCovered(); if (timePeriodsCovered.size() > 0) { JsonArrayBuilder temporalCoverage = Json.createArrayBuilder(); for (String timePeriod : timePeriodsCovered) { temporalCoverage.add(timePeriod); } job.add("temporalCoverage", temporalCoverage); } /** * spatialCoverage (if available) * TODO * (punted, for now - see #2243) * */ /** * funder (if available) * TODO * (punted, for now - see #2243) */ job.add("schemaVersion", "https://schema.org/version/3.3"); TermsOfUseAndAccess terms = this.getTermsOfUseAndAccess(); if (terms != null) { JsonObjectBuilder license = Json.createObjectBuilder().add("@type", "Dataset"); if (TermsOfUseAndAccess.License.CC0.equals(terms.getLicense())) { license.add("text", "CC0").add("url", "https://creativecommons.org/publicdomain/zero/1.0/"); } else { String termsOfUse = terms.getTermsOfUse(); // Terms of use can be null if you create the dataset with JSON. if (termsOfUse != null) { license.add("text", termsOfUse); } } job.add("license",license); } job.add("includedInDataCatalog", Json.createObjectBuilder() .add("@type", "DataCatalog") .add("name", this.getRootDataverseNameforCitation()) .add("url", SystemConfig.getDataverseSiteUrlStatic()) ); job.add("provider", Json.createObjectBuilder() .add("@type", "Organization") .add("name", "Dataverse") ); jsonLd = job.build().toString(); return jsonLd; } }
src/main/java/edu/harvard/iq/dataverse/DatasetVersion.java
package edu.harvard.iq.dataverse; import edu.harvard.iq.dataverse.util.MarkupChecker; import edu.harvard.iq.dataverse.DatasetFieldType.FieldType; import edu.harvard.iq.dataverse.util.StringUtil; import edu.harvard.iq.dataverse.util.SystemConfig; import edu.harvard.iq.dataverse.workflows.WorkflowComment; import java.io.Serializable; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.json.Json; import javax.json.JsonArrayBuilder; import javax.json.JsonObjectBuilder; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Index; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.OrderBy; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import javax.persistence.UniqueConstraint; import javax.persistence.Version; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; /** * * @author skraffmiller */ @Entity @Table(indexes = {@Index(columnList="dataset_id")}, uniqueConstraints = @UniqueConstraint(columnNames = {"dataset_id,versionnumber,minorversionnumber"})) public class DatasetVersion implements Serializable { private static final Logger logger = Logger.getLogger(DatasetVersion.class.getCanonicalName()); /** * Convenience comparator to compare dataset versions by their version number. * The draft version is considered the latest. */ public static final Comparator<DatasetVersion> compareByVersion = new Comparator<DatasetVersion>() { @Override public int compare(DatasetVersion o1, DatasetVersion o2) { if ( o1.isDraft() ) { return o2.isDraft() ? 0 : 1; } else { return (int)Math.signum( (o1.getVersionNumber().equals(o2.getVersionNumber())) ? o1.getMinorVersionNumber() - o2.getMinorVersionNumber() : o1.getVersionNumber() - o2.getVersionNumber() ); } } }; // TODO: Determine the UI implications of various version states //IMPORTANT: If you add a new value to this enum, you will also have to modify the // StudyVersionsFragment.xhtml in order to display the correct value from a Resource Bundle public enum VersionState { DRAFT, RELEASED, ARCHIVED, DEACCESSIONED }; public enum License { NONE, CC0 } public static final int ARCHIVE_NOTE_MAX_LENGTH = 1000; public static final int VERSION_NOTE_MAX_LENGTH = 1000; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String UNF; @Version private Long version; private Long versionNumber; private Long minorVersionNumber; @Column(length = VERSION_NOTE_MAX_LENGTH) private String versionNote; /* * @todo versionState should never be null so when we are ready, uncomment * the `nullable = false` below. */ // @Column(nullable = false) @Enumerated(EnumType.STRING) private VersionState versionState; @ManyToOne private Dataset dataset; @OneToMany(mappedBy = "datasetVersion", cascade = {CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST}) @OrderBy("label") // this is not our preferred ordering, which is with the AlphaNumericComparator, but does allow the files to be grouped by category private List<FileMetadata> fileMetadatas = new ArrayList(); @OneToOne(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REMOVE}, orphanRemoval=true) @JoinColumn(name = "termsOfUseAndAccess_id") private TermsOfUseAndAccess termsOfUseAndAccess; @OneToMany(mappedBy = "datasetVersion", orphanRemoval = true, cascade = {CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST}) private List<DatasetField> datasetFields = new ArrayList(); @Temporal(value = TemporalType.TIMESTAMP) @Column( nullable=false ) private Date createTime; @Temporal(value = TemporalType.TIMESTAMP) @Column( nullable=false ) private Date lastUpdateTime; @Temporal(value = TemporalType.TIMESTAMP) private Date releaseTime; @Temporal(value = TemporalType.TIMESTAMP) private Date archiveTime; @Column(length = ARCHIVE_NOTE_MAX_LENGTH) private String archiveNote; private String deaccessionLink; @Transient private String contributorNames; @Transient private String jsonLd; @OneToMany(mappedBy="datasetVersion", cascade={CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST}) private List<DatasetVersionUser> datasetVersionUsers; // Is this the right mapping and cascading for when the workflowcomments table is being used for objects other than DatasetVersion? @OneToMany(mappedBy = "datasetVersion", cascade={CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST}) private List<WorkflowComment> workflowComments; public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getUNF() { return UNF; } public void setUNF(String UNF) { this.UNF = UNF; } /** * This is JPA's optimistic locking mechanism, and has no semantic meaning in the DV object model. * @return the object db version */ public Long getVersion() { return this.version; } public void setVersion(Long version) { } public List<FileMetadata> getFileMetadatas() { return fileMetadatas; } public List<FileMetadata> getFileMetadatasSorted() { Collections.sort(fileMetadatas, FileMetadata.compareByLabel); return fileMetadatas; } public void setFileMetadatas(List<FileMetadata> fileMetadatas) { this.fileMetadatas = fileMetadatas; } public TermsOfUseAndAccess getTermsOfUseAndAccess() { return termsOfUseAndAccess; } public void setTermsOfUseAndAccess(TermsOfUseAndAccess termsOfUseAndAccess) { this.termsOfUseAndAccess = termsOfUseAndAccess; } public List<DatasetField> getDatasetFields() { return datasetFields; } /** * Sets the dataset fields for this version. Also updates the fields to * have @{code this} as their dataset version. * @param datasetFields */ public void setDatasetFields(List<DatasetField> datasetFields) { for ( DatasetField dsf : datasetFields ) { dsf.setDatasetVersion(this); } this.datasetFields = datasetFields; } /** * The only time a dataset can be in review is when it is in draft. * @return if the dataset is being reviewed */ public boolean isInReview() { if (versionState != null && versionState.equals(VersionState.DRAFT)) { return getDataset().isLockedFor(DatasetLock.Reason.InReview); } else { return false; } } public Date getArchiveTime() { return archiveTime; } public void setArchiveTime(Date archiveTime) { this.archiveTime = archiveTime; } public String getArchiveNote() { return archiveNote; } public void setArchiveNote(String note) { // @todo should this be using bean validation for trsting note length? if (note != null && note.length() > ARCHIVE_NOTE_MAX_LENGTH) { throw new IllegalArgumentException("Error setting archiveNote: String length is greater than maximum (" + ARCHIVE_NOTE_MAX_LENGTH + ")." + " StudyVersion id=" + id + ", archiveNote=" + note); } this.archiveNote = note; } public String getDeaccessionLink() { return deaccessionLink; } public void setDeaccessionLink(String deaccessionLink) { this.deaccessionLink = deaccessionLink; } public GlobalId getDeaccessionLinkAsGlobalId() { return new GlobalId(deaccessionLink); } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getLastUpdateTime() { return lastUpdateTime; } public void setLastUpdateTime(Date lastUpdateTime) { if (createTime == null) { createTime = lastUpdateTime; } this.lastUpdateTime = lastUpdateTime; } public String getVersionDate() { if (this.lastUpdateTime == null){ return null; } return new SimpleDateFormat("MMMM d, yyyy").format(lastUpdateTime); } public String getVersionYear() { return new SimpleDateFormat("yyyy").format(lastUpdateTime); } public Date getReleaseTime() { return releaseTime; } public void setReleaseTime(Date releaseTime) { this.releaseTime = releaseTime; } public List<DatasetVersionUser> getDatasetVersionUsers() { return datasetVersionUsers; } public void setUserDatasets(List<DatasetVersionUser> datasetVersionUsers) { this.datasetVersionUsers = datasetVersionUsers; } public List<String> getVersionContributorIdentifiers() { if (this.getDatasetVersionUsers() == null) { return Collections.emptyList(); } List<String> ret = new LinkedList<>(); for (DatasetVersionUser contributor : this.getDatasetVersionUsers()) { ret.add(contributor.getAuthenticatedUser().getIdentifier()); } return ret; } public String getContributorNames() { return contributorNames; } public void setContributorNames(String contributorNames) { this.contributorNames = contributorNames; } public String getVersionNote() { return versionNote; } public DatasetVersionDifference getDefaultVersionDifference() { // if version is deaccessioned ignore it for differences purposes int index = 0; int size = this.getDataset().getVersions().size(); if (this.isDeaccessioned()) { return null; } for (DatasetVersion dsv : this.getDataset().getVersions()) { if (this.equals(dsv)) { if ((index + 1) <= (size - 1)) { for (DatasetVersion dvTest : this.getDataset().getVersions().subList(index + 1, size)) { if (!dvTest.isDeaccessioned()) { DatasetVersionDifference dvd = new DatasetVersionDifference(this, dvTest); return dvd; } } } } index++; } return null; } public VersionState getPriorVersionState() { int index = 0; int size = this.getDataset().getVersions().size(); if (this.isDeaccessioned()) { return null; } for (DatasetVersion dsv : this.getDataset().getVersions()) { if (this.equals(dsv)) { if ((index + 1) <= (size - 1)) { for (DatasetVersion dvTest : this.getDataset().getVersions().subList(index + 1, size)) { return dvTest.getVersionState(); } } } index++; } return null; } public void setVersionNote(String note) { if (note != null && note.length() > VERSION_NOTE_MAX_LENGTH) { throw new IllegalArgumentException("Error setting versionNote: String length is greater than maximum (" + VERSION_NOTE_MAX_LENGTH + ")." + " StudyVersion id=" + id + ", versionNote=" + note); } this.versionNote = note; } public Long getVersionNumber() { return versionNumber; } public void setVersionNumber(Long versionNumber) { this.versionNumber = versionNumber; } public Long getMinorVersionNumber() { return minorVersionNumber; } public void setMinorVersionNumber(Long minorVersionNumber) { this.minorVersionNumber = minorVersionNumber; } public String getFriendlyVersionNumber(){ if (this.isDraft()) { return "DRAFT"; } else { return versionNumber.toString() + "." + minorVersionNumber.toString(); } } public VersionState getVersionState() { return versionState; } public void setVersionState(VersionState versionState) { this.versionState = versionState; } public boolean isReleased() { return versionState.equals(VersionState.RELEASED); } public boolean isPublished() { return isReleased(); } public boolean isDraft() { return versionState.equals(VersionState.DRAFT); } public boolean isWorkingCopy() { return versionState.equals(VersionState.DRAFT); } public boolean isArchived() { return versionState.equals(VersionState.ARCHIVED); } public boolean isDeaccessioned() { return versionState.equals(VersionState.DEACCESSIONED); } public boolean isRetiredCopy() { return (versionState.equals(VersionState.ARCHIVED) || versionState.equals(VersionState.DEACCESSIONED)); } public boolean isMinorUpdate() { if (this.dataset.getLatestVersion().isWorkingCopy()) { if (this.dataset.getVersions().size() > 1 && this.dataset.getVersions().get(1) != null) { if (this.dataset.getVersions().get(1).isDeaccessioned()) { return false; } } } if (this.getDataset().getReleasedVersion() != null) { if (this.getFileMetadatas().size() != this.getDataset().getReleasedVersion().getFileMetadatas().size()){ return false; } else { List <DataFile> current = new ArrayList<>(); List <DataFile> previous = new ArrayList<>(); for (FileMetadata fmdc : this.getFileMetadatas()){ current.add(fmdc.getDataFile()); } for (FileMetadata fmdc : this.getDataset().getReleasedVersion().getFileMetadatas()){ previous.add(fmdc.getDataFile()); } for (DataFile fmd: current){ previous.remove(fmd); } return previous.isEmpty(); } } return true; } public void updateDefaultValuesFromTemplate(Template template) { if (!template.getDatasetFields().isEmpty()) { this.setDatasetFields(this.copyDatasetFields(template.getDatasetFields())); } if (template.getTermsOfUseAndAccess() != null) { TermsOfUseAndAccess terms = template.getTermsOfUseAndAccess().copyTermsOfUseAndAccess(); terms.setDatasetVersion(this); this.setTermsOfUseAndAccess(terms); } else { TermsOfUseAndAccess terms = new TermsOfUseAndAccess(); terms.setDatasetVersion(this); terms.setLicense(TermsOfUseAndAccess.License.CC0); terms.setDatasetVersion(this); this.setTermsOfUseAndAccess(terms); } } public void initDefaultValues() { //first clear then initialize - in case values were present // from template or user entry this.setDatasetFields(new ArrayList<>()); this.setDatasetFields(this.initDatasetFields()); TermsOfUseAndAccess terms = new TermsOfUseAndAccess(); terms.setDatasetVersion(this); terms.setLicense(TermsOfUseAndAccess.License.CC0); this.setTermsOfUseAndAccess(terms); } public DatasetVersion getMostRecentlyReleasedVersion() { if (this.isReleased()) { return this; } else { if (this.getDataset().isReleased()) { for (DatasetVersion testVersion : this.dataset.getVersions()) { if (testVersion.isReleased()) { return testVersion; } } } } return null; } public DatasetVersion getLargestMinorRelease() { if (this.getDataset().isReleased()) { for (DatasetVersion testVersion : this.dataset.getVersions()) { if (testVersion.getVersionNumber() != null && testVersion.getVersionNumber().equals(this.getVersionNumber())) { return testVersion; } } } return this; } public Dataset getDataset() { return dataset; } public void setDataset(Dataset dataset) { this.dataset = dataset; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof DatasetVersion)) { return false; } DatasetVersion other = (DatasetVersion) object; return !((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))); } @Override public String toString() { return "[DatasetVersion id:" + getId() + "]"; } public boolean isLatestVersion() { return this.equals(this.getDataset().getLatestVersion()); } public String getTitle() { String retVal = ""; for (DatasetField dsfv : this.getDatasetFields()) { if (dsfv.getDatasetFieldType().getName().equals(DatasetFieldConstant.title)) { retVal = dsfv.getDisplayValue(); } } return retVal; } public String getProductionDate() { //todo get "Production Date" from datasetfieldvalue table return "Production Date"; } /** * @return A string with the description of the dataset as-is from the * database (if available, or empty string) without passing it through * methods such as stripAllTags, sanitizeBasicHTML or similar. */ public String getDescription() { for (DatasetField dsf : this.getDatasetFields()) { if (dsf.getDatasetFieldType().getName().equals(DatasetFieldConstant.description)) { String descriptionString = ""; if (dsf.getDatasetFieldCompoundValues() != null && dsf.getDatasetFieldCompoundValues().get(0) != null) { DatasetFieldCompoundValue descriptionValue = dsf.getDatasetFieldCompoundValues().get(0); for (DatasetField subField : descriptionValue.getChildDatasetFields()) { if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.descriptionText) && !subField.isEmptyForDisplay()) { descriptionString = subField.getValue(); } } } logger.fine("pristine description: " + descriptionString); return descriptionString; } } return ""; } /** * @return Strip out all A string with the description of the dataset that * has been passed through the stripAllTags method to remove all HTML tags. */ public String getDescriptionPlainText() { return MarkupChecker.stripAllTags(getDescription()); } /** * @return A string with the description of the dataset that has been passed * through the escapeHtml method to change the "less than" sign to "&lt;" * for example. */ public String getDescriptionHtmlEscaped() { return MarkupChecker.escapeHtml(getDescription()); } public List<String[]> getDatasetContacts(){ List <String[]> retList = new ArrayList<>(); for (DatasetField dsf : this.getDatasetFields()) { Boolean addContributor = true; String contributorName = ""; String contributorAffiliation = ""; if (dsf.getDatasetFieldType().getName().equals(DatasetFieldConstant.datasetContact)) { for (DatasetFieldCompoundValue authorValue : dsf.getDatasetFieldCompoundValues()) { for (DatasetField subField : authorValue.getChildDatasetFields()) { if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.datasetContactName)) { if (subField.isEmptyForDisplay()) { addContributor = false; } contributorName = subField.getDisplayValue(); } if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.datasetContactAffiliation)) { contributorAffiliation = subField.getDisplayValue(); } } if (addContributor) { String[] datasetContributor = new String[] {contributorName, contributorAffiliation}; retList.add(datasetContributor); } } } } return retList; } public List<String[]> getDatasetProducers(){ List <String[]> retList = new ArrayList<>(); for (DatasetField dsf : this.getDatasetFields()) { Boolean addContributor = true; String contributorName = ""; String contributorAffiliation = ""; if (dsf.getDatasetFieldType().getName().equals(DatasetFieldConstant.producer)) { for (DatasetFieldCompoundValue authorValue : dsf.getDatasetFieldCompoundValues()) { for (DatasetField subField : authorValue.getChildDatasetFields()) { if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.producerName)) { if (subField.isEmptyForDisplay()) { addContributor = false; } contributorName = subField.getDisplayValue(); } if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.producerAffiliation)) { contributorAffiliation = subField.getDisplayValue(); } } if (addContributor) { String[] datasetContributor = new String[] {contributorName, contributorAffiliation}; retList.add(datasetContributor); } } } } return retList; } public List<DatasetAuthor> getDatasetAuthors() { //TODO get "List of Authors" from datasetfieldvalue table List <DatasetAuthor> retList = new ArrayList<>(); for (DatasetField dsf : this.getDatasetFields()) { Boolean addAuthor = true; if (dsf.getDatasetFieldType().getName().equals(DatasetFieldConstant.author)) { for (DatasetFieldCompoundValue authorValue : dsf.getDatasetFieldCompoundValues()) { DatasetAuthor datasetAuthor = new DatasetAuthor(); for (DatasetField subField : authorValue.getChildDatasetFields()) { if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.authorName)) { if (subField.isEmptyForDisplay()) { addAuthor = false; } datasetAuthor.setName(subField); } if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.authorAffiliation)) { datasetAuthor.setAffiliation(subField); } if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.authorIdType)){ datasetAuthor.setIdType(subField.getDisplayValue()); } if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.authorIdValue)){ datasetAuthor.setIdValue(subField.getDisplayValue()); } } if (addAuthor) { retList.add(datasetAuthor); } } } } return retList; } public List<String> getTimePeriodsCovered() { List <String> retList = new ArrayList<>(); for (DatasetField dsf : this.getDatasetFields()) { if (dsf.getDatasetFieldType().getName().equals(DatasetFieldConstant.timePeriodCovered)) { for (DatasetFieldCompoundValue timePeriodValue : dsf.getDatasetFieldCompoundValues()) { String start = ""; String end = ""; for (DatasetField subField : timePeriodValue.getChildDatasetFields()) { if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.timePeriodCoveredStart)) { if (subField.isEmptyForDisplay()) { start = null; } else { // we want to use "getValue()", as opposed to "getDisplayValue()" here - // as the latter method prepends the value with the word "Start:"! start = subField.getValue(); } } if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.timePeriodCoveredEnd)) { if (subField.isEmptyForDisplay()) { end = null; } else { // see the comment above end = subField.getValue(); } } } if (start != null && end != null) { retList.add(start + "/" + end); } } } } return retList; } /** * @return List of Strings containing the names of the authors. */ public List<String> getDatasetAuthorNames() { List<String> authors = new ArrayList<>(); for (DatasetAuthor author : this.getDatasetAuthors()) { authors.add(author.getName().getValue()); } return authors; } /** * @return List of Strings containing the dataset's subjects */ public List<String> getDatasetSubjects() { List<String> subjects = new ArrayList<>(); for (DatasetField dsf : this.getDatasetFields()) { if (dsf.getDatasetFieldType().getName().equals(DatasetFieldConstant.subject)) { subjects.addAll(dsf.getValues()); } } return subjects; } /** * @return List of Strings containing the version's Topic Classifications */ public List<String> getTopicClassifications() { return getCompoundChildFieldValues(DatasetFieldConstant.topicClassification, DatasetFieldConstant.topicClassValue); } /** * @return List of Strings containing the version's Keywords */ public List<String> getKeywords() { return getCompoundChildFieldValues(DatasetFieldConstant.keyword, DatasetFieldConstant.keywordValue); } /** * @return List of Strings containing the version's PublicationCitations */ public List<String> getPublicationCitationValues() { return getCompoundChildFieldValues(DatasetFieldConstant.publication, DatasetFieldConstant.publicationCitation); } /** * @param parentFieldName compound dataset field A (from DatasetFieldConstant.*) * @param childFieldName dataset field B, child field of A (from DatasetFieldConstant.*) * @return List of values of the child field */ public List<String> getCompoundChildFieldValues(String parentFieldName, String childFieldName) { List<String> keywords = new ArrayList<>(); for (DatasetField dsf : this.getDatasetFields()) { if (dsf.getDatasetFieldType().getName().equals(parentFieldName)) { for (DatasetFieldCompoundValue keywordFieldValue : dsf.getDatasetFieldCompoundValues()) { for (DatasetField subField : keywordFieldValue.getChildDatasetFields()) { if (subField.getDatasetFieldType().getName().equals(childFieldName)) { String keyword = subField.getValue(); // Field values should NOT be empty or, especially, null, // - in the ideal world. But as we are realizing, they CAN // be null in real life databases. So, a check, just in case: if (!StringUtil.isEmpty(keyword)) { keywords.add(subField.getValue()); } } } } } } return keywords; } public String getDatasetProducersString(){ String retVal = ""; for (DatasetField dsf : this.getDatasetFields()) { if (dsf.getDatasetFieldType().getName().equals(DatasetFieldConstant.producer)) { for (DatasetFieldCompoundValue authorValue : dsf.getDatasetFieldCompoundValues()) { for (DatasetField subField : authorValue.getChildDatasetFields()) { if (subField.getDatasetFieldType().getName().equals(DatasetFieldConstant.producerName)) { if (retVal.isEmpty()){ retVal = subField.getDisplayValue(); } else { retVal += ", " + subField.getDisplayValue(); } } } } } } return retVal; } public void setDatasetAuthors(List<DatasetAuthor> authors) { // FIXME add the authors to the relevant fields } public String getCitation() { return getCitation(false); } public String getCitation(boolean html) { return new DataCitation(this).toString(html); } public Date getCitationDate() { DatasetField citationDate = getDatasetField(this.getDataset().getCitationDateDatasetFieldType()); if (citationDate != null && citationDate.getDatasetFieldType().getFieldType().equals(FieldType.DATE)){ try { return new SimpleDateFormat("yyyy").parse( citationDate.getValue() ); } catch (ParseException ex) { Logger.getLogger(DatasetVersion.class.getName()).log(Level.SEVERE, null, ex); } } return null; } /** * @param dsfType The type of DatasetField required * @return the first field of type dsfType encountered. */ public DatasetField getDatasetField(DatasetFieldType dsfType) { if (dsfType != null) { for (DatasetField dsf : this.getFlatDatasetFields()) { if (dsf.getDatasetFieldType().equals(dsfType)) { return dsf; } } } return null; } public String getDistributionDate() { //todo get dist date from datasetfieldvalue table for (DatasetField dsf : this.getDatasetFields()) { if (DatasetFieldConstant.distributionDate.equals(dsf.getDatasetFieldType().getName())) { String date = dsf.getValue(); return date; } } return null; } public String getDistributorName() { for (DatasetField dsf : this.getFlatDatasetFields()) { if (DatasetFieldConstant.distributorName.equals(dsf.getDatasetFieldType().getName())) { return dsf.getValue(); } } return null; } public String getRootDataverseNameforCitation(){ //Get root dataverse name for Citation Dataverse root = this.getDataset().getOwner(); while (root.getOwner() != null) { root = root.getOwner(); } String rootDataverseName = root.getName(); if (!StringUtil.isEmpty(rootDataverseName)) { return rootDataverseName; } else { return ""; } } public List<DatasetDistributor> getDatasetDistributors() { //todo get distributors from DatasetfieldValues return new ArrayList<>(); } public void setDatasetDistributors(List<DatasetDistributor> distributors) { //todo implement } public String getDistributorNames() { String str = ""; for (DatasetDistributor sd : this.getDatasetDistributors()) { if (str.trim().length() > 1) { str += ";"; } str += sd.getName(); } return str; } public String getAuthorsStr() { return getAuthorsStr(true); } public String getAuthorsStr(boolean affiliation) { String str = ""; for (DatasetAuthor sa : getDatasetAuthors()) { if (sa.getName() == null) { break; } if (str.trim().length() > 1) { str += "; "; } str += sa.getName().getValue(); if (affiliation) { if (sa.getAffiliation() != null) { if (!StringUtil.isEmpty(sa.getAffiliation().getValue())) { str += " (" + sa.getAffiliation().getValue() + ")"; } } } } return str; } // TODO: clean up init methods and get them to work, cascading all the way down. // right now, only work for one level of compound objects private DatasetField initDatasetField(DatasetField dsf) { if (dsf.getDatasetFieldType().isCompound()) { for (DatasetFieldCompoundValue cv : dsf.getDatasetFieldCompoundValues()) { // for each compound value; check the datasetfieldTypes associated with its type for (DatasetFieldType dsfType : dsf.getDatasetFieldType().getChildDatasetFieldTypes()) { boolean add = true; for (DatasetField subfield : cv.getChildDatasetFields()) { if (dsfType.equals(subfield.getDatasetFieldType())) { add = false; break; } } if (add) { cv.getChildDatasetFields().add(DatasetField.createNewEmptyChildDatasetField(dsfType, cv)); } } } } return dsf; } public List<DatasetField> initDatasetFields() { //retList - Return List of values List<DatasetField> retList = new ArrayList<>(); //Running into null on create new dataset if (this.getDatasetFields() != null) { for (DatasetField dsf : this.getDatasetFields()) { retList.add(initDatasetField(dsf)); } } //Test to see that there are values for // all fields in this dataset via metadata blocks //only add if not added above for (MetadataBlock mdb : this.getDataset().getOwner().getMetadataBlocks()) { for (DatasetFieldType dsfType : mdb.getDatasetFieldTypes()) { if (!dsfType.isSubField()) { boolean add = true; //don't add if already added as a val for (DatasetField dsf : retList) { if (dsfType.equals(dsf.getDatasetFieldType())) { add = false; break; } } if (add) { retList.add(DatasetField.createNewEmptyDatasetField(dsfType, this)); } } } } //sort via display order on dataset field Collections.sort(retList, DatasetField.DisplayOrder); return retList; } /** * For the current server, create link back to this Dataset * * example: * http://dvn-build.hmdc.harvard.edu/dataset.xhtml?id=72&versionId=25 * * @param serverName * @param dset * @return */ public String getReturnToDatasetURL(String serverName, Dataset dset) { if (serverName == null) { return null; } if (dset == null) { dset = this.getDataset(); if (dset == null) { // currently postgres allows this, see https://github.com/IQSS/dataverse/issues/828 return null; } } return serverName + "/dataset.xhtml?id=" + dset.getId() + "&versionId=" + this.getId(); } /* Per #3511 we are returning all users to the File Landing page If we in the future we are going to return them to the referring page we will need the getReturnToDatasetURL method and add something to the call to the api to pass the referring page and some kind of decision point in the getWorldMapDatafileInfo method in WorldMapRelatedData SEK 3/24/2017 */ public String getReturnToFilePageURL (String serverName, Dataset dset, DataFile dataFile){ if (serverName == null || dataFile == null) { return null; } if (dset == null) { dset = this.getDataset(); if (dset == null) { return null; } } return serverName + "/file.xhtml?fileId=" + dataFile.getId() + "&version=" + this.getSemanticVersion(); } public List<DatasetField> copyDatasetFields(List<DatasetField> copyFromList) { List<DatasetField> retList = new ArrayList<>(); for (DatasetField sourceDsf : copyFromList) { //the copy needs to have the current version retList.add(sourceDsf.copy(this)); } return retList; } public List<DatasetField> getFlatDatasetFields() { return getFlatDatasetFields(getDatasetFields()); } private List<DatasetField> getFlatDatasetFields(List<DatasetField> dsfList) { List<DatasetField> retList = new LinkedList<>(); for (DatasetField dsf : dsfList) { retList.add(dsf); if (dsf.getDatasetFieldType().isCompound()) { for (DatasetFieldCompoundValue compoundValue : dsf.getDatasetFieldCompoundValues()) { retList.addAll(getFlatDatasetFields(compoundValue.getChildDatasetFields())); } } } return retList; } public String getSemanticVersion() { /** * Not prepending a "v" like "v1.1" or "v2.0" because while SemVerTag * was in http://semver.org/spec/v1.0.0.html but later removed in * http://semver.org/spec/v2.0.0.html * * See also to v or not to v · Issue #1 · mojombo/semver - * https://github.com/mojombo/semver/issues/1#issuecomment-2605236 */ if (this.isReleased()) { return versionNumber + "." + minorVersionNumber; } else if (this.isDraft()){ return VersionState.DRAFT.toString(); } else if (this.isDeaccessioned()){ return versionNumber + "." + minorVersionNumber; } else{ return versionNumber + "." + minorVersionNumber; } // return VersionState.DEACCESSIONED.name(); // } else { // return "-unkwn semantic version-"; // } } public List<ConstraintViolation<DatasetField>> validateRequired() { List<ConstraintViolation<DatasetField>> returnListreturnList = new ArrayList<>(); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); for (DatasetField dsf : this.getFlatDatasetFields()) { dsf.setValidationMessage(null); // clear out any existing validation message Set<ConstraintViolation<DatasetField>> constraintViolations = validator.validate(dsf); for (ConstraintViolation<DatasetField> constraintViolation : constraintViolations) { dsf.setValidationMessage(constraintViolation.getMessage()); returnListreturnList.add(constraintViolation); break; // currently only support one message, so we can break out of the loop after the first constraint violation } } return returnListreturnList; } public Set<ConstraintViolation> validate() { Set<ConstraintViolation> returnSet = new HashSet<>(); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); for (DatasetField dsf : this.getFlatDatasetFields()) { dsf.setValidationMessage(null); // clear out any existing validation message Set<ConstraintViolation<DatasetField>> constraintViolations = validator.validate(dsf); for (ConstraintViolation<DatasetField> constraintViolation : constraintViolations) { dsf.setValidationMessage(constraintViolation.getMessage()); returnSet.add(constraintViolation); break; // currently only support one message, so we can break out of the loop after the first constraint violation } for (DatasetFieldValue dsfv : dsf.getDatasetFieldValues()) { dsfv.setValidationMessage(null); // clear out any existing validation message Set<ConstraintViolation<DatasetFieldValue>> constraintViolations2 = validator.validate(dsfv); for (ConstraintViolation<DatasetFieldValue> constraintViolation : constraintViolations2) { dsfv.setValidationMessage(constraintViolation.getMessage()); returnSet.add(constraintViolation); break; // currently only support one message, so we can break out of the loop after the first constraint violation } } } List<FileMetadata> dsvfileMetadatas = this.getFileMetadatas(); if (dsvfileMetadatas != null) { for (FileMetadata fileMetadata : dsvfileMetadatas) { Set<ConstraintViolation<FileMetadata>> constraintViolations = validator.validate(fileMetadata); if (constraintViolations.size() > 0) { // currently only support one message ConstraintViolation<FileMetadata> violation = constraintViolations.iterator().next(); /** * @todo How can we expose this more detailed message * containing the invalid value to the user? */ String message = "Constraint violation found in FileMetadata. " + violation.getMessage() + " " + "The invalid value is \"" + violation.getInvalidValue().toString() + "\"."; logger.info(message); returnSet.add(violation); break; // currently only support one message, so we can break out of the loop after the first constraint violation } } } return returnSet; } public List<WorkflowComment> getWorkflowComments() { return workflowComments; } /** * dataset publication date unpublished datasets will return an empty * string. * * @return String dataset publication date in ISO 8601 format (yyyy-MM-dd). */ public String getPublicationDateAsString() { if (DatasetVersion.VersionState.DRAFT == this.getVersionState()) { return ""; } Date rel_date = this.getReleaseTime(); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd"); String r = fmt.format(rel_date.getTime()); return r; } // TODO: Make this more performant by writing the output to the database or a file? // Agree - now that this has grown into a somewhat complex chunk of formatted // metadata - and not just a couple of values inserted into the page html - // it feels like it would make more sense to treat it as another supported // export format, that can be produced once and cached. // The problem with that is that the export subsystem assumes there is only // one metadata export in a given format per dataset (it uses the current // released (published) version. This JSON fragment is generated for a // specific released version - and we can have multiple released versions. // So something will need to be modified to accommodate this. -- L.A. public String getJsonLd() { // We show published datasets only for "datePublished" field below. if (!this.isPublished()) { return ""; } if (jsonLd != null) { return jsonLd; } JsonObjectBuilder job = Json.createObjectBuilder(); job.add("@context", "http://schema.org"); job.add("@type", "Dataset"); job.add("identifier", this.getDataset().getPersistentURL()); job.add("name", this.getTitle()); JsonArrayBuilder authors = Json.createArrayBuilder(); for (DatasetAuthor datasetAuthor : this.getDatasetAuthors()) { JsonObjectBuilder author = Json.createObjectBuilder(); String name = datasetAuthor.getName().getValue(); String affiliation = datasetAuthor.getAffiliation().getValue(); // We are aware of "givenName" and "familyName" but instead of a person it might be an organization such as "Gallup Organization". //author.add("@type", "Person"); author.add("name", name); // We are aware that the following error is thrown by https://search.google.com/structured-data/testing-tool // "The property affiliation is not recognized by Google for an object of type Thing." // Someone at Google has said this is ok. if (!StringUtil.isEmpty(affiliation)) { author.add("affiliation", affiliation); } authors.add(author); } job.add("author", authors); /** * We are aware that there is a "datePublished" field but it means "Date * of first broadcast/publication." This only makes sense for a 1.0 * version. */ String datePublished = this.getDataset().getPublicationDateFormattedYYYYMMDD(); if (datePublished != null) { job.add("datePublished", datePublished); } /** * "dateModified" is more appropriate for a version: "The date on which * the CreativeWork was most recently modified or when the item's entry * was modified within a DataFeed." */ job.add("dateModified", this.getPublicationDateAsString()); job.add("version", this.getVersionNumber().toString()); job.add("description", this.getDescriptionPlainText()); /** * "keywords" - contains subject(s), datasetkeyword(s) and topicclassification(s) * metadata fields for the version. -- L.A. * (see #2243 for details/discussion/feedback from Google) */ JsonArrayBuilder keywords = Json.createArrayBuilder(); for (String subject : this.getDatasetSubjects()) { keywords.add(subject); } for (String topic : this.getTopicClassifications()) { keywords.add(topic); } for (String keyword : this.getKeywords()) { keywords.add(keyword); } job.add("keywords", keywords); /** * citation: * (multiple) publicationCitation values, if present: */ List<String> publicationCitations = getPublicationCitationValues(); if (publicationCitations.size() > 0) { JsonArrayBuilder citation = Json.createArrayBuilder(); for (String pubCitation : publicationCitations) { //citationEntry.add("@type", "Dataset"); //citationEntry.add("text", pubCitation); citation.add(pubCitation); } job.add("citation", citation); } /** * temporalCoverage: * (if available) */ List<String> timePeriodsCovered = this.getTimePeriodsCovered(); if (timePeriodsCovered.size() > 0) { JsonArrayBuilder temporalCoverage = Json.createArrayBuilder(); for (String timePeriod : timePeriodsCovered) { temporalCoverage.add(timePeriod); } job.add("temporalCoverage", temporalCoverage); } /** * spatialCoverage (if available) * TODO * (punted, for now - see #2243) * */ /** * funder (if available) * TODO * (punted, for now - see #2243) */ job.add("schemaVersion", "https://schema.org/version/3.3"); TermsOfUseAndAccess terms = this.getTermsOfUseAndAccess(); if (terms != null) { JsonObjectBuilder license = Json.createObjectBuilder().add("@type", "Dataset"); if (TermsOfUseAndAccess.License.CC0.equals(terms.getLicense())) { license.add("text", "CC0").add("url", "https://creativecommons.org/publicdomain/zero/1.0/"); } else { license.add("text", terms.getTermsOfUse()); } job.add("license",license); } job.add("includedInDataCatalog", Json.createObjectBuilder() .add("@type", "DataCatalog") .add("name", this.getRootDataverseNameforCitation()) .add("url", SystemConfig.getDataverseSiteUrlStatic()) ); job.add("provider", Json.createObjectBuilder() .add("@type", "Organization") .add("name", "Dataverse") ); jsonLd = job.build().toString(); return jsonLd; } }
guard against null terms.getTermsOfUse() #3700
src/main/java/edu/harvard/iq/dataverse/DatasetVersion.java
guard against null terms.getTermsOfUse() #3700
Java
apache-2.0
1f15edb3be5e4c47507c8e454532dfcb08b93b38
0
kingster/Ape-Java-Client
package com.cogxio.apeclient; import net.sf.json.JSONObject; import org.java_websocket.WebSocketImpl; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URI; import java.util.Arrays; import java.util.Random; /** * Created by kingster on 31/05/14. */ public class ApeClientTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testClient() throws Exception { WebSocketImpl.DEBUG = false; final Logger Log = LoggerFactory.getLogger(ApeClientTest.class); String wsHost = "ws://ape.ptejada.com:80/6/"; URI uri = new URI(wsHost); String username = ("user_"+ new Random().nextInt(100)).replace("-",""); ApeClient apeClient = new ApeClient(uri) { @Override public void action_onMessage(JSONObject jsonObject) { Log.info(jsonObject.toString()); reply("Hey Boss!"); } }; apeClient.publishKey = "password"; apeClient.connectBlocking(); Log.info("Connected Successfully"); apeClient.startSession(username); apeClient.waitJoinedBlocking(); Log.info("Joined as "+ username); apeClient.join(Arrays.asList("music")); //apeClient.sendMessage("music", "awesome", "message"); Thread.sleep(2000); apeClient.sendMessage("music", "awesome", "message"); Thread.sleep(10000); //keep alive 10s. } }
src/test/java/com/cogxio/apeclient/ApeClientTest.java
package com.cogxio.apeclient; import net.sf.json.JSONObject; import org.java_websocket.WebSocketImpl; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URI; import java.util.Arrays; import java.util.Random; /** * Created by kingster on 31/05/14. */ public class ApeClientTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testClient() throws Exception { WebSocketImpl.DEBUG = false; final Logger Log = LoggerFactory.getLogger(ApeClientTest.class); String wsHost = "ws://ape.ptejada.com:80/6/"; URI uri = new URI(wsHost); String username = ("user_"+ new Random().nextInt(100)).replace("-",""); ApeClient apeClient = new ApeClient(uri) { @Override public void action_onMessage(JSONObject jsonObject) { Log.info(jsonObject.toString()); reply("Hey Boss!"); } }; apeClient.publishKey = "password"; apeClient.connectBlocking(); Log.info("Connected Successfully"); apeClient.startSession(username); apeClient.waitJoinedBlocking(); Log.info("Joined as "+ username); apeClient.join(Arrays.asList("music")); //apeClient.sendMessage("music", "awesome", "message"); Thread.sleep(10000); //keep alive 10s. } }
adding sendMessage ( inline push tests)
src/test/java/com/cogxio/apeclient/ApeClientTest.java
adding sendMessage ( inline push tests)
Java
apache-2.0
00323ae5ce64485362baef5a2fe22b50c430b97c
0
GrayTurtle/codeu_project_2017,GrayTurtle/codeu_project_2017
package codeu.chat.client.simplegui; import codeu.chat.client.ClientUser; import javafx.application.Application; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.stage.Stage; import javafx.scene.text.*; import javafx.collections.*; import javafx.scene.input.MouseEvent; import javafx.scene.control.Alert.AlertType; import codeu.chat.client.ClientContext; import codeu.chat.client.Controller; import codeu.chat.common.ConversationSummary; import codeu.chat.common.User; import codeu.chat.common.Message; import codeu.chat.client.View; import codeu.chat.util.Logger; import codeu.chat.util.Uuid; public final class ChatGuiFX extends Application { private final static Logger.Log LOG = Logger.newLog(ChatGuiFX.class); private static final double WINDOW_WIDTH = 1000; private static final double WINDOW_HEIGHT = 500; private static final String SIGNIN_ERROR_MESSAGE = "Your username or password does not match. Have you signed up yet?"; private static final String SIGNUP_ERROR_MESSAGE = "Sorry, that username already exists. Please choose a different one."; private static final String BADCHAR_ERROR_MESSAGE = "Usernames and passwords can only be composed of letters and numbers, no special characters."; // both page vars //private ClientContext clientContext; /* **This is something to think about** // TODO: split the login & main screens into separate methods public void run(String[] args) { buildLoginScene(); buildMainScene(); } */ // login page vars // Holds the scene that user is currently viewing private Stage thestage; // Scenes to hold all the elements for each page private Scene signInScene, mainScene; // Takes input for username and password for sign in/up private TextField userInput; private PasswordField passInput; // Displays error messages for when the user is not sign in or has not selected a convo private Label errorLabel; // variable that has the current state of the client (current user, conversation, etc) private static ClientContext clientContext; // title of current/selected conversation private Text chatTitle; // these hold the conversations to be displayed on the right panel private ObservableList<String> convoList; private ListView<String> conversations; // these hold the messages of a selected conversation to be displayed in the middle panel private ObservableList<String> messageList; private ListView<String> messages; // these hold the users to be displayed on the left panel private ObservableList<String> usersList; private ListView<String> users; // field for the input of messages into a conversation private TextField input; public void setContext(Controller controller, View view) { clientContext = new ClientContext(controller, view); } public void launch(Controller controller, View view) { setContext(controller, view); Application.launch(ChatGuiFX.class); } @Override public void start(Stage primaryStage) throws Exception { // Sign in page // Initialize the main stage this.thestage = primaryStage; // Initialize panes BorderPane signInPane = new BorderPane(); FlowPane signInLabelPane = new FlowPane(); HBox inputMasterBox = new HBox(); inputMasterBox.setSpacing(5); VBox inputVBox = new VBox(); HBox usernameHBox = new HBox(); HBox passHBox = new HBox(); VBox buttonBox = new VBox(); buttonBox.setPrefWidth(80); // Set Pane alignments signInLabelPane.setAlignment(Pos.BOTTOM_CENTER); inputMasterBox.setAlignment(Pos.CENTER); inputVBox.setAlignment(Pos.CENTER); usernameHBox.setAlignment(Pos.CENTER); passHBox.setAlignment(Pos.CENTER); buttonBox.setAlignment(Pos.CENTER); // Set up labels Label signInLabel = new Label("Sign-in screen"); Label userLabel = new Label("Username:"); Label passLabel = new Label("Password:"); errorLabel = new Label(""); signInLabel.setFont(Font.font(20)); userLabel.setFont(Font.font(15)); passLabel.setFont(Font.font(15)); errorLabel.setFont(Font.font(15)); errorLabel.setTextFill(Color.web("#FF0000")); // Set up buttons Button signInButton = new Button("Sign in"); Button signUpButton = new Button("Sign up"); signInButton.setMinWidth(buttonBox.getPrefWidth()); signUpButton.setMinWidth(buttonBox.getPrefWidth()); // Initialize event handlers signInButton.setOnAction(e-> signInButtonClicked(e)); signUpButton.setOnAction(e -> signUpButtonClicked(e)); // Set up password fields userInput = new TextField(); passInput = new PasswordField(); userInput.setPromptText("Username"); passInput.setPromptText("Password"); userInput.setAlignment(Pos.CENTER); passInput.setAlignment(Pos.CENTER); // Add labels to their respective panes signInLabelPane.getChildren().add(signInLabel); // Set up HBoxes to hold username and password labels/inputs passHBox.getChildren().add(passLabel); usernameHBox.getChildren().add(userLabel); usernameHBox.getChildren().add(userInput); passHBox.getChildren().add(passInput); // Add those HBoxes to a VBox to stack them on top of each other inputVBox.getChildren().add(usernameHBox); inputVBox.getChildren().add(passHBox); // Add buttons to a VBox to one on top of the other buttonBox.getChildren().add(signInButton); buttonBox.getChildren().add(signUpButton); inputMasterBox.getChildren().add(inputVBox); // Add that VBox and buttons to the inputMasterBox inputMasterBox.getChildren().add(buttonBox); signInPane.setTop(signInLabelPane); signInPane.setBottom(errorLabel); // Add labels and input box to the pane signInPane.setCenter(inputMasterBox); signInScene = new Scene(signInPane, WINDOW_WIDTH, WINDOW_HEIGHT); // Main Page // holds the client HBox hboxClient = new HBox(); // holds the input box HBox hboxInput = new HBox(); // holds the list of users VBox userVBox = new VBox(); // holds chat box VBox chatVBox = new VBox(); // holds the conversations VBox convosVBox = new VBox(); // contains the boxes BorderPane container = new BorderPane(); // button for sending a message Button sendButton = new Button("Send"); // button for updating the client Button updateButton = new Button("Update"); // button for adding conversation Button addConvoButton = new Button("Add Conversation"); Text userTitle = new Text("Users"); // changed based on which is select chatTitle = new Text("Conversation"); Text convosTitle = new Text("Conversations"); TextFlow userTf = new TextFlow(userTitle); TextFlow chatTf = new TextFlow(chatTitle); TextFlow convosTf = new TextFlow(convosTitle); input = new TextField(); // initialize the contents of each panel (user, conversations, & messages) usersList = FXCollections.observableArrayList(); users = new ListView<String>(usersList); convoList = FXCollections.observableArrayList(); conversations = new ListView<String>(convoList); messageList = FXCollections.observableArrayList(); messages = new ListView<String>(messageList); // add listener for when user presses add conversation & add to the conversation list addConvoButton.setOnAction(e -> addConversation(e)); // add listener to the list of conversations to select a conversations conversations.setOnMouseClicked(e -> selectConversation(e)); // add listener to the send button to send messages to the conversation sendButton.setOnAction(e -> sendMessage(e)); // add listener to the update button to update the gui updateButton.setOnAction(e -> updateGUI(e)); // set dimensions and add components VBox.setVgrow(users, Priority.ALWAYS); VBox.setVgrow(conversations, Priority.ALWAYS); VBox.setVgrow(messages, Priority.ALWAYS); HBox.setHgrow(input, Priority.ALWAYS); HBox.setHgrow(userVBox, Priority.ALWAYS); HBox.setHgrow(chatVBox, Priority.ALWAYS); HBox.setHgrow(convosVBox, Priority.ALWAYS); sendButton.setMinHeight(40); updateButton.setMinHeight(40); input.setMinHeight(40); addConvoButton.setMinHeight(40); addConvoButton.setMaxWidth(Double.MAX_VALUE); userTf.setMaxWidth(Double.MAX_VALUE); userTf.setMinHeight(30); chatTf.setMaxWidth(Double.MAX_VALUE); chatTf.setMinHeight(30); convosTf.setMaxWidth(Double.MAX_VALUE); convosTf.setMinHeight(30); userVBox.setMaxWidth(150); chatVBox.setMaxWidth(Double.MAX_VALUE); convosVBox.setMaxWidth(150); hboxInput.getChildren().addAll(input, sendButton, updateButton); userVBox.getChildren().addAll(userTf, users); chatVBox.getChildren().addAll(chatTf, messages, hboxInput); convosVBox.getChildren().addAll(convosTf, conversations, addConvoButton); hboxClient.getChildren().addAll(userVBox, chatVBox, convosVBox); container.setCenter(hboxClient); mainScene = new Scene(container, WINDOW_WIDTH, WINDOW_HEIGHT); thestage.setScene(signInScene); thestage.show(); } /* Sign in */ /** * When the sign in button is clicked, it takes the username & password from the * input fields and checks if they are valid inputs. If they are, sign in the user * and change to main chat */ private void signInButtonClicked(ActionEvent e) { String username = userInput.getText(); String password = passInput.getText(); if (ClientUser.isValidInput(username) && ClientUser.isValidInput(password)) { if (clientContext.user.signInUser(username, password)) { // populate the users, conversations, messages panels from the past signins fillMessagesList(clientContext.conversation.getCurrent()); fillConversationsList(conversations); fillUserList(users); thestage.setScene(mainScene); } } else { errorLabel.setText(BADCHAR_ERROR_MESSAGE); } } /** * When the sign up button is clicked, it takes the username & password from the * input fields and checks if they are valid inputs. If they are, add the user * and change to main chat */ private void signUpButtonClicked(ActionEvent e) { String username = userInput.getText(); String password = passInput.getText(); if (ClientUser.isValidInput(username) && ClientUser.isValidInput(password)) { if (clientContext.user.addUser(username, password)) { // populate the users, conversations, messages panels from the past signins fillMessagesList(clientContext.conversation.getCurrent()); fillConversationsList(conversations); fillUserList(users); thestage.setScene(mainScene); } } else { errorLabel.setText(BADCHAR_ERROR_MESSAGE); } } /* Main Chat */ /** * When the add conversation button is pressed, it pops up a dialog for the user to * input a new conversation. If the conversation name is valid, add the conversation * to the list of conversations to be displayed. */ private void addConversation(ActionEvent e) { if (clientContext.user.hasCurrent()) { // popup for the user to add a conversation TextInputDialog dialog = new TextInputDialog("Name your conversation!"); dialog.setTitle(" "); dialog.setHeaderText("Create your conversation"); // get input and add the name of the convo String name = dialog.showAndWait().get(); // TODO: check for duplicate conversations & handle them for (final ConversationSummary cs : clientContext.conversation.getConversationSummaries()) { if (cs.title.equals(name)) { displayAlert("There is already a conversation with that name!"); return; } } if (!name.isEmpty() && name.length() > 0) { clientContext.conversation.startConversation(name, clientContext.user.getCurrent().id); convoList.add(name); } } else { // user is not signed in displayAlert("You're not signed in!"); } } /** * When the user clicks on a conversation in the right panel, it gets its index and name to * fetch its contents, which is a ConversationSummary object. Then it sets the current conversation * to the selected conversation. */ private void selectConversation(MouseEvent e) { // set the conversation title int index = conversations.getSelectionModel().getSelectedIndex(); String data = conversations.getSelectionModel().getSelectedItem(); // get contents of conversation ConversationSummary selectedConvo = lookupByTitle(data, index); // set new conversation if (selectedConvo != null) { clientContext.conversation.setCurrent(selectedConvo); updateCurrentConversation(selectedConvo); } } /** * Finds the ConversationSummary (the contents of the conversation) that corresponds to * the selected conversation * @param title name of the selected conversation * @param index index of selected conversation in the list of conversations */ private ConversationSummary lookupByTitle(String title, int index) { for (final ConversationSummary cs : clientContext.conversation.getConversationSummaries()) { // An exception was thrown when localIndex was used and tested in the following if statement. // Removing it seemed to fix the issue. if (cs.title.equals(title)) { return cs; } } return null; } /** * Sets the conversation title to be selected conversation & fills the middle panel * with the selected conversation's messages * @param selectedConvo the selected conversation */ private void updateCurrentConversation(ConversationSummary selectedConvo) { chatTitle.setText(selectedConvo.title); // fills the message panel with the messages of the selected conversation fillMessagesList(selectedConvo); } /** * When the user presses the send button, it gives user's unique message to the * current conversation & adds to the list of messages to be displayed. * If the user is not signed in or has not selected a conversation, an error * message pops up. */ private void sendMessage(ActionEvent e) { if (!clientContext.user.hasCurrent()) { // if the user is not signed in displayAlert("You're not signed in!"); } else if (!clientContext.conversation.hasCurrent()) { // if the user did not select or add a conversation displayAlert("Add or click a conversation on the right!"); } else { String messageText = input.getText(); messageList.addAll(input.getText()); if (!messageText.isEmpty() && messageText.length() > 0) { // add message to current conversation clientContext.message.addMessage(clientContext.user.getCurrent().id, clientContext.conversation.getCurrentId(), messageText); // populate the list of messages with the current conversation's updated messages fillMessagesList(clientContext.conversation.getCurrent()); } } } /** * Displays an error message * @param warningMessage the error message to be displayed */ private void displayAlert(String warningMessage) { Alert alert = new Alert(AlertType.ERROR); alert.setHeaderText(warningMessage); alert.showAndWait(); } /** * Populates the list of conversations to be displayed * @param conversations the current conversations that will be cleared & updated */ private void fillConversationsList(ListView<String> conversations) { clientContext.conversation.updateAllConversations(false); conversations.getItems().clear(); for (final ConversationSummary conv : clientContext.conversation.getConversationSummaries()) { convoList.addAll(conv.title); } } /** * Populates the list of messages to be displayed * @param conversation the contents of the current conversation that the method uses to * to get usernames, time of creation, etc. */ private void fillMessagesList(ConversationSummary conversation) { messages.getItems().clear(); for (final Message m : clientContext.message.getConversationContents(conversation)) { // Display author name if available. Otherwise display the author UUID. final String authorName = clientContext.user.getName(m.author); final String displayString = String.format("%s: [%s]: %s", ((authorName.isEmpty()) ? m.author : authorName), m.creation, m.content); messageList.addAll(displayString); } } /** * Populates the list of users to be displayed * @param users the current list of users that will be cleared & updated */ private void fillUserList(ListView<String> users) { clientContext.user.updateUsers(); users.getItems().clear(); User currentUser = clientContext.user.getCurrent(); for (final User u : clientContext.user.getUsers()) { if (!Uuid.equals(u.id, currentUser.id)) usersList.add(u.name); } } // TODO: set up a loop to where this updates every half sec or so /** * When the user presses the update button, update the GUI by clearing & and filling * all the lists that will be displayed with updated content */ private void updateGUI(ActionEvent e) { fillUserList(users); fillConversationsList(conversations); clientContext.message.updateMessages(true); fillMessagesList(clientContext.conversation.getCurrent()); } }
src/codeu/chat/client/simplegui/ChatGuiFX.java
package codeu.chat.client.simplegui; import codeu.chat.client.ClientUser; import javafx.application.Application; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.stage.Stage; import javafx.scene.text.*; import javafx.collections.*; import javafx.scene.input.MouseEvent; import javafx.scene.control.Alert.AlertType; import codeu.chat.client.ClientContext; import codeu.chat.client.Controller; import codeu.chat.common.ConversationSummary; import codeu.chat.common.User; import codeu.chat.common.Message; import codeu.chat.client.View; import codeu.chat.util.Logger; import codeu.chat.util.Uuid; public final class ChatGuiFX extends Application { private final static Logger.Log LOG = Logger.newLog(ChatGuiFX.class); private static final double WINDOW_WIDTH = 1000; private static final double WINDOW_HEIGHT = 500; private static final String SIGNIN_ERROR_MESSAGE = "Your username or password does not match. Have you signed up yet?"; private static final String SIGNUP_ERROR_MESSAGE = "Sorry, that username already exists. Please choose a different one."; private static final String BADCHAR_ERROR_MESSAGE = "Usernames and passwords can only be composed of letters and numbers, no special characters."; // both page vars //private ClientContext clientContext; /* **This is something to think about** // TODO: split the login & main screens into separate methods public void run(String[] args) { buildLoginScene(); buildMainScene(); } */ // login page vars // Holds the scene that user is currently viewing private Stage thestage; // Scenes to hold all the elements for each page private Scene signInScene, mainScene; // Takes input for username and password for sign in/up private TextField userInput; private PasswordField passInput; // Displays error messages for when the user is not sign in or has not selected a convo private Label errorLabel; // variable that has the current state of the client (current user, conversation, etc) private static ClientContext clientContext; // title of current/selected conversation private Text chatTitle; // these hold the conversations to be displayed on the right panel private ObservableList<String> convoList; private ListView<String> conversations; // these hold the messages of a selected conversation to be displayed in the middle panel private ObservableList<String> messageList; private ListView<String> messages; // these hold the users to be displayed on the left panel private ObservableList<String> usersList; private ListView<String> users; // field for the input of messages into a conversation private TextField input; public void setContext(Controller controller, View view) { clientContext = new ClientContext(controller, view); } public void launch(Controller controller, View view) { setContext(controller, view); Application.launch(ChatGuiFX.class); } @Override public void start(Stage primaryStage) throws Exception { // Sign in page // Initialize the main stage this.thestage = primaryStage; // Initialize panes BorderPane signInPane = new BorderPane(); FlowPane signInLabelPane = new FlowPane(); HBox inputMasterBox = new HBox(); inputMasterBox.setSpacing(5); VBox inputVBox = new VBox(); HBox usernameHBox = new HBox(); HBox passHBox = new HBox(); VBox buttonBox = new VBox(); buttonBox.setPrefWidth(80); // Set Pane alignments signInLabelPane.setAlignment(Pos.BOTTOM_CENTER); inputMasterBox.setAlignment(Pos.CENTER); inputVBox.setAlignment(Pos.CENTER); usernameHBox.setAlignment(Pos.CENTER); passHBox.setAlignment(Pos.CENTER); buttonBox.setAlignment(Pos.CENTER); // Set up labels Label signInLabel = new Label("Sign-in screen"); Label userLabel = new Label("Username:"); Label passLabel = new Label("Password:"); errorLabel = new Label(""); signInLabel.setFont(Font.font(20)); userLabel.setFont(Font.font(15)); passLabel.setFont(Font.font(15)); errorLabel.setFont(Font.font(15)); errorLabel.setTextFill(Color.web("#FF0000")); // Set up buttons Button signInButton = new Button("Sign in"); Button signUpButton = new Button("Sign up"); signInButton.setMinWidth(buttonBox.getPrefWidth()); signUpButton.setMinWidth(buttonBox.getPrefWidth()); // Initialize event handlers signInButton.setOnAction(e-> signInButtonClicked(e)); signUpButton.setOnAction(e -> signUpButtonClicked(e)); // Set up password fields userInput = new TextField(); passInput = new PasswordField(); userInput.setPromptText("Username"); passInput.setPromptText("Password"); userInput.setAlignment(Pos.CENTER); passInput.setAlignment(Pos.CENTER); // Add labels to their respective panes signInLabelPane.getChildren().add(signInLabel); // Set up HBoxes to hold username and password labels/inputs passHBox.getChildren().add(passLabel); usernameHBox.getChildren().add(userLabel); usernameHBox.getChildren().add(userInput); passHBox.getChildren().add(passInput); // Add those HBoxes to a VBox to stack them on top of each other inputVBox.getChildren().add(usernameHBox); inputVBox.getChildren().add(passHBox); // Add buttons to a VBox to one on top of the other buttonBox.getChildren().add(signInButton); buttonBox.getChildren().add(signUpButton); inputMasterBox.getChildren().add(inputVBox); // Add that VBox and buttons to the inputMasterBox inputMasterBox.getChildren().add(buttonBox); signInPane.setTop(signInLabelPane); signInPane.setBottom(errorLabel); // Add labels and input box to the pane signInPane.setCenter(inputMasterBox); signInScene = new Scene(signInPane, WINDOW_WIDTH, WINDOW_HEIGHT); // Main Page // holds the client HBox hboxClient = new HBox(); // holds the input box HBox hboxInput = new HBox(); // holds the list of users VBox userVBox = new VBox(); // holds chat box VBox chatVBox = new VBox(); // holds the conversations VBox convosVBox = new VBox(); // contains the boxes BorderPane container = new BorderPane(); // button for sending a message Button sendButton = new Button("Send"); // button for updating the client Button updateButton = new Button("Update"); // button for adding conversation Button addConvoButton = new Button("Add Conversation"); Text userTitle = new Text("Users"); // changed based on which is select chatTitle = new Text("Conversation"); Text convosTitle = new Text("Conversations"); TextFlow userTf = new TextFlow(userTitle); TextFlow chatTf = new TextFlow(chatTitle); TextFlow convosTf = new TextFlow(convosTitle); input = new TextField(); // initialize the contents of each panel (user, conversations, & messages) usersList = FXCollections.observableArrayList(); users = new ListView<String>(usersList); convoList = FXCollections.observableArrayList(); conversations = new ListView<String>(convoList); messageList = FXCollections.observableArrayList(); messages = new ListView<String>(messageList); // add listener for when user presses add conversation & add to the conversation list addConvoButton.setOnAction(e -> addConversation(e)); // add listener to the list of conversations to select a conversations conversations.setOnMouseClicked(e -> selectConversation(e)); // add listener to the send button to send messages to the conversation sendButton.setOnAction(e -> sendMessage(e)); // add listener to the update button to update the gui updateButton.setOnAction(e -> updateGUI(e)); // set dimensions and add components VBox.setVgrow(users, Priority.ALWAYS); VBox.setVgrow(conversations, Priority.ALWAYS); VBox.setVgrow(messages, Priority.ALWAYS); HBox.setHgrow(input, Priority.ALWAYS); HBox.setHgrow(userVBox, Priority.ALWAYS); HBox.setHgrow(chatVBox, Priority.ALWAYS); HBox.setHgrow(convosVBox, Priority.ALWAYS); sendButton.setMinHeight(40); updateButton.setMinHeight(40); input.setMinHeight(40); addConvoButton.setMinHeight(40); addConvoButton.setMaxWidth(Double.MAX_VALUE); userTf.setMaxWidth(Double.MAX_VALUE); userTf.setMinHeight(30); chatTf.setMaxWidth(Double.MAX_VALUE); chatTf.setMinHeight(30); convosTf.setMaxWidth(Double.MAX_VALUE); convosTf.setMinHeight(30); userVBox.setMaxWidth(150); chatVBox.setMaxWidth(Double.MAX_VALUE); convosVBox.setMaxWidth(150); hboxInput.getChildren().addAll(input, sendButton, updateButton); userVBox.getChildren().addAll(userTf, users); chatVBox.getChildren().addAll(chatTf, messages, hboxInput); convosVBox.getChildren().addAll(convosTf, conversations, addConvoButton); hboxClient.getChildren().addAll(userVBox, chatVBox, convosVBox); container.setCenter(hboxClient); mainScene = new Scene(container, WINDOW_WIDTH, WINDOW_HEIGHT); thestage.setScene(signInScene); thestage.show(); } /* Sign in */ /** * When the sign in button is clicked, it takes the username & password from the * input fields and checks if they are valid inputs. If they are, sign in the user * and change to main chat */ private void signInButtonClicked(ActionEvent e) { String username = userInput.getText(); String password = passInput.getText(); if (ClientUser.isValidInput(username) && ClientUser.isValidInput(password)) { if (clientContext.user.signInUser(username, password)) { // populate the users, conversations, messages panels from the past signins fillMessagesList(clientContext.conversation.getCurrent()); fillConversationsList(conversations); fillUserList(users); thestage.setScene(mainScene); } } else { errorLabel.setText(BADCHAR_ERROR_MESSAGE); } } /** * When the sign up button is clicked, it takes the username & password from the * input fields and checks if they are valid inputs. If they are, add the user * and change to main chat */ private void signUpButtonClicked(ActionEvent e) { String username = userInput.getText(); String password = passInput.getText(); if (ClientUser.isValidInput(username) && ClientUser.isValidInput(password)) { if (clientContext.user.addUser(username, password)) { // populate the users, conversations, messages panels from the past signins fillMessagesList(clientContext.conversation.getCurrent()); fillConversationsList(conversations); fillUserList(users); thestage.setScene(mainScene); } } else { errorLabel.setText(BADCHAR_ERROR_MESSAGE); } } /* Main Chat */ /** * When the add conversation button is pressed, it pops up a dialog for the user to * input a new conversation. If the conversation name is valid, add the conversation * to the list of conversations to be displayed. */ private void addConversation(ActionEvent e) { if (clientContext.user.hasCurrent()) { // popup for the user to add a conversation TextInputDialog dialog = new TextInputDialog("Name your conversation!"); dialog.setTitle(" "); dialog.setHeaderText("Create your conversation"); // get input and add the name of the convo String name = dialog.showAndWait().get(); // TODO: check for duplicate conversations & handle them for (final ConversationSummary cs : clientContext.conversation.getConversationSummaries()) { if (cs.title.equals(name)) { displayAlert("There is already a conversation with that name!"); return; } } if (!name.isEmpty() && name.length() > 0) { clientContext.conversation.startConversation(name, clientContext.user.getCurrent().id); convoList.add(name); } } else { // user is not signed in displayAlert("You're not signed in!"); } } /** * When the user clicks on a conversation in the right panel, it gets its index and name to * fetch its contents, which is a ConversationSummary object. Then it sets the current conversation * to the selected conversation. */ private void selectConversation(MouseEvent e) { // set the conversation title int index = conversations.getSelectionModel().getSelectedIndex(); String data = conversations.getSelectionModel().getSelectedItem(); // get contents of conversation ConversationSummary selectedConvo = lookupByTitle(data, index); // set new conversation clientContext.conversation.setCurrent(selectedConvo); updateCurrentConversation(selectedConvo); } /** * Finds the ConversationSummary (the contents of the conversation) that corresponds to * the selected conversation * @param title name of the selected conversation * @param index index of selected conversation in the list of conversations */ private ConversationSummary lookupByTitle(String title, int index) { for (final ConversationSummary cs : clientContext.conversation.getConversationSummaries()) { // An exception was thrown when localIndex was used and tested in the following if statement. // Removing it seemed to fix the issue. if (cs.title.equals(title)) { return cs; } } return null; } /** * Sets the conversation title to be selected conversation & fills the middle panel * with the selected conversation's messages * @param selectedConvo the selected conversation */ private void updateCurrentConversation(ConversationSummary selectedConvo) { chatTitle.setText(selectedConvo.title); // fills the message panel with the messages of the selected conversation fillMessagesList(selectedConvo); } /** * When the user presses the send button, it gives user's unique message to the * current conversation & adds to the list of messages to be displayed. * If the user is not signed in or has not selected a conversation, an error * message pops up. */ private void sendMessage(ActionEvent e) { if (!clientContext.user.hasCurrent()) { // if the user is not signed in displayAlert("You're not signed in!"); } else if (!clientContext.conversation.hasCurrent()) { // if the user did not select or add a conversation displayAlert("Add or click a conversation on the right!"); } else { String messageText = input.getText(); messageList.addAll(input.getText()); if (!messageText.isEmpty() && messageText.length() > 0) { // add message to current conversation clientContext.message.addMessage(clientContext.user.getCurrent().id, clientContext.conversation.getCurrentId(), messageText); // populate the list of messages with the current conversation's updated messages fillMessagesList(clientContext.conversation.getCurrent()); } } } /** * Displays an error message * @param warningMessage the error message to be displayed */ private void displayAlert(String warningMessage) { Alert alert = new Alert(AlertType.ERROR); alert.setHeaderText(warningMessage); alert.showAndWait(); } /** * Populates the list of conversations to be displayed * @param conversations the current conversations that will be cleared & updated */ private void fillConversationsList(ListView<String> conversations) { clientContext.conversation.updateAllConversations(false); conversations.getItems().clear(); for (final ConversationSummary conv : clientContext.conversation.getConversationSummaries()) { convoList.addAll(conv.title); } } /** * Populates the list of messages to be displayed * @param conversation the contents of the current conversation that the method uses to * to get usernames, time of creation, etc. */ private void fillMessagesList(ConversationSummary conversation) { messages.getItems().clear(); for (final Message m : clientContext.message.getConversationContents(conversation)) { // Display author name if available. Otherwise display the author UUID. final String authorName = clientContext.user.getName(m.author); final String displayString = String.format("%s: [%s]: %s", ((authorName.isEmpty()) ? m.author : authorName), m.creation, m.content); messageList.addAll(displayString); } } /** * Populates the list of users to be displayed * @param users the current list of users that will be cleared & updated */ private void fillUserList(ListView<String> users) { clientContext.user.updateUsers(); users.getItems().clear(); User currentUser = clientContext.user.getCurrent(); for (final User u : clientContext.user.getUsers()) { if (!Uuid.equals(u.id, currentUser.id)) usersList.add(u.name); } } // TODO: set up a loop to where this updates every half sec or so /** * When the user presses the update button, update the GUI by clearing & and filling * all the lists that will be displayed with updated content */ private void updateGUI(ActionEvent e) { fillUserList(users); fillConversationsList(conversations); clientContext.message.updateMessages(true); fillMessagesList(clientContext.conversation.getCurrent()); } }
Resolved issue of empty cell click
src/codeu/chat/client/simplegui/ChatGuiFX.java
Resolved issue of empty cell click
Java
apache-2.0
33318616d840b75079698a5ab70247402e1c66df
0
greenlaw110/java-tool,osglworks/java-tool
package org.osgl.web.util; import org.osgl.util.S; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; public class UserAgent { public final static UserAgent UNKNOWN = new UserAgent(); public static enum OS { MAC_OS, IOS, WIN32, WIN64, LINUX, DROID, SYMBIAN, BLACKBERRY, J2ME, SUN_OS, BOT, UNKNOWN } private OS os_ = null; public OS getOS() { return os_; } public static enum Device { IPHONE, IPAD, IPOD, DROID, DROID_TABLET, BLACKBERRY, SONYERICSSON, NOKIA, PC, MOBILE, BOT, UNKNOWN } private Device device_ = null; public Device getDevice() { return device_; } public final boolean is(Device device) { return (device_ == device); } public final boolean isMobile() { final Device[] da = { Device.IPHONE, Device.IPOD, Device.DROID, Device.BLACKBERRY, Device.SONYERICSSON, Device.NOKIA }; for (Device d: da) { if (device_ == d) return true; } return false; } public final boolean isTablet() { final Device[] da = { Device.IPAD, Device.DROID_TABLET }; for (Device d: da) { if (device_ == d) return true; } return false; } public static enum Browser { IE_6, IE_7, IE_8, IE_9, IE_10, IE_11, CHROME, SAFARI, FIREFOX_3, FIREFOX, OPERA, UCWEB, BOT, UNKNOWN } private Browser browser_ = Browser.UNKNOWN; public final Browser getBrowser() { return browser_; } public final boolean isIE678() { Browser b = browser_; return Browser.IE_6 == b || Browser.IE_7 == b || Browser.IE_8 == b; } public final boolean isIE9Down() { Browser b = browser_; return Browser.IE_8 == b || Browser.IE_9 == b || Browser.IE_6 == b || Browser.IE_7 == b; } public final boolean isIE9Up() { Browser b = browser_; return Browser.IE_9 == b || Browser.IE_10 == b || Browser.IE_11 == b; } public final boolean isIE10Up() { Browser b = browser_; return Browser.IE_10 == b || Browser.IE_11 == b; } public final boolean isIE11Up() { Browser b = browser_; return Browser.IE_11 == b; } public final boolean isIE() { return browser_.name().contains("IE"); } public final boolean isFirefox3() { return browser_ == Browser.FIREFOX_3; } public final boolean isFirefox4Up() { return browser_ == Browser.FIREFOX && browser_ != Browser.FIREFOX_3; } public final boolean isFirefox() { return browser_.name().contains("FIREFOX"); } public final boolean isOpera() { return browser_ == Browser.OPERA; } public final boolean isWebKit() { return str_.contains("WebKit"); } public final boolean isSafari() { return browser_ == Browser.SAFARI; } public final boolean isChrome() { return browser_ == Browser.CHROME; } public final boolean isUCWeb() { return browser_ == Browser.UCWEB; } private String str_; @Override public final String toString() { return str_; } private static Map<String, UserAgent> cache_ = new HashMap<String, UserAgent>(); public static UserAgent parse(String userAgent) { if (S.empty(userAgent)) { return UserAgent.UNKNOWN; } UserAgent ua = cache_.get(userAgent); if (null != ua) return ua; ua = new UserAgent(userAgent); cache_.put(userAgent, ua); return ua; } /** * Construct the instance from http header: user-agent * @param userAgent */ private UserAgent(String userAgent) { this(); parse_(userAgent); str_ = userAgent; } private UserAgent() { os_ = OS.UNKNOWN; device_ = Device.UNKNOWN; browser_ = Browser.UNKNOWN; str_ = ""; } private static enum P { /* * Note the sequence of the enum DOSE matter! */ J2ME(Pattern.compile(".*(MIDP|J2ME|CLDC).*"), Device.MOBILE, null, OS.J2ME), UCWEB(Pattern.compile(".*UCWEB.*"), Device.MOBILE, Browser.UCWEB, null), WIN32(Pattern.compile(".*(Windows|W32).*"), Device.PC, null, OS.WIN32), WIN64(Pattern.compile(".*(WOW64|Win64).*"), Device.PC, null, OS.WIN64), LINUX(Pattern.compile(".*Linux.*"), null, null, OS.LINUX), MAC(Pattern.compile(".*Mac OS.*"), Device.PC, null, OS.MAC_OS), SOS(Pattern.compile(".*SunOS.*"), Device.PC, null, OS.SUN_OS), IPHONE(Pattern.compile(".*iPhone.*"), Device.IPHONE, Browser.SAFARI, OS.IOS), IPAD(Pattern.compile(".*iPad.*"), Device.IPAD, Browser.SAFARI, OS.IOS), IPOD(Pattern.compile(".*iPod.*"), Device.IPOD, Browser.SAFARI, OS.IOS), DROID_TABLET(Pattern.compile(".*Android.*"), Device.DROID_TABLET, null, OS.DROID), DROID_MOBILE(Pattern.compile(".*Android.*Mobile.*"), Device.DROID, null, OS.DROID), BLACKBERRY(Pattern.compile(".*BlackBerry.*"), Device.BLACKBERRY, null, OS.BLACKBERRY), SYMBIAN(Pattern.compile(".*Symbian.*", Pattern.CASE_INSENSITIVE), null, null, OS.SYMBIAN), SONYERICSSON(Pattern.compile(".*SonyEricsson.*"), Device.SONYERICSSON, null, null), NOKIA(Pattern.compile(".*Nokia.*", Pattern.CASE_INSENSITIVE), Device.NOKIA, null, null), IE6(Pattern.compile(".*MSIE\\s+[6]\\.0.*"), Device.PC, Browser.IE_6, null), IE7(Pattern.compile(".*MSIE\\s+[7]\\.0.*"), Device.PC, Browser.IE_7, null), IE8(Pattern.compile(".*MSIE\\s+[8]\\.0.*"), Device.PC, Browser.IE_8, null), IE9(Pattern.compile(".*MSIE\\s+(9)\\.0.*"), Device.PC, Browser.IE_9, null), IE10(Pattern.compile(".*MSIE\\s+(10)\\.0.*"), null, Browser.IE_10, null), IE11(Pattern.compile(".*Windows\\s+NT.+rv:(11|12)\\.0.*"), null, Browser.IE_11, null), FIREFOX(Pattern.compile(".*Firefox.*"), null, Browser.FIREFOX, null), FIREFOX3(Pattern.compile(".*Firefox/3.*"), null, Browser.FIREFOX_3, null), SAFARI(Pattern.compile(".*Safari.*"), null, Browser.SAFARI, null), CHROME(Pattern.compile(".*Chrome.*"), null, Browser.CHROME, null), OPERA(Pattern.compile(".*Opera.*"), null, Browser.OPERA, null), BOT(Pattern.compile(".*(Googlebot|msn-bot|msnbot|Bot|bot|Baiduspider|SeznamBot|facebookexternalhit).*", Pattern.CASE_INSENSITIVE), Device.BOT, Browser.BOT, OS.BOT); private final Pattern p_; private Device d_ = Device.UNKNOWN; private Browser b_; private OS o_ = OS.UNKNOWN; P(Pattern pattern, Device device, Browser browser, OS os) { p_ = pattern; d_ = device; b_ = browser; o_ = os; } boolean matches(String ua) { return p_.matcher(ua).matches(); } void test(String str, UserAgent ua) { if (matches(str)) { if (null != d_) { ua.device_ = d_; } if (null != b_) { ua.browser_ = b_; } if (null != o_) { ua.os_ = o_; } } } } private void parse_(String userAgent) { for (P p: P.values()) { p.test(userAgent, this); } } public static final String KEY = "__ua__"; /** * Use valueOf instead * @param userAgent * @return */ @Deprecated public static final UserAgent set(String userAgent) { return valueOf(userAgent); } public static final UserAgent valueOf(String userAgent) { return UserAgent.parse(userAgent); } public static void main(String[] args) { String s = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.20 (KHTML, like Gecko) Chrome/11.0.669.0 Safari/534.20"; UserAgent ua = set(s); assert_(ua.getBrowser() == Browser.CHROME, "1"); s = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; Zune 4.0)"; ua = set(s); assert_(!ua.is(Device.IPHONE), "4"); assert_(ua.getBrowser() == Browser.IE_8, "4"); s = "Mozilla/5.0 (Linux; U; Android 3.0; en-us; Xoom Build/HRI39) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13"; ua = set(s); assert_(ua.is(Device.DROID_TABLET), "2"); assert_(ua.getBrowser() == Browser.SAFARI, "3"); s = "Mozilla/5.0 (X11; U; Linux x86_64; fr; rv:1.9.2.3) Gecko/20100403 Fedora/3.6.3-4.fc13 Firefox/3.6.3"; ua = set(s); assert_(ua.isFirefox3(), "firefox 3"); s = "Mozilla/5.0 (Linux; Android 4.1.1; C1504 Build/11.3.A.0.47) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.94 Mobile Safari/537.36"; ua = set(s); assert_(ua.is(Device.DROID), "droid mobile"); assert_(ua.isMobile(), "mobile"); s = "Mozilla/5.0 (Linux; Android 4.0.3; GT-P5110 Build/IML74K) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.123 Safari/537.22"; ua = set(s); assert_(ua.is(Device.DROID_TABLET), "droid tablet"); assert_(ua.isTablet(), "tablet"); s = "Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko"; ua = valueOf(s); assert_(ua.isIE10Up(), "IE 10"); System.out.println("success!"); } private static void assert_(boolean b, String reason) { if (!b) throw new RuntimeException("assert failed: " + reason); } }
src/main/java/org/osgl/web/util/UserAgent.java
package org.osgl.web.util; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; public class UserAgent { public static enum OS { MAC_OS, IOS, WIN32, WIN64, LINUX, DROID, SYMBIAN, BLACKBERRY, J2ME, SUN_OS, BOT, UNKNOWN } private OS os_ = null; public OS getOS() { return os_; } public static enum Device { IPHONE, IPAD, IPOD, DROID, DROID_TABLET, BLACKBERRY, SONYERICSSON, NOKIA, PC, MOBILE, BOT, UNKNOWN } private Device device_ = null; public Device getDevice() { return device_; } public final boolean is(Device device) { return (device_ == device); } public final boolean isMobile() { final Device[] da = { Device.IPHONE, Device.IPOD, Device.DROID, Device.BLACKBERRY, Device.SONYERICSSON, Device.NOKIA }; for (Device d: da) { if (device_ == d) return true; } return false; } public final boolean isTablet() { final Device[] da = { Device.IPAD, Device.DROID_TABLET }; for (Device d: da) { if (device_ == d) return true; } return false; } public static enum Browser { IE_6, IE_7, IE_8, IE_9, IE_10, IE_11, CHROME, SAFARI, FIREFOX_3, FIREFOX, OPERA, UCWEB, BOT, UNKNOWN } private Browser browser_ = Browser.UNKNOWN; public final Browser getBrowser() { return browser_; } public final boolean isIE678() { Browser b = browser_; return Browser.IE_6 == b || Browser.IE_7 == b || Browser.IE_8 == b; } public final boolean isIE9Down() { Browser b = browser_; return Browser.IE_8 == b || Browser.IE_9 == b || Browser.IE_6 == b || Browser.IE_7 == b; } public final boolean isIE9Up() { Browser b = browser_; return Browser.IE_9 == b || Browser.IE_10 == b || Browser.IE_11 == b; } public final boolean isIE10Up() { Browser b = browser_; return Browser.IE_10 == b || Browser.IE_11 == b; } public final boolean isIE11Up() { Browser b = browser_; return Browser.IE_11 == b; } public final boolean isIE() { return browser_.name().contains("IE"); } public final boolean isFirefox3() { return browser_ == Browser.FIREFOX_3; } public final boolean isFirefox4Up() { return browser_ == Browser.FIREFOX && browser_ != Browser.FIREFOX_3; } public final boolean isFirefox() { return browser_.name().contains("FIREFOX"); } public final boolean isOpera() { return browser_ == Browser.OPERA; } public final boolean isWebKit() { return str_.contains("WebKit"); } public final boolean isSafari() { return browser_ == Browser.SAFARI; } public final boolean isChrome() { return browser_ == Browser.CHROME; } public final boolean isUCWeb() { return browser_ == Browser.UCWEB; } private String str_; @Override public final String toString() { return str_; } private static Map<String, UserAgent> cache_ = new HashMap<String, UserAgent>(); public static UserAgent parse(String userAgent) { UserAgent ua = cache_.get(userAgent); if (null != ua) return ua; ua = new UserAgent(userAgent); cache_.put(userAgent, ua); return ua; } /** * Construct the instance from http header: user-agent * @param userAgent */ private UserAgent(String userAgent) { parse_(userAgent); str_ = userAgent; } private static enum P { /* * Note the sequence of the enum DOSE matter! */ J2ME(Pattern.compile(".*(MIDP|J2ME|CLDC).*"), Device.MOBILE, null, OS.J2ME), UCWEB(Pattern.compile(".*UCWEB.*"), Device.MOBILE, Browser.UCWEB, null), WIN32(Pattern.compile(".*(Windows|W32).*"), Device.PC, null, OS.WIN32), WIN64(Pattern.compile(".*(WOW64|Win64).*"), Device.PC, null, OS.WIN64), LINUX(Pattern.compile(".*Linux.*"), null, null, OS.LINUX), MAC(Pattern.compile(".*Mac OS.*"), Device.PC, null, OS.MAC_OS), SOS(Pattern.compile(".*SunOS.*"), Device.PC, null, OS.SUN_OS), IPHONE(Pattern.compile(".*iPhone.*"), Device.IPHONE, Browser.SAFARI, OS.IOS), IPAD(Pattern.compile(".*iPad.*"), Device.IPAD, Browser.SAFARI, OS.IOS), IPOD(Pattern.compile(".*iPod.*"), Device.IPOD, Browser.SAFARI, OS.IOS), DROID_TABLET(Pattern.compile(".*Android.*"), Device.DROID_TABLET, null, OS.DROID), DROID_MOBILE(Pattern.compile(".*Android.*Mobile.*"), Device.DROID, null, OS.DROID), BLACKBERRY(Pattern.compile(".*BlackBerry.*"), Device.BLACKBERRY, null, OS.BLACKBERRY), SYMBIAN(Pattern.compile(".*Symbian.*", Pattern.CASE_INSENSITIVE), null, null, OS.SYMBIAN), SONYERICSSON(Pattern.compile(".*SonyEricsson.*"), Device.SONYERICSSON, null, null), NOKIA(Pattern.compile(".*Nokia.*", Pattern.CASE_INSENSITIVE), Device.NOKIA, null, null), IE6(Pattern.compile(".*MSIE\\s+[6]\\.0.*"), Device.PC, Browser.IE_6, null), IE7(Pattern.compile(".*MSIE\\s+[7]\\.0.*"), Device.PC, Browser.IE_7, null), IE8(Pattern.compile(".*MSIE\\s+[8]\\.0.*"), Device.PC, Browser.IE_8, null), IE9(Pattern.compile(".*MSIE\\s+(9)\\.0.*"), Device.PC, Browser.IE_9, null), IE10(Pattern.compile(".*MSIE\\s+(10)\\.0.*"), null, Browser.IE_10, null), IE11(Pattern.compile(".*Windows\\s+NT.+rv:(11|12)\\.0.*"), null, Browser.IE_11, null), FIREFOX(Pattern.compile(".*Firefox.*"), null, Browser.FIREFOX, null), FIREFOX3(Pattern.compile(".*Firefox/3.*"), null, Browser.FIREFOX_3, null), SAFARI(Pattern.compile(".*Safari.*"), null, Browser.SAFARI, null), CHROME(Pattern.compile(".*Chrome.*"), null, Browser.CHROME, null), OPERA(Pattern.compile(".*Opera.*"), null, Browser.OPERA, null), BOT(Pattern.compile(".*(Googlebot|msn-bot|msnbot|Bot|bot|Baiduspider|SeznamBot|facebookexternalhit).*", Pattern.CASE_INSENSITIVE), Device.BOT, Browser.BOT, OS.BOT); private final Pattern p_; private Device d_ = Device.UNKNOWN; private Browser b_; private OS o_ = OS.UNKNOWN; P(Pattern pattern, Device device, Browser browser, OS os) { p_ = pattern; d_ = device; b_ = browser; o_ = os; } boolean matches(String ua) { return p_.matcher(ua).matches(); } void test(String str, UserAgent ua) { if (matches(str)) { if (null != d_) { ua.device_ = d_; } if (null != b_) { ua.browser_ = b_; } if (null != o_) { ua.os_ = o_; } } } } private void parse_(String userAgent) { for (P p: P.values()) { p.test(userAgent, this); } } public static final String KEY = "__ua__"; /** * Use valueOf instead * @param userAgent * @return */ @Deprecated public static final UserAgent set(String userAgent) { return valueOf(userAgent); } public static final UserAgent valueOf(String userAgent) { return UserAgent.parse(userAgent); } public static void main(String[] args) { String s = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.20 (KHTML, like Gecko) Chrome/11.0.669.0 Safari/534.20"; UserAgent ua = set(s); assert_(ua.getBrowser() == Browser.CHROME, "1"); s = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; Zune 4.0)"; ua = set(s); assert_(!ua.is(Device.IPHONE), "4"); assert_(ua.getBrowser() == Browser.IE_8, "4"); s = "Mozilla/5.0 (Linux; U; Android 3.0; en-us; Xoom Build/HRI39) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13"; ua = set(s); assert_(ua.is(Device.DROID_TABLET), "2"); assert_(ua.getBrowser() == Browser.SAFARI, "3"); s = "Mozilla/5.0 (X11; U; Linux x86_64; fr; rv:1.9.2.3) Gecko/20100403 Fedora/3.6.3-4.fc13 Firefox/3.6.3"; ua = set(s); assert_(ua.isFirefox3(), "firefox 3"); s = "Mozilla/5.0 (Linux; Android 4.1.1; C1504 Build/11.3.A.0.47) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.94 Mobile Safari/537.36"; ua = set(s); assert_(ua.is(Device.DROID), "droid mobile"); assert_(ua.isMobile(), "mobile"); s = "Mozilla/5.0 (Linux; Android 4.0.3; GT-P5110 Build/IML74K) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.123 Safari/537.22"; ua = set(s); assert_(ua.is(Device.DROID_TABLET), "droid tablet"); assert_(ua.isTablet(), "tablet"); s = "Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko"; ua = valueOf(s); assert_(ua.isIE10Up(), "IE 10"); System.out.println("success!"); } private static void assert_(boolean b, String reason) { if (!b) throw new RuntimeException("assert failed: " + reason); } }
gracefully handle empty useragent string
src/main/java/org/osgl/web/util/UserAgent.java
gracefully handle empty useragent string
Java
apache-2.0
4b36a0f1b95c1a4f4f12442d7cf075626b8fdbef
0
AnshulJain1985/Roadcast-Tracker,jssenyange/traccar,al3x1s/traccar,vipien/traccar,tananaev/traccar,5of9/traccar,tananaev/traccar,duke2906/traccar,vipien/traccar,tsmgeek/traccar,ninioe/traccar,tsmgeek/traccar,ninioe/traccar,jssenyange/traccar,jssenyange/traccar,renaudallard/traccar,jon-stumpf/traccar,duke2906/traccar,orcoliver/traccar,renaudallard/traccar,jon-stumpf/traccar,tsmgeek/traccar,orcoliver/traccar,joseant/traccar-1,stalien/traccar_test,al3x1s/traccar,tananaev/traccar,jon-stumpf/traccar,ninioe/traccar,5of9/traccar,AnshulJain1985/Roadcast-Tracker,orcoliver/traccar,joseant/traccar-1,stalien/traccar_test
/* * Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.traccar.protocol; import java.net.SocketAddress; import java.util.Date; import java.util.regex.Pattern; import org.jboss.netty.channel.Channel; import org.traccar.BaseProtocolDecoder; import org.traccar.helper.Parser; import org.traccar.helper.PatternBuilder; import org.traccar.model.Event; import org.traccar.model.Position; public class GpsmtaProtocolDecoder extends BaseProtocolDecoder { public GpsmtaProtocolDecoder(GpsmtaProtocol protocol) { super(protocol); } private static final Pattern PATTERN = new PatternBuilder() .num("(d+) ") // uid .num("(d+) ") // time .num("(d+.d+) ") // latitude .num("(d+.d+) ") // longitude .num("(d+) ") // speed .num("(d+) ") // course .num("(d+) ") // accuracy .num("(d+) ") // altitude .num("(d+) ") // flags .num("(d+) ") // battery .num("(d+) ") // temperature .num("(d)") // changing status .any() .compile(); @Override protected Object decode( Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { Parser parser = new Parser(PATTERN, (String) msg); if (!parser.matches()) { return null; } Position position = new Position(); position.setProtocol(getProtocolName()); if (!identify(parser.next(), channel, remoteAddress)) { return null; } position.setDeviceId(getDeviceId()); String time = parser.next(); position.setTime(new Date(Long.parseLong(time) * 1000)); position.setLatitude(parser.nextDouble()); position.setLongitude(parser.nextDouble()); position.setSpeed(parser.nextInt()); position.setCourse(parser.nextInt()); parser.next(); position.setAltitude(parser.nextInt()); position.set(Event.KEY_STATUS, parser.nextInt()); position.set(Event.KEY_BATTERY, parser.nextInt()); position.set(Event.PREFIX_TEMP + 1, parser.nextInt()); position.set(Event.KEY_CHARGE, parser.nextInt() == 1); if (channel != null) { channel.write(time, remoteAddress); } return position; } }
src/org/traccar/protocol/GpsmtaProtocolDecoder.java
/* * Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.traccar.protocol; import java.net.SocketAddress; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jboss.netty.channel.Channel; import org.traccar.BaseProtocolDecoder; import org.traccar.helper.Parser; import org.traccar.helper.PatternBuilder; import org.traccar.model.Event; import org.traccar.model.Position; public class GpsmtaProtocolDecoder extends BaseProtocolDecoder { public GpsmtaProtocolDecoder(GpsmtaProtocol protocol) { super(protocol); } private static final Pattern PATTERN = new PatternBuilder() .num("(d+) ") // uid .num("(d+) ") // time .num("(d+.d+) ") // latitude .num("(d+.d+) ") // longitude .num("(d+) ") // speed .num("(d+) ") // course .num("(d+) ") // accuracy .num("(d+) ") // altitude .num("(d+) ") // flags .num("(d+) ") // battery .num("(d+) ") // temperature .num("(d)") // changing status .any() .compile(); @Override protected Object decode( Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { Parser parser = new Parser(PATTERN, (String) msg); if (!parser.matches()) { return null; } Position position = new Position(); position.setProtocol(getProtocolName()); if (!identify(parser.next(), channel, remoteAddress)) { return null; } position.setDeviceId(getDeviceId()); String time = parser.next(); position.setTime(new Date(Long.parseLong(time) * 1000)); position.setLatitude(parser.nextDouble()); position.setLongitude(parser.nextDouble()); position.setSpeed(parser.nextInt()); position.setCourse(parser.nextInt()); parser.next(); position.setAltitude(parser.nextInt()); position.set(Event.KEY_STATUS, parser.nextInt()); position.set(Event.KEY_BATTERY, parser.nextInt()); position.set(Event.PREFIX_TEMP + 1, parser.nextInt()); position.set(Event.KEY_CHARGE, parser.nextInt() == 1); if (channel != null) { channel.write(time, remoteAddress); } return position; } }
Remove unused imports from project
src/org/traccar/protocol/GpsmtaProtocolDecoder.java
Remove unused imports from project
Java
apache-2.0
baa193a53b9d1762ea8f3e5308ff0309ef396b9c
0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.clustercontroller.core.database; import org.apache.zookeeper.data.Stat; import org.apache.zookeeper.*; import java.util.logging.Logger; import java.util.*; import java.nio.charset.Charset; import com.yahoo.log.LogLevel; public class MasterDataGatherer { private static Logger log = Logger.getLogger(MasterDataGatherer.class.getName()); private static Charset utf8 = Charset.forName("UTF8"); /** Utility function for getting node index from path name of the ephemeral nodes. */ private static int getIndex(String nodeName) { assert(nodeName != null); int lastSlash = nodeName.lastIndexOf('/'); if (lastSlash <= 1) { System.err.println("Unexpected path to nodename: '" + nodeName + "'."); assert(lastSlash > 1); } return Integer.parseInt(nodeName.substring(lastSlash + 1)); } private final String zooKeeperRoot; // The root path in zookeeper, typically /vespa/fleetcontroller/<clustername>/ private Map<Integer, Integer> masterData = new TreeMap<Integer, Integer>(); // The master state last reported to the fleetcontroller private final Map<Integer, Integer> nextMasterData = new TreeMap<Integer, Integer>(); // Temporary master state while gathering new info from zookeeper private final AsyncCallback.ChildrenCallback childListener = new DirCallback(); // Dir change listener private final NodeDataCallback nodeListener = new NodeDataCallback(); // Ephemeral node data change listener private final Database.DatabaseListener listener; private final ZooKeeper session; private final int nodeIndex; /* private boolean seenDirChangeDuringRun = false; // Set to true if we got a dir event while a refetch is happening private final Set<Integer> seenDataChangeDuringRun = new TreeSet<Integer>(); // Sets the indexes that got a data change event while fetching is already running */ private Watcher changeWatcher = new ChangeWatcher(); /** * This class is used to handle node children changed and node data changed events from the zookeeper server. * A run to fetch new master data starts with either of these changes, except for the first time on startup, * where the constructor triggers a run by requesting dir info, as it starts of knowing nothing. */ private class ChangeWatcher implements Watcher { public void process(WatchedEvent watchedEvent) { switch (watchedEvent.getType()) { case NodeChildrenChanged: // Fleetcontrollers have either connected or disconnected to ZooKeeper log.log(LogLevel.INFO, "Fleetcontroller " + nodeIndex + ": A change occured in the list of registered fleetcontrollers. Requesting new information"); session.getChildren(zooKeeperRoot + "indexes", this, childListener, null); break; case NodeDataChanged: // A fleetcontroller has changed what node it is voting for log.log(LogLevel.INFO, "Fleetcontroller " + nodeIndex + ": Altered data in node " + watchedEvent.getPath() + ". Requesting new vote"); int index = getIndex(watchedEvent.getPath()); synchronized (nextMasterData) { nextMasterData.put(index, null); } session.getData(zooKeeperRoot + "indexes/" + index, this, nodeListener, null); break; case NodeCreated: // How can this happen? Can one leave watches on non-existing nodes? log.log(LogLevel.WARNING, "Fleetcontroller " + nodeIndex + ": Got unexpected ZooKeeper event NodeCreated"); break; case NodeDeleted: // We get this event when fleetcontrollers shut down and node in dir disappears. But it should also trigger a NodeChildrenChanged event, so // ignoring this one. log.log(LogLevel.DEBUG, "Fleetcontroller " + nodeIndex + ": Node deleted event gotten. Ignoring it, expecting a NodeChildrenChanged event too."); break; case None: log.log(LogLevel.DEBUG, "Fleetcontroller " + nodeIndex + ": Got ZooKeeper event None."); } } } /** * The dir callback class is responsible for handling dir change events (nodes coming up or going down). * It will explicitly request the contents of, and set a watch on, all nodes that are present. Nodes * for controllers that have disappeared from ZooKeeper are implicitly removed from nextMasterData. */ private class DirCallback implements AsyncCallback.ChildrenCallback { public void processResult(int version, String path, Object context, List<String> nodes) { if (nodes == null) nodes = new LinkedList<String>(); log.log(LogLevel.INFO, "Fleetcontroller " + nodeIndex + ": Got node list response from " + path + " version " + version + " with " + nodes.size() + " nodes"); synchronized (nextMasterData) { nextMasterData.clear(); for (String node : nodes) { int index = Integer.parseInt(node); nextMasterData.put(index, null); log.log(LogLevel.INFO, "Fleetcontroller " + nodeIndex + ": Attempting to fetch data in node '" + zooKeeperRoot + index + "' to see vote"); session.getData(zooKeeperRoot + "indexes/" + index, changeWatcher, nodeListener, null); // Invocation of cycleCompleted() for fully accumulated election state will happen // as soon as all getData calls have been processed. } } } } /** The node data callback class is responsible for fetching new votes from fleetcontrollers that have altered their vote. */ private class NodeDataCallback implements AsyncCallback.DataCallback { public void processResult(int code, String path, Object context, byte[] rawdata, Stat stat) { String data = rawdata == null ? null : new String(rawdata, utf8); log.log(LogLevel.INFO, "Fleetcontroller " + nodeIndex + ": Got change in vote data from path " + path + " with code " + code + " and data " + data); int index = getIndex(path); synchronized (nextMasterData) { if (code != KeeperException.Code.OK.intValue()) { if (code == KeeperException.Code.NONODE.intValue()) { log.log(LogLevel.INFO, "Fleetcontroller " + nodeIndex + ": Node at " + path + " removed, got no other option than counting it as down."); } else { log.log(LogLevel.ERROR, "Fleetcontroller " + nodeIndex + ": Failure code " + code + " when listening to node at " + path + ", will assume it's down."); } if (nextMasterData.containsKey(index)) { nextMasterData.remove(index); } else { log.log(LogLevel.ERROR, "Fleetcontroller " + nodeIndex + ": Strangely, we already had data from node " + index + " when trying to remove it"); } } else { Integer value = Integer.valueOf(data); if (nextMasterData.containsKey(index)) { if (value.equals(nextMasterData.get(index))) { log.log(LogLevel.DEBUG, "Fleetcontroller " + nodeIndex + ": Got vote from fleetcontroller " + index + ", which already was " + value + "."); } else { log.log(LogLevel.INFO, "Fleetcontroller " + nodeIndex + ": Got vote from fleetcontroller " + index + ". Altering vote from " + nextMasterData.get(index) + " to " + value + "."); nextMasterData.put(index, value); } } else { log.log(LogLevel.WARNING, "Fleetcontroller " + nodeIndex + ": Got vote from fleetcontroller " + index + " which is not alive according to current state. Ignoring it"); } } for(Integer vote : nextMasterData.values()) { if (vote == null) { log.log(LogLevel.SPAM, "Fleetcontroller " + nodeIndex + ": Still not received votes from all fleet controllers. Awaiting more responses."); return; } } } log.log(LogLevel.DEBUG, "Fleetcontroller " + nodeIndex + ": Got votes for all fleetcontrollers. Sending event with new fleet data for update"); cycleCompleted(); } } /** Constructor setting up the various needed members, and initializing the first data fetch to start things up */ public MasterDataGatherer(ZooKeeper session, String zooKeeperRoot, Database.DatabaseListener listener, int nodeIndex) { this.zooKeeperRoot = zooKeeperRoot; this.session = session; this.listener = listener; this.nodeIndex = nodeIndex; if (session.getState().equals(ZooKeeper.States.CONNECTED)) { restart(); } } /** Calling restart, ignores what we currently know and starts another circly. Typically called after reconnecting to ZooKeeperServer. */ public void restart() { synchronized (nextMasterData) { masterData = new TreeMap<Integer, Integer>(); nextMasterData.clear(); session.getChildren(zooKeeperRoot + "indexes", changeWatcher, childListener, null); } } /** Function to be called when we have new consistent master election. */ public void cycleCompleted() { Map<Integer, Integer> copy; synchronized (nextMasterData) { if (nextMasterData.equals(masterData)) { log.log(LogLevel.DEBUG, "Fleetcontroller " + nodeIndex + ": No change in master data detected, not sending it on"); // for(Integer i : nextMasterData.keySet()) { System.err.println(i + " -> " + nextMasterData.get(i)); } return; } masterData = new TreeMap<Integer, Integer>(nextMasterData); copy = masterData; } log.log(LogLevel.DEBUG, "Fleetcontroller " + nodeIndex + ": Got new master data, sending it on"); listener.handleMasterData(copy); } }
clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/database/MasterDataGatherer.java
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.clustercontroller.core.database; import org.apache.zookeeper.data.Stat; import org.apache.zookeeper.*; import java.util.logging.Logger; import java.util.*; import java.nio.charset.Charset; import com.yahoo.log.LogLevel; public class MasterDataGatherer { private static Logger log = Logger.getLogger(MasterDataGatherer.class.getName()); private static Charset utf8 = Charset.forName("UTF8"); /** Utility function for getting node index from path name of the ephemeral nodes. */ private static int getIndex(String nodeName) { assert(nodeName != null); int lastSlash = nodeName.lastIndexOf('/'); if (lastSlash <= 1) { System.err.println("Unexpected path to nodename: '" + nodeName + "'."); assert(lastSlash > 1); } return Integer.parseInt(nodeName.substring(lastSlash + 1)); } private final String zooKeeperRoot; // The root path in zookeeper, typically /vespa/fleetcontroller/<clustername>/ private Map<Integer, Integer> masterData = new TreeMap<Integer, Integer>(); // The master state last reported to the fleetcontroller private final Map<Integer, Integer> nextMasterData = new TreeMap<Integer, Integer>(); // Temporary master state while gathering new info from zookeeper private final AsyncCallback.ChildrenCallback childListener = new DirCallback(); // Dir change listener private final NodeDataCallback nodeListener = new NodeDataCallback(); // Ephemeral node data change listener private final Database.DatabaseListener listener; private final ZooKeeper session; private final int nodeIndex; /* private boolean seenDirChangeDuringRun = false; // Set to true if we got a dir event while a refetch is happening private final Set<Integer> seenDataChangeDuringRun = new TreeSet<Integer>(); // Sets the indexes that got a data change event while fetching is already running */ private Watcher changeWatcher = new ChangeWatcher(); /** * This class is used to handle node children changed and node data changed events from the zookeeper server. * A run to fetch new master data starts with either of these changes, except for the first time on startup, * where the constructor triggers a run by requesting dir info, as it starts of knowing nothing. */ private class ChangeWatcher implements Watcher { public void process(WatchedEvent watchedEvent) { switch (watchedEvent.getType()) { case NodeChildrenChanged: // Fleetcontrollers have either connected or disconnected to ZooKeeper log.log(LogLevel.INFO, "Fleetcontroller " + nodeIndex + ": A change occured in the list of registered fleetcontrollers. Requesting new information"); session.getChildren(zooKeeperRoot + "indexes", this, childListener, null); break; case NodeDataChanged: // A fleetcontroller have changed what node it is voting for log.log(LogLevel.INFO, "Fleetcontroller " + nodeIndex + ": Altered data in node " + watchedEvent.getPath() + ". Requesting new vote"); int index = getIndex(watchedEvent.getPath()); synchronized (nextMasterData) { nextMasterData.put(index, null); } session.getData(zooKeeperRoot + "indexes/" + index, this, nodeListener, null); break; case NodeCreated: // How can this happen? Can one leave watches on non-existing nodes? log.log(LogLevel.WARNING, "Fleetcontroller " + nodeIndex + ": Got unexpected ZooKeeper event NodeCreated"); break; case NodeDeleted: // We get this event when fleetcontrollers shut down and node in dir disappears. But it should also trigger a NodeChildrenChanged event, so // ignoring this one. log.log(LogLevel.DEBUG, "Fleetcontroller " + nodeIndex + ": Node deleted event gotten. Ignoring it, expecting a NodeChildrenChanged event too."); break; case None: log.log(LogLevel.DEBUG, "Fleetcontroller " + nodeIndex + ": Got ZooKeeper event None."); } } } /** * The dir callback class is responsible for handling dir change events. (Nodes coming up or going down) * It gets a list of all the nodes, and need to find which ones are removed and which ones are added, * and update the next state to remove those no longer existing and request data for those that are new. */ private class DirCallback implements AsyncCallback.ChildrenCallback { public void processResult(int version, String path, Object context, List<String> nodes) { if (nodes == null) nodes = new LinkedList<String>(); log.log(LogLevel.INFO, "Fleetcontroller " + nodeIndex + ": Got node list response from " + path + " version " + version + " with " + nodes.size() + " nodes"); // Detect what nodes are added and what nodes have been removed. Others can be ignored. List<Integer> addedNodes = new LinkedList<Integer>(); synchronized (nextMasterData) { Set<Integer> removedNodes = new TreeSet<Integer>(nextMasterData.keySet()); for (String node : nodes) { int index = Integer.parseInt(node); if (removedNodes.contains(index)) { log.log(LogLevel.DEBUG, "Fleetcontroller " + nodeIndex + ": Node " + index + " no longer exists"); removedNodes.remove(index); } else { log.log(LogLevel.DEBUG, "Fleetcontroller " + nodeIndex + ": Node " + index + " is new"); addedNodes.add(index); } } for (Integer index : removedNodes) { nextMasterData.remove(index); } for (Integer index : addedNodes) { log.log(LogLevel.INFO, "Fleetcontroller " + nodeIndex + ": Attempting to fetch data in node '" + zooKeeperRoot + index + "' to see vote"); nextMasterData.put(index, null); session.getData(zooKeeperRoot + "indexes/" + index, changeWatcher, nodeListener, null); } } // If we didn't add any information, we should have all the information we need and we can report back to the fleetcontroller if (addedNodes.isEmpty()) { cycleCompleted(); } } } /** The node data callback class is responsible for fetching new votes from fleetcontrollers that have altered their vote. */ private class NodeDataCallback implements AsyncCallback.DataCallback { public void processResult(int code, String path, Object context, byte[] rawdata, Stat stat) { String data = rawdata == null ? null : new String(rawdata, utf8); log.log(LogLevel.INFO, "Fleetcontroller " + nodeIndex + ": Got change in vote data from path " + path + " with code " + code + " and data " + data); int index = getIndex(path); synchronized (nextMasterData) { if (code != KeeperException.Code.OK.intValue()) { if (code == KeeperException.Code.NONODE.intValue()) { log.log(LogLevel.INFO, "Fleetcontroller " + nodeIndex + ": Node at " + path + " removed, got no other option than counting it as down."); } else { log.log(LogLevel.ERROR, "Fleetcontroller " + nodeIndex + ": Failure code " + code + " when listening to node at " + path + ", will assume it's down."); } if (nextMasterData.containsKey(index)) { nextMasterData.remove(index); } else { log.log(LogLevel.ERROR, "Fleetcontroller " + nodeIndex + ": Strangely, we already had data from node " + index + " when trying to remove it"); } } else { Integer value = Integer.valueOf(data); if (nextMasterData.containsKey(index)) { if (value.equals(nextMasterData.get(index))) { log.log(LogLevel.DEBUG, "Fleetcontroller " + nodeIndex + ": Got vote from fleetcontroller " + index + ", which already was " + value + "."); } else { log.log(LogLevel.INFO, "Fleetcontroller " + nodeIndex + ": Got vote from fleetcontroller " + index + ". Altering vote from " + nextMasterData.get(index) + " to " + value + "."); nextMasterData.put(index, value); } } else { log.log(LogLevel.WARNING, "Fleetcontroller " + nodeIndex + ": Got vote from fleetcontroller " + index + " which is not alive according to current state. Ignoring it"); } } for(Integer vote : nextMasterData.values()) { if (vote == null) { log.log(LogLevel.SPAM, "Fleetcontroller " + nodeIndex + ": Still not received votes from all fleet controllers. Awaiting more responses."); return; } } } log.log(LogLevel.DEBUG, "Fleetcontroller " + nodeIndex + ": Got votes for all fleetcontrollers. Sending event with new fleet data for update"); cycleCompleted(); } } /** Constructor setting up the various needed members, and initializing the first data fetch to start things up */ public MasterDataGatherer(ZooKeeper session, String zooKeeperRoot, Database.DatabaseListener listener, int nodeIndex) { this.zooKeeperRoot = zooKeeperRoot; this.session = session; this.listener = listener; this.nodeIndex = nodeIndex; if (session.getState().equals(ZooKeeper.States.CONNECTED)) { restart(); } } /** Calling restart, ignores what we currently know and starts another circly. Typically called after reconnecting to ZooKeeperServer. */ public void restart() { synchronized (nextMasterData) { masterData = new TreeMap<Integer, Integer>(); nextMasterData.clear(); session.getChildren(zooKeeperRoot + "indexes", changeWatcher, childListener, null); } } /** Function to be called when we have new consistent master election. */ public void cycleCompleted() { Map<Integer, Integer> copy; synchronized (nextMasterData) { if (nextMasterData.equals(masterData)) { log.log(LogLevel.DEBUG, "Fleetcontroller " + nodeIndex + ": No change in master data detected, not sending it on"); // for(Integer i : nextMasterData.keySet()) { System.err.println(i + " -> " + nextMasterData.get(i)); } return; } masterData = new TreeMap<Integer, Integer>(nextMasterData); copy = masterData; } log.log(LogLevel.DEBUG, "Fleetcontroller " + nodeIndex + ": Got new master data, sending it on"); listener.handleMasterData(copy); } }
Always request data for all znodes on master election dir watch callback The previous version of the code attempted to optimize by only requesting node data for nodes that had changed, but there existed an edge case where it would mistakenly fail to request new data for nodes that _had_ changed. This could happen if the callback was invoked when nextMasterData already contained entries for the same set of node indices returned as part of the directory callback. Always clearing our internal state and requesting all znodes is a more robust option. The number of cluster controllers should always be so low that the expected added overhead is negligible.
clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/database/MasterDataGatherer.java
Always request data for all znodes on master election dir watch callback
Java
apache-2.0
6ee7eac06f2bf97a4f101fe4a1d6aa87d5a46ed4
0
opentelecoms-org/jsmpp-svn-mirror,opentelecoms-org/jsmpp-svn-mirror
package org.jsmpp.examples; import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.log4j.PropertyConfigurator; import org.jsmpp.InvalidResponseException; import org.jsmpp.PDUStringException; import org.jsmpp.bean.Alphabet; import org.jsmpp.bean.BindType; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.GeneralDataCoding; import org.jsmpp.bean.MessageClass; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.extra.NegativeResponseException; import org.jsmpp.extra.ResponseTimeoutException; import org.jsmpp.session.SMPPSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author uudashr * */ public class StressClient implements Runnable { private static final String DEFAULT_PASSWORD = "jpwd"; private static final String DEFAULT_SYSID = "j"; private static final String DEFAULT_DESTADDR = "62161616"; private static final String DEFAULT_SOURCEADDR = "1616"; private static final Logger logger = LoggerFactory.getLogger(StressClient.class); private static final String DEFAULT_LOG4J_PATH = "stress/client-log4j.properties"; private static final String DEFAULT_HOST = "localhost"; private static final Integer DEFAULT_PORT = 8056; private static final Long DEFAULT_TRANSACTIONTIMER = 2000L; private static final Integer DEFAULT_BULK_SIZE = 100000; private static final Integer DEFAULT_PROCESSOR_DEGREE = 3; private static final Integer DEFAULT_MAX_OUTSTANDING = 1000; private AtomicInteger requestCounter = new AtomicInteger(); private AtomicInteger totalRequestCounter = new AtomicInteger(); private AtomicInteger responseCounter = new AtomicInteger(); private AtomicInteger totalResponseCounter = new AtomicInteger(); private ExecutorService execService; private String host; private int port; private int bulkSize; private SMPPSession smppSession = new SMPPSession(); private AtomicBoolean exit = new AtomicBoolean(); private int id; private String systemId; private String password; private String sourceAddr; private String destinationAddr; public StressClient(int id, String host, int port, int bulkSize, String systemId, String password, String sourceAddr, String destinationAddr, long transactionTimer, int pduProcessorDegree, int maxOutstanding) { this.id = id; this.host = host; this.port = port; this.bulkSize = bulkSize; this.systemId = systemId; this.password = password; this.sourceAddr = sourceAddr; this.destinationAddr = destinationAddr; smppSession.setPduProcessorDegree(pduProcessorDegree); smppSession.setTransactionTimer(transactionTimer); execService = Executors.newFixedThreadPool(maxOutstanding); } private void shutdown() { execService.shutdown(); exit.set(true); } public void run() { try { smppSession.connectAndBind(host, port, BindType.BIND_TRX, systemId, password, "cln", TypeOfNumber.UNKNOWN, NumberingPlanIndicator.UNKNOWN, null); logger.info("Bound to " + host + ":" + port); } catch (IOException e) { logger.error("Failed initialize connection or bind", e); return; } new TrafficWatcherThread().start(); logger.info("Starting send " + bulkSize + " bulk message..."); for (int i = 0; i < bulkSize && !exit.get(); i++) { execService.execute(newSendTask("Hello " + id + " idx=" + i)); } while (!exit.get()) { try { Thread.sleep(1000); } catch (InterruptedException e) { } } logger.info("Done"); smppSession.unbindAndClose(); } private Runnable newSendTask(final String message) { return new Runnable() { public void run() { try { requestCounter.incrementAndGet(); smppSession.submitShortMessage(null, TypeOfNumber.UNKNOWN, NumberingPlanIndicator.UNKNOWN, sourceAddr, TypeOfNumber.UNKNOWN, NumberingPlanIndicator.UNKNOWN, destinationAddr, new ESMClass(), (byte)0, (byte)0, null, null, new RegisteredDelivery(0), (byte)0, new GeneralDataCoding(true, true, MessageClass.CLASS1, Alphabet.ALPHA_DEFAULT), (byte)0, message.getBytes()); responseCounter.incrementAndGet(); } catch (PDUStringException e) { logger.error("Failed submit short message '" + message + "'", e); shutdown(); } catch (ResponseTimeoutException e) { logger.error("Failed submit short message '" + message + "'", e); shutdown(); } catch (InvalidResponseException e) { logger.error("Failed submit short message '" + message + "'", e); shutdown(); } catch (NegativeResponseException e) { logger.error("Failed submit short message '" + message + "'", e); shutdown(); } catch (IOException e) { logger.error("Failed submit short message '" + message + "'", e); shutdown(); } } }; } private class TrafficWatcherThread extends Thread { @Override public void run() { logger.info("Starting traffic watcher..."); while (!exit.get()) { try { Thread.sleep(1000); } catch (InterruptedException e) { } int requestPerSecond = requestCounter.getAndSet(0); int responsePerSecond = responseCounter.getAndSet(0); totalRequestCounter.addAndGet(requestPerSecond); int total = totalResponseCounter.addAndGet(responsePerSecond); logger.info("Request/Response per second : " + requestPerSecond + "/" + responsePerSecond + " of " + total); if (total == bulkSize) { shutdown(); } } } } public static void main(String[] args) { String host = System.getProperty("jsmpp.client.host", DEFAULT_HOST); String systemId = System.getProperty("jsmpp.client.systemId", DEFAULT_SYSID); String password = System.getProperty("jsmpp.client.password", DEFAULT_PASSWORD); String sourceAddr = System.getProperty("jsmpp.client.sourceAddr", DEFAULT_SOURCEADDR); String destinationAddr = System.getProperty("jsmpp.client.destinationAddr", DEFAULT_DESTADDR); int port; try { port = Integer.parseInt(System.getProperty("jsmpp.client.port", DEFAULT_PORT.toString())); } catch (NumberFormatException e) { port = DEFAULT_PORT; } long transactionTimer; try { transactionTimer = Integer.parseInt(System.getProperty("jsmpp.client.transactionTimer", DEFAULT_TRANSACTIONTIMER.toString())); } catch (NumberFormatException e) { transactionTimer = DEFAULT_TRANSACTIONTIMER; } int bulkSize; try { bulkSize = Integer.parseInt(System.getProperty("jsmpp.client.bulksize", DEFAULT_BULK_SIZE.toString())); } catch (NumberFormatException e) { bulkSize = DEFAULT_BULK_SIZE; } int processorDegree; try { processorDegree = Integer.parseInt(System.getProperty("jsmpp.client.procdegree", DEFAULT_PROCESSOR_DEGREE.toString())); } catch (NumberFormatException e) { processorDegree = DEFAULT_PROCESSOR_DEGREE; } int maxOutstanding; try { maxOutstanding = Integer.parseInt(System.getProperty("jsmpp.client.maxoutstanding", DEFAULT_MAX_OUTSTANDING.toString())); } catch (NumberFormatException e) { maxOutstanding = DEFAULT_MAX_OUTSTANDING; } String log4jPath = System.getProperty("jsmpp.log4j.path", DEFAULT_LOG4J_PATH); PropertyConfigurator.configure(log4jPath); logger.info("Target server {}:{}", host, port); logger.info("System ID: {}", systemId); logger.info("Password: {}", password); logger.info("Source address: {}", sourceAddr); logger.info("Destination address: {}", destinationAddr); logger.info("Transaction timer: {}", transactionTimer); logger.info("Bulk size: {}", bulkSize); logger.info("Max outstanding: {}", maxOutstanding); logger.info("Processor degree: {}", processorDegree); StressClient stressClient = new StressClient(0, host, port, bulkSize, systemId, password, sourceAddr, destinationAddr, transactionTimer, processorDegree, maxOutstanding); stressClient.run(); } }
src/java/examples/org/jsmpp/examples/StressClient.java
package org.jsmpp.examples; import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.log4j.PropertyConfigurator; import org.jsmpp.InvalidResponseException; import org.jsmpp.PDUStringException; import org.jsmpp.bean.Alphabet; import org.jsmpp.bean.BindType; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.GeneralDataCoding; import org.jsmpp.bean.MessageClass; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.extra.NegativeResponseException; import org.jsmpp.extra.ResponseTimeoutException; import org.jsmpp.session.SMPPSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author uudashr * */ public class StressClient implements Runnable { private static final String DEFAULT_PASSWORD = "jpwd"; private static final String DEFAULT_SYSID = "j"; private static final String DEFAULT_DESTADDR = "62161616"; private static final String DEFAULT_SOURCEADDR = "1616"; private static final Logger logger = LoggerFactory.getLogger(StressClient.class); private static final String DEFAULT_LOG4J_PATH = "stress/client-log4j.properties"; private static final String DEFAULT_HOST = "localhost"; private static final Integer DEFAULT_PORT = 8056; private static final Integer DEFAULT_BULK_SIZE = 100000; private static final Integer DEFAULT_PROCESSOR_DEGREE = 3; private static final Integer DEFAULT_MAX_OUTSTANDING = 1000; private AtomicInteger requestCounter = new AtomicInteger(); private AtomicInteger totalRequestCounter = new AtomicInteger(); private AtomicInteger responseCounter = new AtomicInteger(); private AtomicInteger totalResponseCounter = new AtomicInteger(); private ExecutorService execService; private String host; private int port; private int bulkSize; private SMPPSession smppSession = new SMPPSession(); private AtomicBoolean exit = new AtomicBoolean(); private int id; private String systemId; private String password; private String sourceAddr; private String destinationAddr; public StressClient(int id, String host, int port, int bulkSize, String systemId, String password, String sourceAddr, String destinationAddr, int pduProcessorDegree, int maxOutstanding) { this.id = id; this.host = host; this.port = port; this.bulkSize = bulkSize; this.systemId = systemId; this.password = password; this.sourceAddr = sourceAddr; this.destinationAddr = destinationAddr; smppSession.setPduProcessorDegree(pduProcessorDegree); execService = Executors.newFixedThreadPool(maxOutstanding); } private void shutdown() { execService.shutdown(); exit.set(true); } public void run() { try { smppSession.connectAndBind(host, port, BindType.BIND_TRX, systemId, password, "cln", TypeOfNumber.UNKNOWN, NumberingPlanIndicator.UNKNOWN, null); logger.info("Bound to " + host + ":" + port); } catch (IOException e) { logger.error("Failed initialize connection or bind", e); return; } new TrafficWatcherThread().start(); logger.info("Starting send " + bulkSize + " bulk message..."); for (int i = 0; i < bulkSize && !exit.get(); i++) { execService.execute(newSendTask("Hello " + id + " idx=" + i)); } while (!exit.get()) { try { Thread.sleep(1000); } catch (InterruptedException e) { } } logger.info("Done"); smppSession.unbindAndClose(); } private Runnable newSendTask(final String message) { return new Runnable() { public void run() { try { requestCounter.incrementAndGet(); smppSession.submitShortMessage(null, TypeOfNumber.UNKNOWN, NumberingPlanIndicator.UNKNOWN, sourceAddr, TypeOfNumber.UNKNOWN, NumberingPlanIndicator.UNKNOWN, destinationAddr, new ESMClass(), (byte)0, (byte)0, null, null, new RegisteredDelivery(0), (byte)0, new GeneralDataCoding(true, true, MessageClass.CLASS1, Alphabet.ALPHA_DEFAULT), (byte)0, message.getBytes()); responseCounter.incrementAndGet(); } catch (PDUStringException e) { logger.error("Failed submit short message '" + message + "'", e); shutdown(); } catch (ResponseTimeoutException e) { logger.error("Failed submit short message '" + message + "'", e); shutdown(); } catch (InvalidResponseException e) { logger.error("Failed submit short message '" + message + "'", e); shutdown(); } catch (NegativeResponseException e) { logger.error("Failed submit short message '" + message + "'", e); shutdown(); } catch (IOException e) { logger.error("Failed submit short message '" + message + "'", e); shutdown(); } } }; } private class TrafficWatcherThread extends Thread { @Override public void run() { logger.info("Starting traffic watcher..."); while (!exit.get()) { try { Thread.sleep(1000); } catch (InterruptedException e) { } int requestPerSecond = requestCounter.getAndSet(0); int responsePerSecond = responseCounter.getAndSet(0); totalRequestCounter.addAndGet(requestPerSecond); int total = totalResponseCounter.addAndGet(responsePerSecond); logger.info("Request/Response per second : " + requestPerSecond + "/" + responsePerSecond + " of " + total); if (total == bulkSize) { shutdown(); } } } } public static void main(String[] args) { String host = System.getProperty("jsmpp.client.host", DEFAULT_HOST); String systemId = System.getProperty("jsmpp.client.systemId", DEFAULT_SYSID); String password = System.getProperty("jsmpp.client.password", DEFAULT_PASSWORD); String sourceAddr = System.getProperty("jsmpp.client.sourceAddr", DEFAULT_SOURCEADDR); String destinationAddr = System.getProperty("jsmpp.client.destinationAddr", DEFAULT_DESTADDR); int port; try { port = Integer.parseInt(System.getProperty("jsmpp.client.port", DEFAULT_PORT.toString())); } catch (NumberFormatException e) { port = DEFAULT_PORT; } int bulkSize; try { bulkSize = Integer.parseInt(System.getProperty("jsmpp.client.bulksize", DEFAULT_BULK_SIZE.toString())); } catch (NumberFormatException e) { bulkSize = DEFAULT_BULK_SIZE; } int processorDegree; try { processorDegree = Integer.parseInt(System.getProperty("jsmpp.client.procdegree", DEFAULT_PROCESSOR_DEGREE.toString())); } catch (NumberFormatException e) { processorDegree = DEFAULT_PROCESSOR_DEGREE; } int maxOutstanding; try { maxOutstanding = Integer.parseInt(System.getProperty("jsmpp.client.maxoutstanding", DEFAULT_MAX_OUTSTANDING.toString())); } catch (NumberFormatException e) { maxOutstanding = DEFAULT_MAX_OUTSTANDING; } String log4jPath = System.getProperty("jsmpp.log4j.path", DEFAULT_LOG4J_PATH); PropertyConfigurator.configure(log4jPath); logger.info("Target server {}:{}", host, port); logger.info("System ID: {}", systemId); logger.info("Password: {}", password); logger.info("Source address: " + sourceAddr); logger.info("Destination address: " + destinationAddr); logger.info("Bulk size: {}", bulkSize); logger.info("Max outstanding: {}", maxOutstanding); logger.info("Processor degree: {}", processorDegree); StressClient stressClient = new StressClient(0, host, port, bulkSize, systemId, password, sourceAddr, destinationAddr, processorDegree, maxOutstanding); stressClient.run(); } }
Configurable transaction timer for StressClient git-svn-id: 8aef34885c21801cc977f98956a081c938212632@137 1678c8a9-8d33-0410-b0a4-d546c816ed44
src/java/examples/org/jsmpp/examples/StressClient.java
Configurable transaction timer for StressClient
Java
bsd-2-clause
4e23aa44f94b311b9e2e7656b76a06943058e716
0
wongcc966422/ld33,wongcc966422/ld33,SadaleNet/ld33,SadaleNet/ld33,wongcc966422/ld33,SadaleNet/ld33
package com.ld33.game; import java.util.Vector; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.ParticleEffect; import com.badlogic.gdx.graphics.g2d.ParticleEffectPool; import com.badlogic.gdx.graphics.g2d.ParticleEffectPool.PooledEffect; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Align; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.TimeUtils; import com.badlogic.gdx.utils.viewport.FitViewport; import com.badlogic.gdx.utils.viewport.Viewport; public class LD33Game extends ApplicationAdapter { SpriteBatch batch; ShapeRenderer shapeRenderer; Texture background; BitmapFont bitmapFont; Vector<GameObject> objectList; private Texture sprite; Texture winScene, loseScene, currentScene; private Viewport viewport; private Camera camera; Bird bird; Boss boss; PoliceCar policeCar; ParticleEffectPool poopEffectPool; ParticleEffectPool poopedEffectPool; Array<PooledEffect> effects; Button attackButton, rateButton, flySpeedButton, spawnRateButton, moneyButton; int money ; float damage; int averageSpawnDuration; float bossSpawnProbability; int moneyDelta; long nextVictimSpawnTick; long nextBlackCloudSpawnTick; long nextWhiteCloudSpawnTick; long centerTextDisappearTick; //Long.MAX_VALUE means click to disappear boolean policeWarningTriggered; long nextPoliceSpawnTick; private String centerTextString; long endGameTick; public static final int GAME_WIDTH = 960; public static final int GAME_HEIGHT = 500; private static final float MIN_VICTIM_SPEED = 50f; private static final float MAX_VICTIM_SPEED = 100f; private static final float AVERAGE_WHITE_CLOUD_SPAWN_DURATION = 2500; private static final float AVERAGE_BLACK_CLOUD_SPAWN_DURATION = 10000; private static final float MIN_CLOUD_SPEED = 25f; private static final float MAX_CLOUD_SPEED = 75f; private static final float AVERAGE_POLICE_SPAWN_DURATION = 100000; private static final float MIN_POLICE_SPEED = 100f; private static final float MAX_POLICE_SPEED = 250f; private static final float POLICE_WARNING_OFFSET = 5000; private static final long TEXT_FADEOUT_DURATION = 1000; private static final long GAME_END_SCENE_CROSSFACE_DURATION = 5000; public static LD33Game instance; @Override public void create () { instance = this; objectList = new Vector<GameObject>(); money = 0; damage = 1f; averageSpawnDuration = 10000; bossSpawnProbability = 0.25f; moneyDelta = 1; nextBlackCloudSpawnTick = Long.MIN_VALUE; centerTextDisappearTick = Long.MAX_VALUE; policeWarningTriggered = false; nextPoliceSpawnTick = Long.MIN_VALUE; centerTextString = "Poopie the Flying Monster\n\n Click to Play"; endGameTick = Long.MAX_VALUE; currentScene=null; boss = null; policeCar = null; effects = new Array<PooledEffect>(); camera = new OrthographicCamera(GAME_WIDTH, GAME_HEIGHT); camera.position.set(GAME_WIDTH/2, GAME_HEIGHT/2, 0); camera.update(); viewport = new FitViewport(GAME_WIDTH, GAME_HEIGHT, camera); sprite = new Texture("sprite.png"); batch = new SpriteBatch(); shapeRenderer = new ShapeRenderer(); winScene = new Texture("win.png"); loseScene = new Texture("lose.png"); background = new Texture("background.png"); bitmapFont = new BitmapFont(Gdx.files.internal("font.fnt")); attackButton = new Button(32, GAME_HEIGHT-32-32, 0, new int[]{3, 10, 50}, new Action(){ @Override void action(int level) { switch(level){ case 1: damage = 2; break; case 2: damage = 3; break; case 3: damage = 10; break; } } }); objectList.add(attackButton); rateButton = new Button(32, GAME_HEIGHT-32-32-64, 1, new int[]{3, 10, 50}, new Action(){ @Override void action(int level) { switch(level){ case 1: bird.poopReloadDuration = 1250; break; case 2: bird.poopReloadDuration = 500; break; case 3: bird.poopReloadDuration = 100; break; } } }); objectList.add(rateButton); flySpeedButton = new Button(32, GAME_HEIGHT-32-32-64*2, 2, new int[]{3, 10, 20}, new Action(){ @Override void action(int level) { switch(level){ case 1: bird.speed = 150f; break; case 2: bird.speed = 200f; break; case 3: bird.speed = 300f; break; } } }); objectList.add(flySpeedButton); spawnRateButton = new Button(32, GAME_HEIGHT-32-32-64*3, 3, new int[]{10, 50, 200}, new Action(){ @Override void action(int level) { switch(level){ case 1: averageSpawnDuration = 5000; bossSpawnProbability=0f; break; case 2: averageSpawnDuration = 2000; break; case 3: averageSpawnDuration = 1000; bossSpawnProbability=1f; break; } } }); objectList.add(spawnRateButton); moneyButton = new Button(32, GAME_HEIGHT-32-32-64*4, 4, new int[]{5, 10, 20}, new Action(){ @Override void action(int level) { switch(level){ case 1: moneyDelta = 2; break; case 2: moneyDelta = 3; break; case 3: moneyDelta = 4; break; } } }); objectList.add(moneyButton); ParticleEffect poopEffect = new ParticleEffect(); poopEffect.load(Gdx.files.internal("poopDrop.p"), Gdx.files.internal("")); poopEffectPool = new ParticleEffectPool(poopEffect, 8, 128); ParticleEffect poopedEffect = new ParticleEffect(); poopedEffect.load(Gdx.files.internal("pooped.p"), Gdx.files.internal("")); poopedEffectPool = new ParticleEffectPool(poopedEffect, 16, 1024); objectList.add(bird=new Bird(GAME_WIDTH/2, GAME_HEIGHT/2)); spawnVictim(); spawnBlackCloud(); spawnWhiteCloud(); } @Override public void render () { float deltaTime = Gdx.graphics.getDeltaTime(); Vector3 touchPos = new Vector3(); touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0); touchPos = camera.unproject(touchPos); Vector<GameObject> objectListClone = new Vector<GameObject>(objectList); //Do click handling if(currentScene==null){ if(Gdx.input.justTouched()){ if(nextPoliceSpawnTick==Long.MIN_VALUE) spawnPoliceCar(); if(centerTextDisappearTick==Long.MAX_VALUE) centerTextDisappearTick = TimeUtils.millis(); boolean handled = false; for(GameObject i:objectList){ if(i instanceof Button){ if(new Rectangle(i.x-i.w/2, i.y-i.h/2, i.w, i.h).contains(touchPos.x, touchPos.y)){ ((Button)i).action(); handled = true; break; } } } if(!handled){ bird.poop(); if(policeCar!=null){ centerTextString = "Oh... Police found you being a monster..."; policeCar.activate(); } } } //spawn items if(TimeUtils.millis()>nextVictimSpawnTick) spawnVictim(); if(TimeUtils.millis()>nextBlackCloudSpawnTick) spawnBlackCloud(); if(TimeUtils.millis()>nextWhiteCloudSpawnTick) spawnWhiteCloud(); if(!policeWarningTriggered&&nextPoliceSpawnTick!=Long.MIN_VALUE&&TimeUtils.millis()+POLICE_WARNING_OFFSET>nextPoliceSpawnTick){ policeWarningTriggered = true; centerTextString = "POLICE!\nSTOP POOPING!"; LD33Game.instance.centerTextDisappearTick = Long.MAX_VALUE-1; //TODO: play warning music here } if(TimeUtils.millis()>nextPoliceSpawnTick) spawnPoliceCar(); //update the objects for(GameObject i:objectListClone) i.onStep(deltaTime, (int)touchPos.x, (int)touchPos.y); //collision detection for(int i=0; i<objectListClone.size(); i++){ for(int j=i+1; j<objectListClone.size(); j++){ GameObject a = objectListClone.get(i); GameObject b = objectListClone.get(j); if(b instanceof Poop && a instanceof Victim ||b instanceof Bird && a instanceof Thunder ||b instanceof Bird && a instanceof PoliceCar){ GameObject c = a; a = b; b = c; } if(a instanceof Poop && b instanceof Victim){ if(((Victim)b).hp<=0) continue; if(new Rectangle(b.x-b.w/2, b.y-b.h/2, b.w, b.h).contains(a.x, a.y)){ ((Victim)b).hit(damage); ((Poop)a).effect.setDuration(0); objectList.remove(a); } }else if(a instanceof Bird && b instanceof Thunder){ if(new Rectangle(a.x-a.w/2, a.y-a.h/2, a.w, a.h) .overlaps(new Rectangle(b.x-b.w/2, b.y-b.h/2, b.w, b.h))){ objectList.remove(b); if(money<=1) money = 0; else money /= 2; objectList.add(new MoneyEyesCandy(a.x, a.y-32, -50f)); } }else if(a instanceof Bird && b instanceof PoliceCar){ if(Math.sqrt((b.x-a.x)*(b.x-a.x)+(b.y-a.y)*(b.y-a.y))<=64){ currentScene = loseScene; endGameTick = TimeUtils.millis(); } } } } }else{ if(Gdx.input.isKeyJustPressed(Keys.ESCAPE)){ create(); //restart the game return; } } //do the rendering Gdx.gl.glClearColor(1, 1, 1, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); batch.setProjectionMatrix(camera.combined); shapeRenderer.setProjectionMatrix(camera.combined); batch.begin(); batch.draw(background, 0, 0); //rendering particles for (int i = effects.size - 1; i >= 0; i--) { PooledEffect effect = effects.get(i); effect.draw(batch, deltaTime); if (effect.isComplete()) { effect.free(); effects.removeIndex(i); } } //render sprite for(GameObject i:objectList) i.render(batch, sprite); //render money string bitmapFont.getData().setScale(1f); LD33Game.instance.bitmapFont.draw(batch, "$"+Integer.toString(money), 0, GAME_HEIGHT); //render menu string if(TimeUtils.millis()-TEXT_FADEOUT_DURATION<centerTextDisappearTick){ if(TimeUtils.millis()>centerTextDisappearTick) LD33Game.instance.bitmapFont.setColor(1, 1, 1, 1f-(float)(TimeUtils.millis()-centerTextDisappearTick)/TEXT_FADEOUT_DURATION); LD33Game.instance.bitmapFont.draw(batch, centerTextString, 0, 400, GAME_WIDTH, Align.center, false); LD33Game.instance.bitmapFont.setColor(1, 1, 1, 1); } batch.end(); //render HP bar shapeRenderer.begin(ShapeType.Filled); for(GameObject i:objectList){ if(i instanceof Victim){ if(((Victim)i).hp==((Victim)i).getFullHp()) continue; float yOffset = i instanceof Boss?100:80; shapeRenderer.setColor(Color.RED); shapeRenderer.rect(i.x-i.w/2, i.y+yOffset, i.w, 10); if(((Victim)i).hp>0){ shapeRenderer.setColor(Color.GREEN); shapeRenderer.rect(i.x-i.w/2, i.y+yOffset, i.w*((Victim)i).hp/((Victim)i).getFullHp(), 10); } } } shapeRenderer.end(); if(currentScene!=null){ batch.setColor(1, 1, 1, (float)Math.min(1, (double)(TimeUtils.millis()-endGameTick)/(double)GAME_END_SCENE_CROSSFACE_DURATION)); batch.begin(); batch.draw(currentScene, 0, 0); batch.end(); } } @Override public void resize(int width, int height) { viewport.update(width, height); } private void spawnVictim() { nextVictimSpawnTick = TimeUtils.millis()+(long)(averageSpawnDuration/2+Math.random()*averageSpawnDuration); if(boss==null&&Math.random()<bossSpawnProbability){ objectList.add(boss=new Boss( (float)( (Math.random()<0.5?1:-1) *(MIN_VICTIM_SPEED+Math.random()*(MAX_VICTIM_SPEED-MIN_VICTIM_SPEED)) ) )); }else{ objectList.add(new Victim( (float)( (Math.random()<0.5?1:-1) *(MIN_VICTIM_SPEED+Math.random()*(MAX_VICTIM_SPEED-MIN_VICTIM_SPEED)) ) )); } } private void spawnWhiteCloud(){ if(nextWhiteCloudSpawnTick!=Long.MIN_VALUE){ objectList.add(new Cloud( (float)( (Math.random()<0.5?1:-1) *(MIN_CLOUD_SPEED+Math.random()*(MAX_CLOUD_SPEED-MIN_CLOUD_SPEED)) ) )); } nextWhiteCloudSpawnTick = TimeUtils.millis()+(long)(AVERAGE_WHITE_CLOUD_SPAWN_DURATION/2+Math.random()*AVERAGE_WHITE_CLOUD_SPAWN_DURATION); } private void spawnBlackCloud(){ if(nextBlackCloudSpawnTick!=Long.MIN_VALUE){ objectList.add(new BlackCloud( (float)( (Math.random()<0.5?1:-1) *(MIN_CLOUD_SPEED+Math.random()*(MAX_CLOUD_SPEED-MIN_CLOUD_SPEED)) ) )); } nextBlackCloudSpawnTick = TimeUtils.millis()+(long)(AVERAGE_BLACK_CLOUD_SPAWN_DURATION/2+Math.random()*AVERAGE_BLACK_CLOUD_SPAWN_DURATION); } private void spawnPoliceCar(){ if(nextPoliceSpawnTick!=Long.MIN_VALUE){ objectList.add(policeCar=new PoliceCar( (float)( (Math.random()<0.5?1:-1) *(MIN_POLICE_SPEED+Math.random()*(MAX_POLICE_SPEED-MIN_POLICE_SPEED)) ) )); } nextPoliceSpawnTick = TimeUtils.millis()+(long)(AVERAGE_POLICE_SPAWN_DURATION/2+Math.random()*AVERAGE_POLICE_SPAWN_DURATION); } }
core/src/com/ld33/game/LD33Game.java
package com.ld33.game; import java.util.Vector; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.ParticleEffect; import com.badlogic.gdx.graphics.g2d.ParticleEffectPool; import com.badlogic.gdx.graphics.g2d.ParticleEffectPool.PooledEffect; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Align; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.TimeUtils; import com.badlogic.gdx.utils.viewport.FitViewport; import com.badlogic.gdx.utils.viewport.Viewport; public class LD33Game extends ApplicationAdapter { SpriteBatch batch; ShapeRenderer shapeRenderer; Texture background; BitmapFont bitmapFont; Vector<GameObject> objectList; private Texture sprite; Texture winScene, loseScene, currentScene; private Viewport viewport; private Camera camera; Bird bird; Boss boss; PoliceCar policeCar; ParticleEffectPool poopEffectPool; ParticleEffectPool poopedEffectPool; Array<PooledEffect> effects; Button attackButton, rateButton, flySpeedButton, spawnRateButton, moneyButton; int money ; float damage; int averageSpawnDuration; float bossSpawnProbability; int moneyDelta; long nextVictimSpawnTick; long nextBlackCloudSpawnTick; long nextWhiteCloudSpawnTick; long centerTextDisappearTick; //Long.MAX_VALUE means click to disappear boolean policeWarningTriggered; long nextPoliceSpawnTick; private String centerTextString; long endGameTick; public static final int GAME_WIDTH = 960; public static final int GAME_HEIGHT = 500; private static final float MIN_VICTIM_SPEED = 50f; private static final float MAX_VICTIM_SPEED = 100f; private static final float AVERAGE_WHITE_CLOUD_SPAWN_DURATION = 2500; private static final float AVERAGE_BLACK_CLOUD_SPAWN_DURATION = 10000; private static final float MIN_CLOUD_SPEED = 25f; private static final float MAX_CLOUD_SPEED = 75f; private static final float AVERAGE_POLICE_SPAWN_DURATION = 100000; private static final float MIN_POLICE_SPEED = 100f; private static final float MAX_POLICE_SPEED = 250f; private static final float POLICE_WARNING_OFFSET = 5000; private static final long TEXT_FADEOUT_DURATION = 1000; private static final long GAME_END_SCENE_CROSSFACE_DURATION = 5000; public static LD33Game instance; @Override public void create () { instance = this; objectList = new Vector<GameObject>(); money = 0; damage = 1f; averageSpawnDuration = 10000; bossSpawnProbability = 0.25f; moneyDelta = 1; nextBlackCloudSpawnTick = Long.MIN_VALUE; centerTextDisappearTick = Long.MAX_VALUE; policeWarningTriggered = false; nextPoliceSpawnTick = Long.MIN_VALUE; centerTextString = "Poopie the Flying Monster\n\n Click to Play"; endGameTick = Long.MAX_VALUE; currentScene=null; boss = null; policeCar = null; effects = new Array<PooledEffect>(); camera = new OrthographicCamera(GAME_WIDTH, GAME_HEIGHT); camera.position.set(GAME_WIDTH/2, GAME_HEIGHT/2, 0); camera.update(); viewport = new FitViewport(GAME_WIDTH, GAME_HEIGHT, camera); sprite = new Texture("sprite.png"); batch = new SpriteBatch(); shapeRenderer = new ShapeRenderer(); winScene = new Texture("win.png"); loseScene = new Texture("lose.png"); background = new Texture("background.png"); bitmapFont = new BitmapFont(Gdx.files.internal("font.fnt")); attackButton = new Button(32, GAME_HEIGHT-32-32, 0, new int[]{3, 10, 50}, new Action(){ @Override void action(int level) { switch(level){ case 1: damage = 2; break; case 2: damage = 3; break; case 3: damage = 10; break; } } }); objectList.add(attackButton); rateButton = new Button(32, GAME_HEIGHT-32-32-64, 1, new int[]{3, 10, 50}, new Action(){ @Override void action(int level) { switch(level){ case 1: bird.poopReloadDuration = 1250; break; case 2: bird.poopReloadDuration = 500; break; case 3: bird.poopReloadDuration = 100; break; } } }); objectList.add(rateButton); flySpeedButton = new Button(32, GAME_HEIGHT-32-32-64*2, 2, new int[]{3, 10, 20}, new Action(){ @Override void action(int level) { switch(level){ case 1: bird.speed = 150f; break; case 2: bird.speed = 200f; break; case 3: bird.speed = 300f; break; } } }); objectList.add(flySpeedButton); spawnRateButton = new Button(32, GAME_HEIGHT-32-32-64*3, 3, new int[]{10, 50, 200}, new Action(){ @Override void action(int level) { switch(level){ case 1: averageSpawnDuration = 5000; bossSpawnProbability=0f; break; case 2: averageSpawnDuration = 2000; break; case 3: averageSpawnDuration = 1000; bossSpawnProbability=1f; break; } } }); objectList.add(spawnRateButton); moneyButton = new Button(32, GAME_HEIGHT-32-32-64*4, 4, new int[]{5, 10, 20}, new Action(){ @Override void action(int level) { switch(level){ case 1: moneyDelta = 2; break; case 2: moneyDelta = 3; break; case 3: moneyDelta = 4; break; } } }); objectList.add(moneyButton); ParticleEffect poopEffect = new ParticleEffect(); poopEffect.load(Gdx.files.internal("poopDrop.p"), Gdx.files.internal("")); poopEffectPool = new ParticleEffectPool(poopEffect, 8, 128); ParticleEffect poopedEffect = new ParticleEffect(); poopedEffect.load(Gdx.files.internal("pooped.p"), Gdx.files.internal("")); poopedEffectPool = new ParticleEffectPool(poopedEffect, 16, 1024); objectList.add(bird=new Bird(GAME_WIDTH/2, GAME_HEIGHT/2)); spawnVictim(); spawnBlackCloud(); spawnWhiteCloud(); } @Override public void render () { float deltaTime = Gdx.graphics.getDeltaTime(); Vector3 touchPos = new Vector3(); touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0); touchPos = camera.unproject(touchPos); Vector<GameObject> objectListClone = new Vector<GameObject>(objectList); //Do click handling if(currentScene==null){ if(Gdx.input.justTouched()){ if(policeCar!=null){ centerTextString = "Oh... Police found you being a monster..."; policeCar.activate(); } if(nextPoliceSpawnTick==Long.MIN_VALUE) spawnPoliceCar(); if(centerTextDisappearTick==Long.MAX_VALUE) centerTextDisappearTick = TimeUtils.millis(); boolean handled = false; for(GameObject i:objectList){ if(i instanceof Button){ if(new Rectangle(i.x-i.w/2, i.y-i.h/2, i.w, i.h).contains(touchPos.x, touchPos.y)){ ((Button)i).action(); handled = true; break; } } } if(!handled) bird.poop(); } //spawn items if(TimeUtils.millis()>nextVictimSpawnTick) spawnVictim(); if(TimeUtils.millis()>nextBlackCloudSpawnTick) spawnBlackCloud(); if(TimeUtils.millis()>nextWhiteCloudSpawnTick) spawnWhiteCloud(); if(!policeWarningTriggered&&nextPoliceSpawnTick!=Long.MIN_VALUE&&TimeUtils.millis()+POLICE_WARNING_OFFSET>nextPoliceSpawnTick){ policeWarningTriggered = true; centerTextString = "POLICE!\nSTOP POOPING!"; LD33Game.instance.centerTextDisappearTick = Long.MAX_VALUE-1; //TODO: play warning music here } if(TimeUtils.millis()>nextPoliceSpawnTick) spawnPoliceCar(); //update the objects for(GameObject i:objectListClone) i.onStep(deltaTime, (int)touchPos.x, (int)touchPos.y); //collision detection for(int i=0; i<objectListClone.size(); i++){ for(int j=i+1; j<objectListClone.size(); j++){ GameObject a = objectListClone.get(i); GameObject b = objectListClone.get(j); if(b instanceof Poop && a instanceof Victim ||b instanceof Bird && a instanceof Thunder ||b instanceof Bird && a instanceof PoliceCar){ GameObject c = a; a = b; b = c; } if(a instanceof Poop && b instanceof Victim){ if(((Victim)b).hp<=0) continue; if(new Rectangle(b.x-b.w/2, b.y-b.h/2, b.w, b.h).contains(a.x, a.y)){ ((Victim)b).hit(damage); ((Poop)a).effect.setDuration(0); objectList.remove(a); } }else if(a instanceof Bird && b instanceof Thunder){ if(new Rectangle(a.x-a.w/2, a.y-a.h/2, a.w, a.h) .overlaps(new Rectangle(b.x-b.w/2, b.y-b.h/2, b.w, b.h))){ objectList.remove(b); if(money<=1) money = 0; else money /= 2; objectList.add(new MoneyEyesCandy(a.x, a.y-32, -50f)); } }else if(a instanceof Bird && b instanceof PoliceCar){ if(Math.sqrt((b.x-a.x)*(b.x-a.x)+(b.y-a.y)*(b.y-a.y))<=64){ currentScene = loseScene; endGameTick = TimeUtils.millis(); } } } } }else{ if(Gdx.input.isKeyJustPressed(Keys.ESCAPE)){ create(); //restart the game return; } } //do the rendering Gdx.gl.glClearColor(1, 1, 1, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); batch.setProjectionMatrix(camera.combined); shapeRenderer.setProjectionMatrix(camera.combined); batch.begin(); batch.draw(background, 0, 0); //rendering particles for (int i = effects.size - 1; i >= 0; i--) { PooledEffect effect = effects.get(i); effect.draw(batch, deltaTime); if (effect.isComplete()) { effect.free(); effects.removeIndex(i); } } //render sprite for(GameObject i:objectList) i.render(batch, sprite); //render money string bitmapFont.getData().setScale(1f); LD33Game.instance.bitmapFont.draw(batch, "$"+Integer.toString(money), 0, GAME_HEIGHT); //render menu string if(TimeUtils.millis()-TEXT_FADEOUT_DURATION<centerTextDisappearTick){ if(TimeUtils.millis()>centerTextDisappearTick) LD33Game.instance.bitmapFont.setColor(1, 1, 1, 1f-(float)(TimeUtils.millis()-centerTextDisappearTick)/TEXT_FADEOUT_DURATION); LD33Game.instance.bitmapFont.draw(batch, centerTextString, 0, 400, GAME_WIDTH, Align.center, false); LD33Game.instance.bitmapFont.setColor(1, 1, 1, 1); } batch.end(); //render HP bar shapeRenderer.begin(ShapeType.Filled); for(GameObject i:objectList){ if(i instanceof Victim){ if(((Victim)i).hp==((Victim)i).getFullHp()) continue; float yOffset = i instanceof Boss?100:80; shapeRenderer.setColor(Color.RED); shapeRenderer.rect(i.x-i.w/2, i.y+yOffset, i.w, 10); if(((Victim)i).hp>0){ shapeRenderer.setColor(Color.GREEN); shapeRenderer.rect(i.x-i.w/2, i.y+yOffset, i.w*((Victim)i).hp/((Victim)i).getFullHp(), 10); } } } shapeRenderer.end(); if(currentScene!=null){ batch.setColor(1, 1, 1, (float)Math.min(1, (double)(TimeUtils.millis()-endGameTick)/(double)GAME_END_SCENE_CROSSFACE_DURATION)); batch.begin(); batch.draw(currentScene, 0, 0); batch.end(); } } @Override public void resize(int width, int height) { viewport.update(width, height); } private void spawnVictim() { nextVictimSpawnTick = TimeUtils.millis()+(long)(averageSpawnDuration/2+Math.random()*averageSpawnDuration); if(boss==null&&Math.random()<bossSpawnProbability){ objectList.add(boss=new Boss( (float)( (Math.random()<0.5?1:-1) *(MIN_VICTIM_SPEED+Math.random()*(MAX_VICTIM_SPEED-MIN_VICTIM_SPEED)) ) )); }else{ objectList.add(new Victim( (float)( (Math.random()<0.5?1:-1) *(MIN_VICTIM_SPEED+Math.random()*(MAX_VICTIM_SPEED-MIN_VICTIM_SPEED)) ) )); } } private void spawnWhiteCloud(){ if(nextWhiteCloudSpawnTick!=Long.MIN_VALUE){ objectList.add(new Cloud( (float)( (Math.random()<0.5?1:-1) *(MIN_CLOUD_SPEED+Math.random()*(MAX_CLOUD_SPEED-MIN_CLOUD_SPEED)) ) )); } nextWhiteCloudSpawnTick = TimeUtils.millis()+(long)(AVERAGE_WHITE_CLOUD_SPAWN_DURATION/2+Math.random()*AVERAGE_WHITE_CLOUD_SPAWN_DURATION); } private void spawnBlackCloud(){ if(nextBlackCloudSpawnTick!=Long.MIN_VALUE){ objectList.add(new BlackCloud( (float)( (Math.random()<0.5?1:-1) *(MIN_CLOUD_SPEED+Math.random()*(MAX_CLOUD_SPEED-MIN_CLOUD_SPEED)) ) )); } nextBlackCloudSpawnTick = TimeUtils.millis()+(long)(AVERAGE_BLACK_CLOUD_SPAWN_DURATION/2+Math.random()*AVERAGE_BLACK_CLOUD_SPAWN_DURATION); } private void spawnPoliceCar(){ if(nextPoliceSpawnTick!=Long.MIN_VALUE){ objectList.add(policeCar=new PoliceCar( (float)( (Math.random()<0.5?1:-1) *(MIN_POLICE_SPEED+Math.random()*(MAX_POLICE_SPEED-MIN_POLICE_SPEED)) ) )); } nextPoliceSpawnTick = TimeUtils.millis()+(long)(AVERAGE_POLICE_SPAWN_DURATION/2+Math.random()*AVERAGE_POLICE_SPAWN_DURATION); } }
Bugfix: police activated when you click buy item buttons
core/src/com/ld33/game/LD33Game.java
Bugfix: police activated when you click buy item buttons
Java
bsd-3-clause
b752a0b94423422100a9664d6be0127db214a970
0
mccraigmccraig/prefuse,mccraigmccraig/prefuse
package edu.berkeley.guir.prefuse.graph; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; /** * Library of useful operations on graphs. * * @version 1.0 * @author <a href="http://jheer.org">Jeffrey Heer</a> prefuse(AT)jheer.org */ public class GraphLib { public static Graph getStar(int n) { Node n0 = new TreeNode(); n0.setAttribute("label","n"+0); ArrayList al = new ArrayList(n+1); al.add(n0); for ( int i=1; i <= n; i++ ) { Node nn = new TreeNode(); nn.setAttribute("label","n"+i); Edge e = new Edge(n0, nn); n0.addEdge(e); nn.addEdge(e); al.add(nn); } return new SimpleGraph(al); } // public static Graph getClique(int n) { Node nodes[] = new Node[n]; ArrayList al = new ArrayList(n); for ( int i = 0; i < n; i++ ) { nodes[i] = new TreeNode(); nodes[i].setAttribute("label", "n"+i); al.add(nodes[i]); } for ( int i = 0; i < n; i++ ) { for ( int j = 0; j < n; j++ ) if ( i != j ) nodes[i].addNeighbor(nodes[j]); } return new SimpleGraph(al); } // public static Graph getGrid(int m, int n) { ArrayList nodes = new ArrayList(); for ( int i = 0; i < m*n; i++ ) { TreeNode node = new TreeNode(); node.setAttribute("label", "n"+i); nodes.add(node); if ( i >= n ) { TreeNode above = (TreeNode)nodes.get(i-n); Edge e = new Edge(above, node); node.addEdge(e); above.addEdge(e); } if ( i % n != 0 ) { TreeNode bfor = (TreeNode)nodes.get(i-1); Edge e = new Edge(bfor, node); node.addEdge(e); bfor.addEdge(e); } } return new SimpleGraph(nodes); } // public static final int SEARCH_NODES = 0; public static final int SEARCH_EDGES = 1; public static final int SEARCH_ALL = 2; /** * Performs a simple search, returning all nodes that exactly match the provided attribute. * @param g the graph to search over * @param attrName the attribute name to look up * @param attrValue the attribute value to match * @return a <code>List</code> of the matching <code>Node</code> objects */ public static List searchNodes(Graph g, String attrName, String attrValue) { return search(g, attrName, attrValue, SEARCH_NODES); } // public static void searchNodes(Graph g, Collection result, String query) { Iterator nodeIter = g.getNodes(); while ( nodeIter.hasNext() ) { Node n = (Node)nodeIter.next(); Iterator attIter = n.getAttributes().values().iterator(); while ( attIter.hasNext() ) { String value = (String)attIter.next(); if ( value.indexOf(query) > -1 ) { result.add(n); break; } } } } // /** * Performs a simple search, returning all Entities that exactly match the provided attribute. * @param g the graph to search over * @param attrName the attribute name to look up * @param attrValue the attribute value to match * @param type determines if nodes, edges, or both are searched. The legal values are * <code>SEARCH_NODES</code>, <code>SEARCH_EDGES</code>, <code>SEARCH_ALL</code>. * @return a <code>List</code> of the matching <code>Entity</code> objects */ public static List search(Graph g, String attrName, String attrValue, int type) { ArrayList result = new ArrayList(); if ( type == SEARCH_NODES || type == SEARCH_ALL ) { search(result, g.getNodes(), attrName, attrValue); } if ( type == SEARCH_EDGES || type == SEARCH_ALL ) { search(result, g.getEdges(), attrName, attrValue); } return result; } // private static void search(Collection result, Iterator iter, String attrName, String attrValue) { while ( iter.hasNext() ) { Entity e = (Entity)iter.next(); String val = e.getAttribute(attrName); if ( val != null && val.equals(attrValue) ) result.add(e); } } // // /** // * Filters a graph of unwanted entities, creating a new subgraph. // * @param og the original <code>Graph</code>. It will be not bechanged. // * @param func a FilterFunction that determines what entities are filtered. // * @return a new, filtered <code>Graph</code> instance. // */ // public static Graph getFilteredGraph(final Graph og, FilterFunction func) // { // SimpleGraph g = new SimpleGraph(); // HashMap nodeMap = new HashMap(); // Iterator iter = og.getNodes(); // while ( iter.hasNext() ) { // Node u = (Node)iter.next(); // if ( func.filter(u) ) { // Node v = null; // try { // v = (Node)u.getClass().newInstance(); // } catch ( Exception e ) { // e.printStackTrace(); // } // v.setAttributes(u.getAttributes()); // nodeMap.put(u,v); // g.addNode(v); // } // } // iter = og.getEdges(); // while ( iter.hasNext() ) { // Edge e = (Edge)iter.next(); // Node v1 = (Node)nodeMap.get(e.getFirstNode()); // Node v2 = (Node)nodeMap.get(e.getSecondNode()); // if ( v1 != null && v2 != null && func.filter(e) ) { // Edge e2 = new Edge(v1, v2); // e2.setAttributes(e.getAttributes()); // g.addEdge(e2); // } // } // return g; // } // // // /** // * Filters a graph of unwanted entities. // * @param g the graph to filter // * @param func a FilterFunction that determines what entities are filtered. // */ // public static void filterGraph(SimpleGraph g, FilterFunction func) { // Iterator iter = g.getNodes(); // List removeList = new ArrayList(); // while ( iter.hasNext() ) { // Node u = (Node)iter.next(); // if ( !func.filter(u) ) { // removeList.add(u); // } // } // iter = removeList.iterator(); // while ( iter.hasNext() ) // g.removeNode((Node)iter.next()); // removeList.clear(); // iter = g.getEdges(); // while ( iter.hasNext() ) { // Edge e = (Edge)iter.next(); // if ( !func.filter(e) ) { // removeList.add(e); // } // } // iter = removeList.iterator(); // while ( iter.hasNext() ) // g.removeEdge((Edge)iter.next()); // removeList.clear(); // } // } // end of class GraphLib
src/edu/berkeley/guir/prefuse/graph/GraphLib.java
package edu.berkeley.guir.prefuse.graph; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; /** * Library of useful operations on graphs. * * @version 1.0 * @author <a href="http://jheer.org">Jeffrey Heer</a> prefuse(AT)jheer.org */ public class GraphLib { public static Graph getStar(int n) { Node n0 = new TreeNode(); n0.setAttribute("label","n"+0); ArrayList al = new ArrayList(n+1); al.add(n0); for ( int i=1; i <= n; i++ ) { Node nn = new TreeNode(); nn.setAttribute("label","n"+i); Edge e = new Edge(n0, nn); n0.addEdge(e); nn.addEdge(e); al.add(nn); } return new SimpleGraph(al); } // public static Graph getClique(int n) { Node nodes[] = new Node[n]; ArrayList al = new ArrayList(n); for ( int i = 0; i < n; i++ ) { nodes[i] = new TreeNode(); nodes[i].setAttribute("label", "n"+i); al.add(nodes[i]); } for ( int i = 0; i < n; i++ ) { for ( int j = 0; j < n; j++ ) if ( i != j ) nodes[i].addNeighbor(nodes[j]); } return new SimpleGraph(al); } // public static Graph getGrid(int m, int n) { ArrayList nodes = new ArrayList(); for ( int i = 0; i < m*n; i++ ) { TreeNode node = new TreeNode(); node.setAttribute("label", "n"+i); nodes.add(node); if ( i >= m ) { TreeNode above = (TreeNode)nodes.get(i-m); Edge e = new Edge(above, node); node.addEdge(e); above.addEdge(e); } if ( i % m != 0 ) { TreeNode bfor = (TreeNode)nodes.get(i-1); Edge e = new Edge(bfor, node); node.addEdge(e); bfor.addEdge(e); } } return new SimpleGraph(nodes); } // public static final int SEARCH_NODES = 0; public static final int SEARCH_EDGES = 1; public static final int SEARCH_ALL = 2; /** * Performs a simple search, returning all nodes that exactly match the provided attribute. * @param g the graph to search over * @param attrName the attribute name to look up * @param attrValue the attribute value to match * @return a <code>List</code> of the matching <code>Node</code> objects */ public static List searchNodes(Graph g, String attrName, String attrValue) { return search(g, attrName, attrValue, SEARCH_NODES); } // public static void searchNodes(Graph g, Collection result, String query) { Iterator nodeIter = g.getNodes(); while ( nodeIter.hasNext() ) { Node n = (Node)nodeIter.next(); Iterator attIter = n.getAttributes().values().iterator(); while ( attIter.hasNext() ) { String value = (String)attIter.next(); if ( value.indexOf(query) > -1 ) { result.add(n); break; } } } } // /** * Performs a simple search, returning all Entities that exactly match the provided attribute. * @param g the graph to search over * @param attrName the attribute name to look up * @param attrValue the attribute value to match * @param type determines if nodes, edges, or both are searched. The legal values are * <code>SEARCH_NODES</code>, <code>SEARCH_EDGES</code>, <code>SEARCH_ALL</code>. * @return a <code>List</code> of the matching <code>Entity</code> objects */ public static List search(Graph g, String attrName, String attrValue, int type) { ArrayList result = new ArrayList(); if ( type == SEARCH_NODES || type == SEARCH_ALL ) { search(result, g.getNodes(), attrName, attrValue); } if ( type == SEARCH_EDGES || type == SEARCH_ALL ) { search(result, g.getEdges(), attrName, attrValue); } return result; } // private static void search(Collection result, Iterator iter, String attrName, String attrValue) { while ( iter.hasNext() ) { Entity e = (Entity)iter.next(); String val = e.getAttribute(attrName); if ( val != null && val.equals(attrValue) ) result.add(e); } } // // /** // * Filters a graph of unwanted entities, creating a new subgraph. // * @param og the original <code>Graph</code>. It will be not bechanged. // * @param func a FilterFunction that determines what entities are filtered. // * @return a new, filtered <code>Graph</code> instance. // */ // public static Graph getFilteredGraph(final Graph og, FilterFunction func) // { // SimpleGraph g = new SimpleGraph(); // HashMap nodeMap = new HashMap(); // Iterator iter = og.getNodes(); // while ( iter.hasNext() ) { // Node u = (Node)iter.next(); // if ( func.filter(u) ) { // Node v = null; // try { // v = (Node)u.getClass().newInstance(); // } catch ( Exception e ) { // e.printStackTrace(); // } // v.setAttributes(u.getAttributes()); // nodeMap.put(u,v); // g.addNode(v); // } // } // iter = og.getEdges(); // while ( iter.hasNext() ) { // Edge e = (Edge)iter.next(); // Node v1 = (Node)nodeMap.get(e.getFirstNode()); // Node v2 = (Node)nodeMap.get(e.getSecondNode()); // if ( v1 != null && v2 != null && func.filter(e) ) { // Edge e2 = new Edge(v1, v2); // e2.setAttributes(e.getAttributes()); // g.addEdge(e2); // } // } // return g; // } // // // /** // * Filters a graph of unwanted entities. // * @param g the graph to filter // * @param func a FilterFunction that determines what entities are filtered. // */ // public static void filterGraph(SimpleGraph g, FilterFunction func) { // Iterator iter = g.getNodes(); // List removeList = new ArrayList(); // while ( iter.hasNext() ) { // Node u = (Node)iter.next(); // if ( !func.filter(u) ) { // removeList.add(u); // } // } // iter = removeList.iterator(); // while ( iter.hasNext() ) // g.removeNode((Node)iter.next()); // removeList.clear(); // iter = g.getEdges(); // while ( iter.hasNext() ) { // Edge e = (Edge)iter.next(); // if ( !func.filter(e) ) { // removeList.add(e); // } // } // iter = removeList.iterator(); // while ( iter.hasNext() ) // g.removeEdge((Edge)iter.next()); // removeList.clear(); // } // } // end of class GraphLib
fixed bug in getGrid
src/edu/berkeley/guir/prefuse/graph/GraphLib.java
fixed bug in getGrid
Java
bsd-3-clause
e97875f99bf75e971eb60fd7e160aae1a6613f06
0
bdezonia/zorbage,bdezonia/zorbage
/* * Zorbage: an algebraic data hierarchy for use in numeric processing. * * Copyright (C) 2016-2018 Barry DeZonia * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package nom.bdezonia.zorbage.algorithm; import nom.bdezonia.zorbage.type.data.float64.complex.ComplexFloat64Group; import nom.bdezonia.zorbage.type.data.float64.complex.ComplexFloat64Member; import nom.bdezonia.zorbage.type.storage.IndexedDataSource; /** * * @author Barry DeZonia * */ public class FFT { // don't instantiate private FFT() {} /** * * @param group * @param a * @param b */ public static void compute(ComplexFloat64Group group, IndexedDataSource<?,ComplexFloat64Member> a, IndexedDataSource<?,ComplexFloat64Member> b) { if (a.size() != FFT.enclosingPowerOf2(a.size())) throw new IllegalArgumentException("input size is not a power of 2"); if (a.size() != b.size()) throw new IllegalArgumentException("output size does not match input size"); ComplexFloat64Member tmp1 = group.construct(); ComplexFloat64Member tmp2 = group.construct(); // bit reversal permutation int shift = 1 + Long.numberOfLeadingZeros(a.size()); for (long k = 0; k < a.size(); k++) { long j = Long.reverse(k) >>> shift; a.get(j, tmp1); a.get(k, tmp2); if (j > k) { b.set(k, tmp1); b.set(j, tmp2); } else { b.set(j, tmp1); b.set(k, tmp2); } } ComplexFloat64Member w = group.construct(); ComplexFloat64Member tao = group.construct(); // butterfly updates for (long L = 2; L <= a.size(); L = L+L) { for (long k = 0; k < L/2; k++) { double kth = -2 * k * Math.PI / L; w.setR(Math.cos(kth)); w.setI(Math.sin(kth)); for (long j = 0; j < a.size()/L; j++) { b.get(j*L + k + L/2, tmp1); group.multiply(w, tmp1, tao); b.get(j*L + k, tmp2); group.subtract(tmp2, tao, tmp1); b.set(j*L + k + L/2, tmp1); group.add(tmp2, tao, tmp1); b.set(j*L + k, tmp1); } } } } /** * * @param num * @return */ public static long enclosingPowerOf2(long num) { if (num <= 0) throw new IllegalArgumentException("num too small"); long max = 1; for (int i = 0; i < 63; i++) { if (num <= max) return max; max <<= 1; } throw new IllegalArgumentException("num too big"); } }
src/main/java/nom/bdezonia/zorbage/algorithm/FFT.java
/* * Zorbage: an algebraic data hierarchy for use in numeric processing. * * Copyright (C) 2016-2018 Barry DeZonia * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package nom.bdezonia.zorbage.algorithm; import nom.bdezonia.zorbage.type.data.float64.complex.ComplexFloat64Group; import nom.bdezonia.zorbage.type.data.float64.complex.ComplexFloat64Member; import nom.bdezonia.zorbage.type.storage.IndexedDataSource; /** * * @author Barry DeZonia * */ public class FFT { // don't instantiate private FFT() {} /** * * @param group * @param a * @param b */ public static void compute(ComplexFloat64Group group, IndexedDataSource<?,ComplexFloat64Member> a, IndexedDataSource<?,ComplexFloat64Member> b) { if (a.size() != FFT.enclosingPowerOf2(a.size())) throw new IllegalArgumentException("input size is not a power of 2"); if (a.size() != b.size()) throw new IllegalArgumentException("output size does not match input size"); ComplexFloat64Member tmp1 = group.construct(); ComplexFloat64Member tmp2 = group.construct(); // bit reversal permutation int shift = 1 + Long.numberOfLeadingZeros(a.size()); for (long k = 0; k < a.size(); k++) { long j = Long.reverse(k) >>> shift; a.get(j, tmp1); a.get(k, tmp2); if (j > k) { b.set(k, tmp1); b.set(j, tmp2); } else { b.set(j, tmp1); b.set(k, tmp2); } } ComplexFloat64Member w = group.construct(); ComplexFloat64Member tao = group.construct(); // butterfly updates for (long L = 2; L <= a.size(); L = L+L) { for (long k = 0; k < L/2; k++) { double kth = -2 * k * Math.PI / L; w.setR(Math.cos(kth)); w.setI(Math.sin(kth)); for (long j = 0; j < a.size()/L; j++) { b.get(j*L + k + L/2, tmp1); group.multiply(w, tmp1, tao); b.get(j*L + k, tmp2); group.subtract(tmp2, tao, tmp1); b.set(j*L + k + L/2, tmp1); group.add(tmp2, tao, tmp1); b.set(j*L + k, tmp1); } } } } /** * * @param num * @return */ public static long enclosingPowerOf2(long num) { if (num <= 0) throw new IllegalArgumentException("num too small"); long max = 1; for (int i = 0; i < 63; i++) { if (num <= max) return max; max <<= 1; } throw new IllegalArgumentException("num too big"); } }
Whitespace changes
src/main/java/nom/bdezonia/zorbage/algorithm/FFT.java
Whitespace changes
Java
bsd-3-clause
e94a4672b5d62fde4a9a9e61099f9d3e50dbb09e
0
cerebro/ggp-base,cerebro/ggp-base
package org.ggp.base.util.gdl.factory; import java.util.ArrayList; import java.util.List; import org.ggp.base.util.gdl.factory.exceptions.GdlFormatException; import org.ggp.base.util.gdl.grammar.Gdl; import org.ggp.base.util.gdl.grammar.GdlConstant; import org.ggp.base.util.gdl.grammar.GdlDistinct; import org.ggp.base.util.gdl.grammar.GdlFunction; import org.ggp.base.util.gdl.grammar.GdlLiteral; import org.ggp.base.util.gdl.grammar.GdlNot; import org.ggp.base.util.gdl.grammar.GdlOr; import org.ggp.base.util.gdl.grammar.GdlPool; import org.ggp.base.util.gdl.grammar.GdlProposition; import org.ggp.base.util.gdl.grammar.GdlRelation; import org.ggp.base.util.gdl.grammar.GdlRule; import org.ggp.base.util.gdl.grammar.GdlSentence; import org.ggp.base.util.gdl.grammar.GdlTerm; import org.ggp.base.util.gdl.grammar.GdlVariable; import org.ggp.base.util.symbol.factory.SymbolFactory; import org.ggp.base.util.symbol.factory.exceptions.SymbolFormatException; import org.ggp.base.util.symbol.grammar.Symbol; import org.ggp.base.util.symbol.grammar.SymbolAtom; import org.ggp.base.util.symbol.grammar.SymbolList; public final class GdlFactory { public static Gdl create(String string) throws GdlFormatException, SymbolFormatException { return create(SymbolFactory.create(string)); } public static Gdl create(Symbol symbol) throws GdlFormatException { try { return createGdl(symbol); } catch (Exception e) { createGdl(symbol); throw new GdlFormatException(symbol); } } private static GdlConstant createConstant(SymbolAtom atom) { return GdlPool.getConstant(atom.getValue()); } private static GdlDistinct createDistinct(SymbolList list) { GdlTerm arg1 = createTerm(list.get(1)); GdlTerm arg2 = createTerm(list.get(2)); return GdlPool.getDistinct(arg1, arg2); } private static GdlFunction createFunction(SymbolList list) { GdlConstant name = createConstant((SymbolAtom) list.get(0)); List<GdlTerm> body = new ArrayList<GdlTerm>(); for (int i = 1; i < list.size(); i++) { body.add(createTerm(list.get(i))); } return GdlPool.getFunction(name, body); } private static Gdl createGdl(Symbol symbol) { if (symbol instanceof SymbolList) { SymbolList list = (SymbolList) symbol; SymbolAtom type = (SymbolAtom) list.get(0); if (type.getValue().equals("<=")) { return createRule(list); } } return createSentence(symbol); } private static GdlLiteral createLiteral(Symbol symbol) { if (symbol instanceof SymbolList) { SymbolList list = (SymbolList) symbol; SymbolAtom type = (SymbolAtom) list.get(0); if (type.getValue().toLowerCase().equals("distinct")) { return createDistinct(list); } else if (type.getValue().toLowerCase().equals("not")) { return createNot(list); } else if (type.getValue().toLowerCase().equals("or")) { return createOr(list); } } return createSentence(symbol); } private static GdlNot createNot(SymbolList list) { return GdlPool.getNot(createLiteral(list.get(1))); } private static GdlOr createOr(SymbolList list) { List<GdlLiteral> disjuncts = new ArrayList<GdlLiteral>(); for (int i = 1; i < list.size(); i++) { disjuncts.add(createLiteral(list.get(i))); } return GdlPool.getOr(disjuncts); } private static GdlProposition createProposition(SymbolAtom atom) { return GdlPool.getProposition(createConstant(atom)); } private static GdlRelation createRelation(SymbolList list) { GdlConstant name = createConstant((SymbolAtom) list.get(0)); List<GdlTerm> body = new ArrayList<GdlTerm>(); for (int i = 1; i < list.size(); i++) { body.add(createTerm(list.get(i))); } return GdlPool.getRelation(name, body); } private static GdlRule createRule(SymbolList list) { GdlSentence head = createSentence(list.get(1)); List<GdlLiteral> body = new ArrayList<GdlLiteral>(); for (int i = 2; i < list.size(); i++) { body.add(createLiteral(list.get(i))); } return GdlPool.getRule(head, body); } private static GdlSentence createSentence(Symbol symbol) { if (symbol instanceof SymbolAtom) { return createProposition((SymbolAtom) symbol); } else { return createRelation((SymbolList) symbol); } } public static GdlTerm createTerm(String string) throws SymbolFormatException { return createTerm(SymbolFactory.create(string)); } public static GdlTerm createTerm(Symbol symbol) { if (symbol instanceof SymbolAtom) { SymbolAtom atom = (SymbolAtom) symbol; if (atom.getValue().charAt(0) == '?') { return createVariable(atom); } else { return createConstant(atom); } } else { return createFunction((SymbolList) symbol); } } private static GdlVariable createVariable(SymbolAtom atom) { return GdlPool.getVariable(atom.getValue()); } }
ggp-base/src/org/ggp/base/util/gdl/factory/GdlFactory.java
package org.ggp.base.util.gdl.factory; import java.util.ArrayList; import java.util.List; import org.ggp.base.util.gdl.factory.exceptions.GdlFormatException; import org.ggp.base.util.gdl.grammar.Gdl; import org.ggp.base.util.gdl.grammar.GdlConstant; import org.ggp.base.util.gdl.grammar.GdlDistinct; import org.ggp.base.util.gdl.grammar.GdlFunction; import org.ggp.base.util.gdl.grammar.GdlLiteral; import org.ggp.base.util.gdl.grammar.GdlNot; import org.ggp.base.util.gdl.grammar.GdlOr; import org.ggp.base.util.gdl.grammar.GdlPool; import org.ggp.base.util.gdl.grammar.GdlProposition; import org.ggp.base.util.gdl.grammar.GdlRelation; import org.ggp.base.util.gdl.grammar.GdlRule; import org.ggp.base.util.gdl.grammar.GdlSentence; import org.ggp.base.util.gdl.grammar.GdlTerm; import org.ggp.base.util.gdl.grammar.GdlVariable; import org.ggp.base.util.symbol.factory.SymbolFactory; import org.ggp.base.util.symbol.factory.exceptions.SymbolFormatException; import org.ggp.base.util.symbol.grammar.Symbol; import org.ggp.base.util.symbol.grammar.SymbolAtom; import org.ggp.base.util.symbol.grammar.SymbolList; public final class GdlFactory { public static Gdl create(String string) throws GdlFormatException, SymbolFormatException { return create(SymbolFactory.create(string)); } public static Gdl create(Symbol symbol) throws GdlFormatException { try { return createGdl(symbol); } catch (Exception e) { createGdl(symbol); throw new GdlFormatException(symbol); } } private static GdlConstant createConstant(SymbolAtom atom) { return GdlPool.getConstant(atom.getValue()); } private static GdlDistinct createDistinct(SymbolList list) { GdlTerm arg1 = createTerm(list.get(1)); GdlTerm arg2 = createTerm(list.get(2)); return GdlPool.getDistinct(arg1, arg2); } private static GdlFunction createFunction(SymbolList list) { GdlConstant name = createConstant((SymbolAtom) list.get(0)); List<GdlTerm> body = new ArrayList<GdlTerm>(); for (int i = 1; i < list.size(); i++) { body.add(createTerm(list.get(i))); } return GdlPool.getFunction(name, body); } private static Gdl createGdl(Symbol symbol) { if (symbol instanceof SymbolList) { SymbolList list = (SymbolList) symbol; SymbolAtom type = (SymbolAtom) list.get(0); if (type.getValue().equals("<=")) { return createRule(list); } } return createSentence(symbol); } private static GdlLiteral createLiteral(Symbol symbol) { if (symbol instanceof SymbolList) { SymbolList list = (SymbolList) symbol; SymbolAtom type = (SymbolAtom) list.get(0); if (type.getValue().toLowerCase().equals("distinct")) { return createDistinct(list); } else if (type.getValue().toLowerCase().equals("not")) { return createNot(list); } else if (type.getValue().toLowerCase().equals("or")) { return createOr(list); } } return createSentence(symbol); } private static GdlNot createNot(SymbolList list) { return GdlPool.getNot(createLiteral(list.get(1))); } private static GdlOr createOr(SymbolList list) { List<GdlLiteral> disjuncts = new ArrayList<GdlLiteral>(); for (int i = 1; i < list.size(); i++) { disjuncts.add(createLiteral(list.get(i))); } return GdlPool.getOr(disjuncts); } private static GdlProposition createProposition(SymbolAtom atom) { return GdlPool.getProposition(createConstant(atom)); } private static GdlRelation createRelation(SymbolList list) { GdlConstant name = createConstant((SymbolAtom) list.get(0)); List<GdlTerm> body = new ArrayList<GdlTerm>(); for (int i = 1; i < list.size(); i++) { body.add(createTerm(list.get(i))); } return GdlPool.getRelation(name, body); } private static GdlRule createRule(SymbolList list) { GdlSentence head = createSentence(list.get(1)); List<GdlLiteral> body = new ArrayList<GdlLiteral>(); for (int i = 2; i < list.size(); i++) { body.add(createLiteral(list.get(i))); } return GdlPool.getRule(head, body); } private static GdlSentence createSentence(Symbol symbol) { if (symbol instanceof SymbolAtom) { return createProposition((SymbolAtom) symbol); } else { return createRelation((SymbolList) symbol); } } public static GdlTerm createTerm(String string) throws SymbolFormatException { return createTerm(SymbolFactory.create(string)); } public static GdlTerm createTerm(Symbol symbol) { if (symbol instanceof SymbolAtom) { SymbolAtom atom = (SymbolAtom) symbol; if (atom.getValue().charAt(0) == '?') { return createVariable(atom); } else { return createConstant(atom); } } else { return createFunction((SymbolList) symbol); } } private static GdlVariable createVariable(SymbolAtom atom) { return GdlPool.getVariable(atom.getValue()); } }
Adjust some whitespace. git-svn-id: 4739e81c2fe647bfb539b919360e2c658e6121ea@514 716a755e-b13f-cedc-210d-596dafc6fb9b
ggp-base/src/org/ggp/base/util/gdl/factory/GdlFactory.java
Adjust some whitespace.
Java
bsd-3-clause
d7f288d811b321717b793c02cbd9f1df2fe06afa
0
bdezonia/zorbage,bdezonia/zorbage
/* * Zorbage: an algebraic data hierarchy for use in numeric processing. * * Copyright (C) 2016-2017 Barry DeZonia * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package zorbage.type.data.int128; import zorbage.algorithm.Gcd; import zorbage.algorithm.Lcm; import zorbage.type.algebra.BitOperations; import zorbage.type.algebra.Bounded; import zorbage.type.algebra.Integer; import zorbage.type.algebra.Random; /** * * @author Barry DeZonia * */ public class UnsignedInt128Group implements Integer<UnsignedInt128Group, UnsignedInt128Member>, Bounded<UnsignedInt128Member>, BitOperations<UnsignedInt128Member>, Random<UnsignedInt128Member> { // TODO // 1) convert byte references and constants to long references and constants // 2) speed test versus imglib private static final java.util.Random rng = new java.util.Random(System.currentTimeMillis()); private static final UnsignedInt128Member ZERO = new UnsignedInt128Member(); private static final UnsignedInt128Member ONE = new UnsignedInt128Member((byte)0,(byte)1); @Override public UnsignedInt128Member construct() { return new UnsignedInt128Member(); } @Override public UnsignedInt128Member construct(UnsignedInt128Member other) { return new UnsignedInt128Member(other); } @Override public UnsignedInt128Member construct(String str) { return new UnsignedInt128Member(str); } @Override public boolean isEqual(UnsignedInt128Member a, UnsignedInt128Member b) { return a.lo == b.lo && a.hi == b.hi; } @Override public boolean isNotEqual(UnsignedInt128Member a, UnsignedInt128Member b) { return !isEqual(a, b); } @Override public void assign(UnsignedInt128Member from, UnsignedInt128Member to) { to.set(from); } @Override public void zero(UnsignedInt128Member a) { a.hi = a.lo = 0; } // TODO: this shows that unsigned numbers aren't quite ints. They should derive slightly differently // in the algebra hierarchy. @Override public void negate(UnsignedInt128Member a, UnsignedInt128Member b) { assign(a,b); // ignore } @Override public void add(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member c) { byte cLo = (byte) (a.lo + b.lo); byte cHi = (byte) (a.hi + b.hi); int correction = 0; byte alh = (byte) (a.lo & 0x80); byte blh = (byte) (b.lo & 0x80); if (alh != 0 && blh != 0) { correction = 1; } else if ((alh != 0 && blh == 0) || (alh == 0 && blh != 0)) { byte all = (byte) (a.lo & 0x7f); byte bll = (byte) (b.lo & 0x7f); if ((byte)(all + bll) < 0) correction = 1; } cHi += correction; c.lo = cLo; c.hi = cHi; } @Override public void subtract(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member c) { byte cHi = (byte) (a.hi - b.hi); byte cLo = (byte) (a.lo - b.lo); final int correction; int alh = a.lo & 0x80; int blh = b.lo & 0x80; if (alh == 0 && blh != 0) correction = 1; else if (alh != 0 && blh == 0) { correction = 0; } else { // alh == blh int all = a.lo & 0x7f; int bll = b.lo & 0x7f; if (all < bll) correction = 1; else // (all >= bll) correction = 0; } cHi -= correction; c.lo = cLo; c.hi = cHi; } @Override public void multiply(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member c) { UnsignedInt128Member bTmp = new UnsignedInt128Member(b); UnsignedInt128Member tmp = new UnsignedInt128Member(); UnsignedInt128Member part = new UnsignedInt128Member(a); while (isNotEqual(bTmp,ZERO)) { if ((bTmp.lo & 1) > 0) { add(tmp, part, tmp); } shiftLeftOneBit(part); shiftRightOneBit(bTmp); } assign(tmp,c); } public void multiplyFast(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member c) { byte all = (byte) (a.lo & 0xf); byte alh = (byte) ((a.lo & 0xf0) >>> 4); byte bll = (byte) (b.lo & 0xf); byte blh = (byte) ((b.lo & 0xf0) >>> 4); byte loLoNib = (byte) (all * bll); byte loHiNib = (byte) ((all * blh) + (alh * bll)); if ((loLoNib & 0xf0) != 0) { loHiNib++; loLoNib &= 0xf; } byte hiLoNib = (byte) (alh * blh); if ((loHiNib & 0xf0) != 0) { hiLoNib++; loHiNib &= 0xf; } byte mid1 = (byte) (a.lo * b.hi); byte mid2 = (byte) (a.hi * b.lo); // can throw away a.hi * b.hi: all overflow c.lo = (byte)((loHiNib << 4) + loLoNib); c.hi = (byte) (hiLoNib + mid1 + mid2); } @Override public void power(int power, UnsignedInt128Member a, UnsignedInt128Member b) { if (power == 0 && isEqual(a, ZERO)) throw new IllegalArgumentException("0^0 is not a number"); if (power < 0) throw new IllegalArgumentException("Cannot get negative powers from integers"); UnsignedInt128Member tmp = new UnsignedInt128Member(ONE); for (int i = 0; i < power; i++) multiply(tmp, a, tmp); assign(tmp, b); } @Override public void unity(UnsignedInt128Member result) { assign(ONE, result); } @Override public boolean isLess(UnsignedInt128Member a, UnsignedInt128Member b) { return compare(a,b) < 0; } @Override public boolean isLessEqual(UnsignedInt128Member a, UnsignedInt128Member b) { return compare(a,b) <= 0; } @Override public boolean isGreater(UnsignedInt128Member a, UnsignedInt128Member b) { return compare(a,b) > 0; } @Override public boolean isGreaterEqual(UnsignedInt128Member a, UnsignedInt128Member b) { return compare(a,b) >= 0; } @Override public int compare(UnsignedInt128Member a, UnsignedInt128Member b) { int abyte, bbyte; int ab = a.hi & 0x80; int bb = b.hi & 0x80; if (ab == 0 && bb != 0) { return -1; } else if (ab != 0 && bb == 0) { return 1; } else { // ab == bb abyte = a.hi & 0x7f; bbyte = b.hi & 0x7f; if (abyte < bbyte) return -1; else if (abyte > bbyte) return 1; else { // a.hi == b.hi ab = a.lo & 0x80; bb = b.lo & 0x80; if (ab == 0 && bb != 0) { return -1; } else if (ab != 0 && bb == 0) { return 1; } else { // ab == bb abyte = a.lo & 0x7f; bbyte = b.lo & 0x7f; if (abyte < bbyte) return -1; else if (abyte > bbyte) return 1; else return 0; } } } } @Override public int signum(UnsignedInt128Member a) { return compare(a,ZERO); } @Override public void min(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member c) { if (compare(a,b) < 0) assign(a, c); else assign(b, c); } @Override public void max(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member c) { if (compare(a,b) > 0) assign(a, c); else assign(b, c); } @Override public void abs(UnsignedInt128Member a, UnsignedInt128Member b) { assign(a, b); } @Override public void norm(UnsignedInt128Member a, UnsignedInt128Member b) { assign(a, b); } @Override public void div(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member d) { UnsignedInt128Member m = new UnsignedInt128Member(); divMod(a,b,d,m); } @Override public void mod(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member m) { UnsignedInt128Member d = new UnsignedInt128Member(); divMod(a,b,d,m); } @Override public void divMod(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member d, UnsignedInt128Member m) { if (isEqual(b, ZERO)) { throw new IllegalArgumentException("divide by zero error in UnsignedInt128Group"); } int comparison = compare(a,b); if (comparison == 0) { // a is equal b assign(ONE, d); assign(ZERO, m); return; } if (comparison < 0) { // a is less than b assign(ZERO, d); assign(a, m); return; } // if here a is greater than b UnsignedInt128Member quotient = new UnsignedInt128Member(); UnsignedInt128Member dividend = new UnsignedInt128Member(a); UnsignedInt128Member divisor = new UnsignedInt128Member(b); int dividendLeadingNonzeroBit = leadingNonZeroBit(a); int divisorLeadingNonzeroBit = leadingNonZeroBit(b); bitShiftLeft((dividendLeadingNonzeroBit - divisorLeadingNonzeroBit), divisor, divisor); for (int i = 0; i < dividendLeadingNonzeroBit-divisorLeadingNonzeroBit+1; i++) { shiftLeftOneBit(quotient); if (isGreaterEqual(dividend, divisor)) { subtract(dividend, divisor, dividend); quotient.lo |= 1; } shiftRightOneBit(divisor); } assign(quotient, d); assign(dividend, m); } private int leadingNonZeroBit(UnsignedInt128Member num) { int mask = 0x80; for (int i = 0; i < 8; i++) { if ((num.hi & mask) != 0) { return 15 - i; } mask >>>= 1; } mask = 0x80; for (int i = 0; i < 8; i++) { if ((num.lo & mask) != 0) { return 7 - i; } mask >>>= 1; } return -1; } @Override public void gcd(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member c) { Gcd.compute(this, a, b, c); } @Override public void lcm(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member c) { Lcm.compute(this, a, b, c); } @Override public boolean isEven(UnsignedInt128Member a) { return a.lo % 2 == 0; } @Override public boolean isOdd(UnsignedInt128Member a) { return a.lo % 2 == 1; } @Override public void pred(UnsignedInt128Member a, UnsignedInt128Member b) { subtract(a,ONE,b); } @Override public void succ(UnsignedInt128Member a, UnsignedInt128Member b) { add(a,ONE,b); } @Override public void pow(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member c) { int cmp = signum(b); if (cmp < 0) throw new IllegalArgumentException("Cannot get negative powers from integers"); if (cmp == 0 && signum(a) == 0) throw new IllegalArgumentException("0^0 is not a number"); UnsignedInt128Member tmp = new UnsignedInt128Member(ONE); UnsignedInt128Member pow = new UnsignedInt128Member(b); while (!isEqual(pow, ZERO)) { multiply(tmp, a, tmp); pred(pow,pow); } assign(tmp, c); } @Override public void random(UnsignedInt128Member a) { a.lo = (byte) (rng.nextInt(256) - 0x80); a.hi = (byte) (rng.nextInt(256) - 0x80); } @Override public void bitAnd(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member c) { c.lo = (byte) (a.lo & b.lo); c.hi = (byte) (a.hi & b.hi); } @Override public void bitOr(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member c) { c.lo = (byte) (a.lo | b.lo); c.hi = (byte) (a.hi | b.hi); } @Override public void bitXor(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member c) { c.lo = (byte) (a.lo ^ b.lo); c.hi = (byte) (a.hi ^ b.hi); } @Override public void bitNot(UnsignedInt128Member a, UnsignedInt128Member b) { b.lo = (byte) ~a.lo; b.hi = (byte) ~a.hi; } // TODO improve performance @Override public void bitShiftLeft(int count, UnsignedInt128Member a, UnsignedInt128Member b) { if (count < 0) bitShiftRight(Math.abs(count), a, b); else { count = count % 0x80; UnsignedInt128Member tmp = new UnsignedInt128Member(a); for (int i = 0; i < count; i++) { shiftLeftOneBit(tmp); } assign(tmp, b); } } // TODO improve performance @Override public void bitShiftRight(int count, UnsignedInt128Member a, UnsignedInt128Member b) { if (count < 0) bitShiftLeft(Math.abs(count), a, b); else if (count > 0x7f) assign(ZERO, b); else { UnsignedInt128Member tmp = new UnsignedInt128Member(a); for (int i = 0; i < count; i++) { shiftRightOneBit(tmp); } assign(tmp, b); } } @Override public void maxBound(UnsignedInt128Member a) { a.lo = -1; a.hi = -1; } @Override public void minBound(UnsignedInt128Member a) { a.lo = 0; a.hi = 0; } private void shiftLeftOneBit(UnsignedInt128Member val) { boolean transitionBit = (val.lo & 0x80) != 0; val.lo = (byte) ((val.lo & 0xff) << 1); val.hi = (byte) ((val.hi & 0xff) << 1); if (transitionBit) val.hi |= 1; } private void shiftRightOneBit(UnsignedInt128Member val) { boolean transitionBit = (val.hi & 1) != 0; val.lo = (byte) ((val.lo & 0xff) >>> 1); val.hi = (byte) ((val.hi & 0xff) >>> 1); if (transitionBit) val.lo |= 0x80; } }
src/zorbage/type/data/int128/UnsignedInt128Group.java
/* * Zorbage: an algebraic data hierarchy for use in numeric processing. * * Copyright (C) 2016-2017 Barry DeZonia * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package zorbage.type.data.int128; import zorbage.algorithm.Gcd; import zorbage.algorithm.Lcm; import zorbage.type.algebra.BitOperations; import zorbage.type.algebra.Bounded; import zorbage.type.algebra.Integer; import zorbage.type.algebra.Random; /** * * @author Barry DeZonia * */ public class UnsignedInt128Group implements Integer<UnsignedInt128Group, UnsignedInt128Member>, Bounded<UnsignedInt128Member>, BitOperations<UnsignedInt128Member>, Random<UnsignedInt128Member> { // TODO // 1) convert byte references and constants to long references and constants // 2) speed test versus imglib private static final java.util.Random rng = new java.util.Random(System.currentTimeMillis()); private static final UnsignedInt128Member ZERO = new UnsignedInt128Member(); private static final UnsignedInt128Member ONE = new UnsignedInt128Member((byte)0,(byte)1); @Override public UnsignedInt128Member construct() { return new UnsignedInt128Member(); } @Override public UnsignedInt128Member construct(UnsignedInt128Member other) { return new UnsignedInt128Member(other); } @Override public UnsignedInt128Member construct(String str) { return new UnsignedInt128Member(str); } @Override public boolean isEqual(UnsignedInt128Member a, UnsignedInt128Member b) { return a.lo == b.lo && a.hi == b.hi; } @Override public boolean isNotEqual(UnsignedInt128Member a, UnsignedInt128Member b) { return !isEqual(a, b); } @Override public void assign(UnsignedInt128Member from, UnsignedInt128Member to) { to.set(from); } @Override public void zero(UnsignedInt128Member a) { a.hi = a.lo = 0; } // TODO: this shows that unsigned numbers aren't quite ints. They should derive slightly differently // in the algebra hierarchy. @Override public void negate(UnsignedInt128Member a, UnsignedInt128Member b) { assign(a,b); // ignore } @Override public void add(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member c) { byte cLo = (byte) (a.lo + b.lo); byte cHi = (byte) (a.hi + b.hi); int correction = 0; byte alh = (byte) (a.lo & 0x80); byte blh = (byte) (b.lo & 0x80); if (alh != 0 && blh != 0) { correction = 1; } else if ((alh != 0 && blh == 0) || (alh == 0 && blh != 0)) { byte all = (byte) (a.lo & 0x7f); byte bll = (byte) (b.lo & 0x7f); if ((byte)(all + bll) < 0) correction = 1; } cHi += correction; c.lo = cLo; c.hi = cHi; } @Override public void subtract(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member c) { byte cHi = (byte) (a.hi - b.hi); byte cLo = (byte) (a.lo - b.lo); final int correction; int alh = a.lo & 0x80; int blh = b.lo & 0x80; if (alh == 0 && blh != 0) correction = 1; else if (alh != 0 && blh == 0) { correction = 0; } else { // alh == blh int all = a.lo & 0x7f; int bll = b.lo & 0x7f; if (all < bll) correction = 1; else // (all >= bll) correction = 0; } cHi -= correction; c.lo = cLo; c.hi = cHi; } @Override public void multiply(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member c) { UnsignedInt128Member bTmp = new UnsignedInt128Member(b); UnsignedInt128Member tmp = new UnsignedInt128Member(); UnsignedInt128Member part = new UnsignedInt128Member(a); while (isNotEqual(bTmp,ZERO)) { if ((bTmp.lo & 1) > 0) { add(tmp, part, tmp); } shiftLeftOneBit(part); shiftRightOneBit(bTmp); } assign(tmp,c); } public void multiplyFast(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member c) { byte all = (byte) (a.lo & 0xf); byte alh = (byte) ((a.lo & 0xf0) >>> 4); byte bll = (byte) (b.lo & 0xf); byte blh = (byte) ((b.lo & 0xf0) >>> 4); byte loLoNib = (byte) (all * bll); byte loHiNib = (byte) ((all * blh) + (alh * bll)); if ((loLoNib & 0xf0) != 0) { loHiNib++; loLoNib &= 0xf; } byte hiLoNib = (byte) (alh * blh); if ((loHiNib & 0xf0) != 0) { hiLoNib++; loHiNib &= 0xf; } byte mid1 = (byte) (a.lo * b.hi); byte mid2 = (byte) (a.hi * b.lo); // can throw away a.hi * b.hi: all overflow c.lo = (byte)((loHiNib << 4) + loLoNib); c.hi = (byte) (hiLoNib + mid1 + mid2); } @Override public void power(int power, UnsignedInt128Member a, UnsignedInt128Member b) { if (power == 0 && isEqual(a, ZERO)) throw new IllegalArgumentException("0^0 is not a number"); if (power < 0) throw new IllegalArgumentException("Cannot get negative powers from integers"); UnsignedInt128Member tmp = new UnsignedInt128Member(ONE); for (int i = 0; i < power; i++) multiply(tmp, a, tmp); assign(tmp, b); } @Override public void unity(UnsignedInt128Member result) { assign(ONE, result); } @Override public boolean isLess(UnsignedInt128Member a, UnsignedInt128Member b) { return compare(a,b) < 0; } @Override public boolean isLessEqual(UnsignedInt128Member a, UnsignedInt128Member b) { return compare(a,b) <= 0; } @Override public boolean isGreater(UnsignedInt128Member a, UnsignedInt128Member b) { return compare(a,b) > 0; } @Override public boolean isGreaterEqual(UnsignedInt128Member a, UnsignedInt128Member b) { return compare(a,b) >= 0; } @Override public int compare(UnsignedInt128Member a, UnsignedInt128Member b) { int abyte, bbyte; int ab = a.hi & 0x80; int bb = b.hi & 0x80; if (ab == 0 && bb != 0) { return -1; } else if (ab != 0 && bb == 0) { return 1; } else { // ab == bb abyte = a.hi & 0x7f; bbyte = b.hi & 0x7f; if (abyte < bbyte) return -1; else if (abyte > bbyte) return 1; else { // a.hi == b.hi ab = a.lo & 0x80; bb = b.lo & 0x80; if (ab == 0 && bb != 0) { return -1; } else if (ab != 0 && bb == 0) { return 1; } else { // ab == bb abyte = a.lo & 0x7f; bbyte = b.lo & 0x7f; if (abyte < bbyte) return -1; else if (abyte > bbyte) return 1; else return 0; } } } } @Override public int signum(UnsignedInt128Member a) { return compare(a,ZERO); } @Override public void min(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member c) { if (compare(a,b) < 0) assign(a, c); else assign(b, c); } @Override public void max(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member c) { if (compare(a,b) > 0) assign(a, c); else assign(b, c); } @Override public void abs(UnsignedInt128Member a, UnsignedInt128Member b) { assign(a, b); } @Override public void norm(UnsignedInt128Member a, UnsignedInt128Member b) { assign(a, b); } @Override public void div(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member d) { UnsignedInt128Member m = new UnsignedInt128Member(); divMod(a,b,d,m); } @Override public void mod(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member m) { UnsignedInt128Member d = new UnsignedInt128Member(); divMod(a,b,d,m); } @Override public void divMod(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member d, UnsignedInt128Member m) { if (isEqual(b, ZERO)) { throw new IllegalArgumentException("divide by zero error in UnsignedInt128Group"); } int comparison = compare(a,b); if (comparison == 0) { // a is equal b assign(ONE, d); assign(ZERO, m); return; } if (comparison < 0) { // a is less than b assign(ZERO, d); assign(a, m); return; } // if here a is greater than b UnsignedInt128Member quotient = new UnsignedInt128Member(); UnsignedInt128Member dividend = new UnsignedInt128Member(a); UnsignedInt128Member divisor = new UnsignedInt128Member(b); int dividendLeadingNonzeroBit = leadingNonZeroBit(a); int divisorLeadingNonzeroBit = leadingNonZeroBit(b); bitShiftLeft((dividendLeadingNonzeroBit - divisorLeadingNonzeroBit), divisor, divisor); for (int i = 0; i < dividendLeadingNonzeroBit-divisorLeadingNonzeroBit+1; i++) { shiftLeftOneBit(quotient); if (isGreaterEqual(dividend, divisor)) { subtract(dividend, divisor, dividend); quotient.lo |= 1; } shiftRightOneBit(divisor); } assign(quotient, d); assign(dividend, m); } private int leadingNonZeroBit(UnsignedInt128Member num) { int mask = 0x80; for (int i = 0; i < 8; i++) { if ((num.hi & mask) != 0) { return 15 - i; } mask >>>= 1; } mask = 0x80; for (int i = 0; i < 8; i++) { if ((num.lo & mask) != 0) { return 7 - i; } mask >>>= 1; } return -1; } @Override public void gcd(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member c) { Gcd.compute(this, a, b, c); } @Override public void lcm(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member c) { Lcm.compute(this, a, b, c); } @Override public boolean isEven(UnsignedInt128Member a) { return a.lo % 2 == 0; } @Override public boolean isOdd(UnsignedInt128Member a) { return a.lo % 2 == 1; } @Override public void pred(UnsignedInt128Member a, UnsignedInt128Member b) { subtract(a,ONE,b); } @Override public void succ(UnsignedInt128Member a, UnsignedInt128Member b) { add(a,ONE,b); } @Override public void pow(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member c) { int cmp = compare(b,ZERO); if (cmp < 0) throw new IllegalArgumentException("Cannot get negative powers from integers"); if (cmp == 0 && compare(a,ZERO) == 0) throw new IllegalArgumentException("0^0 is not a number"); UnsignedInt128Member tmp = new UnsignedInt128Member(ONE); UnsignedInt128Member pow = new UnsignedInt128Member(b); while (!isEqual(pow, ZERO)) { multiply(tmp, a, tmp); pred(pow,pow); } assign(tmp, c); } @Override public void random(UnsignedInt128Member a) { a.lo = (byte) (rng.nextInt(256) - 0x80); a.hi = (byte) (rng.nextInt(256) - 0x80); } @Override public void bitAnd(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member c) { c.lo = (byte) (a.lo & b.lo); c.hi = (byte) (a.hi & b.hi); } @Override public void bitOr(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member c) { c.lo = (byte) (a.lo | b.lo); c.hi = (byte) (a.hi | b.hi); } @Override public void bitXor(UnsignedInt128Member a, UnsignedInt128Member b, UnsignedInt128Member c) { c.lo = (byte) (a.lo ^ b.lo); c.hi = (byte) (a.hi ^ b.hi); } @Override public void bitNot(UnsignedInt128Member a, UnsignedInt128Member b) { b.lo = (byte) ~a.lo; b.hi = (byte) ~a.hi; } // TODO improve performance @Override public void bitShiftLeft(int count, UnsignedInt128Member a, UnsignedInt128Member b) { if (count < 0) bitShiftRight(Math.abs(count), a, b); else { count = count % 0x80; UnsignedInt128Member tmp = new UnsignedInt128Member(a); for (int i = 0; i < count; i++) { shiftLeftOneBit(tmp); } assign(tmp, b); } } // TODO improve performance @Override public void bitShiftRight(int count, UnsignedInt128Member a, UnsignedInt128Member b) { if (count < 0) bitShiftLeft(Math.abs(count), a, b); else if (count > 0x7f) assign(ZERO, b); else { UnsignedInt128Member tmp = new UnsignedInt128Member(a); for (int i = 0; i < count; i++) { shiftRightOneBit(tmp); } assign(tmp, b); } } @Override public void maxBound(UnsignedInt128Member a) { a.lo = -1; a.hi = -1; } @Override public void minBound(UnsignedInt128Member a) { a.lo = 0; a.hi = 0; } private void shiftLeftOneBit(UnsignedInt128Member val) { boolean transitionBit = (val.lo & 0x80) != 0; val.lo = (byte) ((val.lo & 0xff) << 1); val.hi = (byte) ((val.hi & 0xff) << 1); if (transitionBit) val.hi |= 1; } private void shiftRightOneBit(UnsignedInt128Member val) { boolean transitionBit = (val.hi & 1) != 0; val.lo = (byte) ((val.lo & 0xff) >>> 1); val.hi = (byte) ((val.hi & 0xff) >>> 1); if (transitionBit) val.lo |= 0x80; } }
Use signum(a) instead of compare(a,ZERO)
src/zorbage/type/data/int128/UnsignedInt128Group.java
Use signum(a) instead of compare(a,ZERO)
Java
mit
3146f243a312f26d5fb33ef36b0d4db73f660728
0
InventivetalentDev/NBTLibrary
package org.inventivetalent.nbt; import com.google.gson.JsonObject; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class CompoundTag extends NBTTag<Map<String, NBTTag>> implements Iterable<Map.Entry<String, NBTTag>> { private final Map<String, NBTTag> value; public CompoundTag() { super(""); this.value = new HashMap<>(); } public CompoundTag(Map<String, NBTTag> value) { super(""); this.value = new HashMap<>(value); } public CompoundTag(String name) { super(name); this.value = new HashMap<>(); } public CompoundTag(String name, Map<String, NBTTag> value) { super(name); this.value = new HashMap<>(value); } @Override public Map<String, NBTTag> getValue() { return value; } @Override public void setValue(Map<String, NBTTag> value) { this.value.putAll(value); } public NBTTag get(String name) { return value.get(name); } public void set(String name, NBTTag tag) { this.value.put(name, tag); } public void set(String name, byte b) { set(name, new ByteTag(name, b)); } public void set(String name, short s) { set(name, new ShortTag(name, s)); } public void set(String name, int i) { set(name, new IntTag(name, i)); } public void set(String name, long l) { set(name, new LongTag(name, l)); } public void set(String name, float f) { set(name, new FloatTag(name, f)); } public void set(String name, double d) { set(name, new DoubleTag(name, d)); } public void set(String name, String string) { set(name, new StringTag(name, string)); } public void set(String name, byte[] b) { set(name, new ByteArrayTag(name, b)); } public void set(String name, int[] i) { set(name, new IntArrayTag(name, i)); } public void set(String name, boolean b) { set(name, (byte) (b ? 1 : 0)); } public boolean has(String name) { return value.containsKey(name); } public String getString(String name) { NBTTag tag = get(name); if (tag == null) { return null; } Object value = tag.getValue(); if (value == null) { return null; } return value.toString(); } public Number getNumber(String name) { NBTTag tag = get(name); if (tag == null) { return null; } if (tag instanceof NumberTag) { return ((NumberTag) tag).getValue(); } return null; } public CompoundTag getCompound(String name) { NBTTag tag = get(name); if (tag == null) { return null; } if (tag instanceof CompoundTag) { return (CompoundTag) tag; } return null; } public CompoundTag getOrCreateCompound(String name) { if (has(name)) { return getCompound(name); } CompoundTag compoundTag = new CompoundTag(name); set(name, compoundTag); return compoundTag; } public ListTag getList(String name) { NBTTag tag = get(name); if (tag == null) { return null; } if (tag instanceof ListTag) { return (ListTag) tag; } return null; } public <V extends NBTTag> ListTag<V> getList(String name, Class<V> type) { ListTag list = getList(name); if (list.getTagType() != TagID.forClass(type)) { throw new IllegalArgumentException("ListTag(" + name + ") is not of type " + type.getSimpleName()); } return (ListTag<V>) list; } @Override public JsonObject asJson() { JsonObject jsonObject = new JsonObject(); for (Map.Entry<String, NBTTag> entry : value.entrySet()) { jsonObject.add(entry.getKey(), entry.getValue().asJson()); } return jsonObject; } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { while (true) { NBTTag tag = nbtIn.readNBTTag(depth + 1); if (tag.getTypeId() == TagID.TAG_END) { break; } else { set(tag.getName(), tag); } } } @Override public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException { for (NBTTag tag : value.values()) { nbtOut.writeTag(tag); } out.writeByte(TagID.TAG_END); } @Override public int getTypeId() { return TagID.TAG_COMPOUND; } @Override public String getTypeName() { return "TAG_Compund"; } @Override public Iterator<Map.Entry<String, NBTTag>> iterator() { return value.entrySet().iterator(); } public String getNMSClass() { return "NBTTagCompound"; } @Override public CompoundTag fromNMS(Object nms) throws ReflectiveOperationException { Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); Class<?> nbtBaseClass = NMS_CLASS_RESOLVER.resolve("NBTBase"); Field field = clazz.getDeclaredField("map"); field.setAccessible(true); Map<String, Object> nmsMap = (Map<String, Object>) field.get(nms); for (Map.Entry<String, Object> nmsEntry : nmsMap.entrySet()) { byte typeId = (byte) nbtBaseClass.getMethod("getTypeId").invoke(nmsEntry.getValue()); if (typeId == TagID.TAG_END) { continue; } set(nmsEntry.getKey(), NBTTag.forType(typeId).getConstructor(String.class).newInstance(nmsEntry.getKey()).fromNMS(nmsEntry.getValue())); } return this; } @Override public Object toNMS() throws ReflectiveOperationException { Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); Field field = clazz.getDeclaredField("map"); field.setAccessible(true); Object nms = clazz.newInstance(); Map map = (Map) field.get(nms); for (Map.Entry<String, NBTTag> entry : this) { map.put(entry.getKey(), entry.getValue().toNMS()); } field.set(nms, map);// I don't quite get why this doesn't complain about illegal access (the field is private final) return nms; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CompoundTag that = (CompoundTag) o; return value != null ? value.equals(that.value) : that.value == null; } @Override public int hashCode() { return value != null ? value.hashCode() : 0; } }
src/main/java/org/inventivetalent/nbt/CompoundTag.java
package org.inventivetalent.nbt; import com.google.gson.JsonObject; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class CompoundTag extends NBTTag<Map<String, NBTTag>> implements Iterable<Map.Entry<String, NBTTag>> { private final Map<String, NBTTag> value; public CompoundTag() { super(""); this.value = new HashMap<>(); } public CompoundTag(Map<String, NBTTag> value) { super(""); this.value = new HashMap<>(value); } public CompoundTag(String name) { super(name); this.value = new HashMap<>(); } public CompoundTag(String name, Map<String, NBTTag> value) { super(name); this.value = new HashMap<>(value); } @Override public Map<String, NBTTag> getValue() { return value; } @Override public void setValue(Map<String, NBTTag> value) { this.value.putAll(value); } public NBTTag get(String name) { return value.get(name); } public void set(String name, NBTTag tag) { this.value.put(name, tag); } public void set(String name, byte b) { set(name, new ByteTag(name, b)); } public void set(String name, short s) { set(name, new ShortTag(name, s)); } public void set(String name, int i) { set(name, new IntTag(name, i)); } public void set(String name, long l) { set(name, new LongTag(name, l)); } public void set(String name, float f) { set(name, new FloatTag(name, f)); } public void set(String name, double d) { set(name, new DoubleTag(name, d)); } public void set(String name, String string) { set(name, new StringTag(name, string)); } public void set(String name, byte[] b) { set(name, new ByteArrayTag(name, b)); } public void set(String name, int[] i) { set(name, new IntArrayTag(name, i)); } public void set(String name, boolean b) { set(name, (byte) (b ? 1 : 0)); } public boolean has(String name) { return value.containsKey(name); } public String getString(String name) { NBTTag tag = get(name); if (tag == null) { return null; } Object value = tag.getValue(); if (value == null) { return null; } return value.toString(); } public Number getNumber(String name) { NBTTag tag = get(name); if (tag == null) { return null; } if (tag instanceof NumberTag) { return ((NumberTag) tag).getValue(); } return null; } public CompoundTag getCompound(String name) { NBTTag tag = get(name); if (tag == null) { return null; } if (tag instanceof CompoundTag) { return (CompoundTag) tag; } return null; } public ListTag getList(String name) { NBTTag tag = get(name); if (tag == null) { return null; } if (tag instanceof ListTag) { return (ListTag) tag; } return null; } public <V extends NBTTag> ListTag<V> getList(String name, Class<V> type) { ListTag list=getList(name); if (list.getTagType() != TagID.forClass(type)) { throw new IllegalArgumentException("ListTag(" + name + ") is not of type " + type.getSimpleName()); } return (ListTag<V>) list; } @Override public JsonObject asJson() { JsonObject jsonObject = new JsonObject(); for (Map.Entry<String, NBTTag> entry : value.entrySet()) { jsonObject.add(entry.getKey(), entry.getValue().asJson()); } return jsonObject; } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { while (true) { NBTTag tag = nbtIn.readNBTTag(depth + 1); if (tag.getTypeId() == TagID.TAG_END) { break; } else { set(tag.getName(), tag); } } } @Override public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException { for (NBTTag tag : value.values()) { nbtOut.writeTag(tag); } out.writeByte(TagID.TAG_END); } @Override public int getTypeId() { return TagID.TAG_COMPOUND; } @Override public String getTypeName() { return "TAG_Compund"; } @Override public Iterator<Map.Entry<String, NBTTag>> iterator() { return value.entrySet().iterator(); } public String getNMSClass() { return "NBTTagCompound"; } @Override public CompoundTag fromNMS(Object nms) throws ReflectiveOperationException { Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); Class<?> nbtBaseClass = NMS_CLASS_RESOLVER.resolve("NBTBase"); Field field = clazz.getDeclaredField("map"); field.setAccessible(true); Map<String, Object> nmsMap = (Map<String, Object>) field.get(nms); for (Map.Entry<String, Object> nmsEntry : nmsMap.entrySet()) { byte typeId = (byte) nbtBaseClass.getMethod("getTypeId").invoke(nmsEntry.getValue()); if (typeId == TagID.TAG_END) { continue; } set(nmsEntry.getKey(), NBTTag.forType(typeId).getConstructor(String.class).newInstance(nmsEntry.getKey()).fromNMS(nmsEntry.getValue())); } return this; } @Override public Object toNMS() throws ReflectiveOperationException { Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); Field field = clazz.getDeclaredField("map"); field.setAccessible(true); Object nms = clazz.newInstance(); Map map = (Map) field.get(nms); for (Map.Entry<String, NBTTag> entry : this) { map.put(entry.getKey(), entry.getValue().toNMS()); } field.set(nms, map);// I don't quite get why this doesn't complain about illegal access (the field is private final) return nms; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CompoundTag that = (CompoundTag) o; return value != null ? value.equals(that.value) : that.value == null; } @Override public int hashCode() { return value != null ? value.hashCode() : 0; } }
add #getOrCreateCompound
src/main/java/org/inventivetalent/nbt/CompoundTag.java
add #getOrCreateCompound
Java
mit
b13ca3ff8276ac5d4c24b2d71fe1a36d9fadf498
0
jenkinsci/warnings-plugin,jenkinsci/warnings-plugin,jenkinsci/warnings-plugin
package io.jenkins.plugins.analysis.core.model; import java.util.Locale; import java.util.regex.Pattern; import org.eclipse.collections.impl.factory.Lists; import org.eclipse.collections.impl.factory.Maps; import org.junit.jupiter.api.Test; import io.jenkins.plugins.analysis.core.model.StaticAnalysisLabelProvider.IconPathResolver; import io.jenkins.plugins.analysis.core.model.Summary.LabelProviderFactoryFacade; import io.jenkins.plugins.analysis.core.quality.AnalysisBuild; import io.jenkins.plugins.analysis.core.quality.QualityGate; import io.jenkins.plugins.analysis.core.quality.Thresholds; import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; import hudson.model.BallColor; import hudson.model.Result; /** * Tests the class {@link Summary}. * * @author Ullrich Hafner */ class SummaryTest { @Test void shouldProvideSummary() { Locale.setDefault(Locale.ENGLISH); LabelProviderFactoryFacade facade = mock(LabelProviderFactoryFacade.class); when(facade.get("checkstyle")).thenReturn(createLabelProvider("checkstyle", "CheckStyle")); when(facade.get("pmd")).thenReturn(createLabelProvider("pmd", "PMD")); AnalysisResult analysisRun = mock(AnalysisResult.class); when(analysisRun.getSizePerOrigin()).thenReturn(Maps.fixedSize.of("checkstyle", 15, "pmd", 20)); when(analysisRun.getNewSize()).thenReturn(2); when(analysisRun.getFixedSize()).thenReturn(2); when(analysisRun.getErrorMessages()).thenReturn(Lists.immutable.empty()); when(analysisRun.getNoIssuesSinceBuild()).thenReturn(1); Thresholds thresholds = new Thresholds(); thresholds.unstableTotalAll = 1; when(analysisRun.getQualityGate()).thenReturn(new QualityGate(thresholds)); when(analysisRun.getOverallResult()).thenReturn(Result.SUCCESS); when(analysisRun.getReferenceBuild()).thenReturn(15); AnalysisBuild build = mock(AnalysisBuild.class); when(build.getNumber()).thenReturn(2); when(analysisRun.getBuild()).thenReturn(build); String actualSummary = new Summary(createLabelProvider("test", "SummaryTest"), analysisRun, facade).create(); assertThat(actualSummary).contains("CheckStyle, PMD"); assertThat(actualSummary).contains("No warnings for 2 builds"); assertThat(actualSummary).contains("since build <a href=\"../1\" class=\"model-link inside\">1</a>"); assertThat(actualSummary).containsPattern( createWarningsLink("<a href=\"testResult/new\">.*2 new warnings.*</a>")); assertThat(actualSummary).containsPattern( createWarningsLink("<a href=\"testResult/fixed\">.*2 fixed warnings.*</a>")); assertThat(actualSummary).contains("Quality gates: <a href=\"BLUE\" alt=\"Success\" title=\"Success\">Success</a>"); assertThat(actualSummary).contains("Reference build <a href=\"../15/testResult\" class=\"model-link inside\">15</a>"); } private StaticAnalysisLabelProvider createLabelProvider(final String checkstyle, final String checkStyle) { return new StaticAnalysisLabelProvider(checkstyle, checkStyle, new IconResolverStub()); } private Pattern createWarningsLink(final String href) { return Pattern.compile(href, Pattern.MULTILINE | Pattern.DOTALL); } private static class IconResolverStub extends IconPathResolver { @Override String getImagePath(final BallColor color) { return color.name(); } } }
src/test/java/io/jenkins/plugins/analysis/core/model/SummaryTest.java
package io.jenkins.plugins.analysis.core.model; import java.util.Locale; import java.util.regex.Pattern; import org.eclipse.collections.impl.factory.Maps; import org.junit.jupiter.api.Test; import io.jenkins.plugins.analysis.core.model.StaticAnalysisLabelProvider.IconPathResolver; import io.jenkins.plugins.analysis.core.model.Summary.LabelProviderFactoryFacade; import io.jenkins.plugins.analysis.core.quality.AnalysisBuild; import io.jenkins.plugins.analysis.core.quality.QualityGate; import io.jenkins.plugins.analysis.core.quality.Thresholds; import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; import hudson.model.BallColor; import hudson.model.Result; /** * Tests the class {@link Summary}. * * @author Ullrich Hafner */ class SummaryTest { @Test void shouldProvideSummary() { Locale.setDefault(Locale.ENGLISH); LabelProviderFactoryFacade facade = mock(LabelProviderFactoryFacade.class); when(facade.get("checkstyle")).thenReturn(createLabelProvider("checkstyle", "CheckStyle")); when(facade.get("pmd")).thenReturn(createLabelProvider("pmd", "PMD")); AnalysisResult analysisRun = mock(AnalysisResult.class); when(analysisRun.getSizePerOrigin()).thenReturn(Maps.fixedSize.of("checkstyle", 15, "pmd", 20)); when(analysisRun.getNewSize()).thenReturn(2); when(analysisRun.getFixedSize()).thenReturn(2); when(analysisRun.getNoIssuesSinceBuild()).thenReturn(1); Thresholds thresholds = new Thresholds(); thresholds.unstableTotalAll = 1; when(analysisRun.getQualityGate()).thenReturn(new QualityGate(thresholds)); when(analysisRun.getOverallResult()).thenReturn(Result.SUCCESS); when(analysisRun.getReferenceBuild()).thenReturn(15); AnalysisBuild build = mock(AnalysisBuild.class); when(build.getNumber()).thenReturn(2); when(analysisRun.getBuild()).thenReturn(build); String actualSummary = new Summary(createLabelProvider("test", "SummaryTest"), analysisRun, facade).create(); assertThat(actualSummary).contains("CheckStyle, PMD"); assertThat(actualSummary).contains("No warnings for 2 builds"); assertThat(actualSummary).contains("since build <a href=\"../1\" class=\"model-link inside\">1</a>"); assertThat(actualSummary).containsPattern( createWarningsLink("<a href=\"testResult/new\">.*2 new warnings.*</a>")); assertThat(actualSummary).containsPattern( createWarningsLink("<a href=\"testResult/fixed\">.*2 fixed warnings.*</a>")); assertThat(actualSummary).contains("Quality gates: <a href=\"BLUE\" alt=\"Success\" title=\"Success\">Success</a>"); assertThat(actualSummary).contains("Reference build <a href=\"../15/testResult\" class=\"model-link inside\">15</a>"); } private StaticAnalysisLabelProvider createLabelProvider(final String checkstyle, final String checkStyle) { return new StaticAnalysisLabelProvider(checkstyle, checkStyle, new IconResolverStub()); } private Pattern createWarningsLink(final String href) { return Pattern.compile(href, Pattern.MULTILINE | Pattern.DOTALL); } private static class IconResolverStub extends IconPathResolver { @Override String getImagePath(final BallColor color) { return color.name(); } } }
Fixed test setup.
src/test/java/io/jenkins/plugins/analysis/core/model/SummaryTest.java
Fixed test setup.
Java
mit
5674c681e3d0266598ab7a81125dd73435f3da1b
0
ScottDIT/Assignment3
package ie.dit; import java.awt.Color; import processing.core.PApplet; import processing.core.PVector; public class GameObject { public PApplet applet; public float w, h, theta; public PVector location, velocity; public Color colour; public GameObject(PApplet applet) { this.applet = applet; w = h = 100.0f; theta = 0.0f; location = new PVector(500.0f, 500.0f); velocity = new PVector(0.0f, 0.0f); colour = new Color(255, 0, 0); } // End constructor. public GameObject(float w, float h, PVector location, PVector velocity, Color colour, PApplet applet) { this.applet = applet; this.w = w; this.h = h; this.location = location; this.velocity = velocity; this.colour = colour; } // End constructor. public void run(){ display(); update(); } // End run. public void display() { } // End display. public void update() { } // End update. } // End GameObject class.
Assignment3/src/ie/dit/GameObject.java
package ie.dit; // The base class. public class GameObject { float theta; GameObject(){ theta = 0.0f; } // End constructor. public void run() { display(); update(); } // End run. public void display() { } // End display. public void update() { } // End update. } // End GameObject.
GameObject Updated.
Assignment3/src/ie/dit/GameObject.java
GameObject Updated.
Java
mit
bb6f32b4af1ab2728e381c16cbd2c481b418bb64
0
niekBr/Mario
import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.image.BufferedImage; import javax.swing.JLabel; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.JFrame; //klasse: "Spel" public class Spel implements KeyListener { /** * De attributen van de klasse */ ArrayList<Enemy> enemies; Tekenaar t; ArrayList<Rand> randen; ArrayList<Kogel> kogels; ArrayList<Coin> coins; int punten = 11; int ammo = 5; BufferedImage image; JLabel score; JLabel ammunitie; boolean running; Achtergrond bg; Enemy vijand; Mario mario; JFrame scherm; boolean gebotst; int vx; //Alle objecten moeten meebewegen! Mario en achtergrond bewegen niet als enige! boolean teller; Kogel deleteKogel; String plaatjes; //Het converteren van een int naar plaatjes bij updateCoins() int coin; //Save van het aantal dat coins nu op staat boolean changed; public Spel(){ image = laadPlaatje("mario.gif"); mario = new Mario(image, 500, 400, 30, 60); image = laadPlaatje("background.jpg"); bg = new Achtergrond(image, 0, 0, 1750, 750); createEnemies(3, 0, 0); randen = new ArrayList<Rand>(); image = laadPlaatje("mysteryBox.jpg"); randen.add(new Rand(image, 1000, 500, 25, 25)); coins = new ArrayList<Coin>(); kogels = new ArrayList<Kogel>(); image = laadPlaatje("kogel.png"); createMap(); running = true; gebotst = false; coin = 0; changed = false; while (running){ try{ Thread.sleep(10); } catch(InterruptedException e){ e.printStackTrace();} mario.xOld = mario.x; mario.yOld = mario.y; gebotst = controleerContact(mario, enemies); if(gebotst){ enemies.remove(vijand); score.setText("Score: " + punten); } for(Enemy e : enemies) { e.yOld = e.y; } for(Rand p : randen){ p.x += this.vx; } mario.y += mario.vy; if(mario.y < mario.spring - 50 && mario.vy != 1) { mario.vy=1; } for(Enemy e : enemies) { e.x += e.vx + this.vx; e.y += e.vy; } for(Kogel k : kogels){ k.x += k.vx; if(k.y < 0 || k.y > scherm.getHeight() || k.x < 0 || k.x > scherm.getWidth()){ deleteKogel = k; } } kogels.remove(deleteKogel); controleerSchot(kogels, enemies, randen); controleerMario(mario, randen); controleerEnemies(randen, enemies); //Checkt of de coins moeten worden geupdate if(coin != punten){ updateCoins(punten); } t.repaint(); } scherm.dispose(); System.out.println("QUIT"); } public BufferedImage laadPlaatje(String fileName) { BufferedImage img = null; try{ img = ImageIO.read(new File(fileName)); } catch(IOException e){ System.out.println("Er is iets fout gegaan bij het laden van het plaatje " + fileName + "."); } return img; } private void createMap(){ image = laadPlaatje("grass.jpg"); for(int i=0; i<30; i++) { this.randen.add(new Rand(image, 50*i, 525, 50, 50)); } scherm = new JFrame("Mario - Thomas & Niek"); scherm.setBounds(0, 0, 1000, 600); scherm.setLayout(null); t = new Tekenaar(kogels, bg, enemies, mario, randen, coins); t.setBounds(0, 0, 1000, 600); score = new JLabel("Score: " + punten); //maak een nieuw JLabel object t.add(score); // en voeg deze aan je JPanel(Tekenaar) toe ammunitie = new JLabel(" Ammo: " + ammo); t.add(ammunitie); scherm.add(t); scherm.setVisible(true); scherm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); scherm.addKeyListener(this); } //Hier alle enemies aanmaken --> Constructor Enemy: Enemy(image, x, y, breedte, hoogte); //Arguments: aantal van iedere enemy! private void createEnemies(int goombas, int koopatroopas, int parakoopatroopas) { //Goomba's BufferedImage image = laadPlaatje("goomba.png"); enemies = new ArrayList<Enemy>(); for(int i=0; i<goombas; i++) { this.enemies.add(new Goomba(image, 50*i, 0, 25, 25)); } //Koopa Troopa's image = laadPlaatje("koopatroopa.png"); for(int i=0; i<koopatroopas; i++) { this.enemies.add(new KoopaTroopa(image, 50*i, 50, 25, 25)); } //Para Koopa Troopa's image = laadPlaatje("parakoopatroopa.jpg"); for(int i=0; i<parakoopatroopas; i++) { this.enemies.add(new ParaKoopaTroopa(image, 50*i, 100, 25, 25)); } } public void keyPressed(KeyEvent e) { if(e.getKeyCode() == e.VK_ESCAPE){ running = false; } if(e.getKeyCode() == e.VK_RIGHT){ this.vx = -2; } if(e.getKeyCode() == e.VK_LEFT){ this.vx = 2; } if(e.getKeyCode() == e.VK_DOWN){ } if(e.getKeyCode() == e.VK_UP){ if(!teller) { if(mario.platform) { mario.spring(); teller = true; } } } if(e.getKeyCode() == e.VK_SPACE){ if(ammo > 0 && !teller){ maakKogel(); ammo--; ammunitie.setText(" Ammo: " + ammo); teller = true; } } } public void keyReleased(KeyEvent e) { if(e.getKeyCode() == e.VK_RIGHT){ this.vx = 0; } if(e.getKeyCode() == e.VK_LEFT){ this.vx = 0; } if(e.getKeyCode() == e.VK_UP){ mario.vy = 1; teller = false; } if(e.getKeyCode() == e.VK_SPACE) { teller = false; } } public void keyTyped(KeyEvent e) { } public void maakKogel(){ kogels.add(new Kogel(laadPlaatje("kogel.png"), mario.x + mario.breedte, mario.y + 20, 32, 26, 3, 0)); } public boolean controleerContact(Mario a, ArrayList<Enemy> enemies) { for(Enemy p : enemies){ if(a.x + a.breedte >= p.x && a.x <= p.x + p.breedte && a.y + a.breedte >= p.y && a.y <= p.y + p.breedte) { this.vijand = p; if(p instanceof KoopaTroopa) { punten++; } else { punten--; } return true; } } return false; } public boolean controleerSchot(ArrayList<Kogel> kogels, ArrayList<Enemy> enemies, ArrayList<Rand> randen) { for(Kogel k : kogels){ for(Enemy p : enemies){ if(k.x + k.breedte >= p.x && k.x <= p.x + p.breedte && k.y + k.breedte >= p.y && k.y <= p.y + p.breedte) { kogels.remove(k); enemies.remove(p); punten++; score.setText("Score: " + punten); t.repaint(); return true; } } for(Rand r : randen){ if(k.x + k.breedte >= r.x && k.x <= r.x + r.breedte && k.y + k.breedte >= r.y && k.y <= r.y + r.breedte) { kogels.remove(k); return true; } } } return false; } public void controleerEnemies(ArrayList<Rand> randen, ArrayList<Enemy> enemies){ for(Enemy e: enemies){ for(Rand r: randen){ if(e.x + e.breedte >= r.x && e.x <= r.x + r.breedte && e.y + e.breedte >= r.y && e.y <= r.y + r.breedte) { if(e instanceof ParaKoopaTroopa) { e.vy = -e.vy; } else { if(e.y + e.hoogte == r.y){ e.y = e.yOld; } else { e.vx = -e.vx; } } } } } } public void controleerMario(Mario a, ArrayList<Rand> rand){ a.platform = false; for(Rand p : rand) { if(a.x + a.breedte >= p.x && a.x <= p.x + p.breedte && a.y + a.breedte + 30 >= p.y && a.y <= p.y + p.breedte) { if(a.y + a.hoogte == p.y){ a.platform = true; a.y = a.yOld; } else { vx = 0; } } } } public void updateCoins(int p){ //Checkt of de code min. 1x is gerunt en cleart dan pas de coins list (anders komt er een error) if(!changed){ coins.clear(); } changed = false; //Als de punten nog niet hoger dan 10 zijn dan hoeven er geen twee cijfers getekent te worden if(p < 10){ plaatjes = Integer.toString(p) + ".png"; coins.add(new Coin(laadPlaatje(plaatjes), 50 ,20, 30, 30)); } //Nu moet er een cijfertje extra bij komen if(p > 10){ plaatjes = Integer.toString(p-10) + ".png"; coins.add(new Coin(laadPlaatje("1.png"), 50 ,20, 30, 30)); coins.add(new Coin(laadPlaatje(plaatjes), 70 ,20, 30, 30)); } //Tekent standaard de coin en stelt de coins gelijk aan punten (kijk while functie) coin = punten; coins.add(new Coin(laadPlaatje("coin.png"), 10,10, 50, 50)); } }
Game/src/Spel.java
import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.image.BufferedImage; import javax.swing.JLabel; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.JFrame; //klasse: "Spel" public class Spel implements KeyListener { /** * De attributen van de klasse */ ArrayList<Enemy> enemies; Tekenaar t; ArrayList<Rand> randen; ArrayList<Kogel> kogels; ArrayList<Coin> coins; int punten = 11; int ammo = 5; BufferedImage image; JLabel score; JLabel ammunitie; boolean running; Achtergrond bg; Enemy vijand; Mario mario; boolean gebotst; int vx; //Alle objecten moeten meebewegen! Mario en achtergrond bewegen niet als enige! boolean teller; Kogel deleteKogel; String plaatjes; //Het converteren van een int naar plaatjes bij updateCoins() int coin; //Save van het aantal dat coins nu op staat boolean changed; public Spel(){ image = laadPlaatje("mario.gif"); mario = new Mario(image, 500, 400, 30, 60); image = laadPlaatje("background.jpg"); bg = new Achtergrond(image, 0, 0, 1750, 750); createEnemies(3, 0, 0); randen = new ArrayList<Rand>(); image = laadPlaatje("mysteryBox.jpg"); randen.add(new Rand(image, 1000, 500, 25, 25)); coins = new ArrayList<Coin>(); createMap(); kogels = new ArrayList<Kogel>(); image = laadPlaatje("kogel.png"); JFrame scherm = new JFrame("Mario - Thomas & Niek"); scherm.setBounds(0, 0, 1000, 600); scherm.setLayout(null); t = new Tekenaar(kogels, bg, enemies, mario, randen, coins); t.setBounds(0, 0, 1000, 600); score = new JLabel("Score: " + punten); //maak een nieuw JLabel object t.add(score); // en voeg deze aan je JPanel(Tekenaar) toe ammunitie = new JLabel(" Ammo: " + ammo); t.add(ammunitie); scherm.add(t); scherm.setVisible(true); scherm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); scherm.addKeyListener(this); running = true; gebotst = false; coin = 0; changed = false; while (running){ try{ Thread.sleep(10); } catch(InterruptedException e){ e.printStackTrace();} mario.xOld = mario.x; mario.yOld = mario.y; gebotst = controleerContact(mario, enemies); if(gebotst){ enemies.remove(vijand); score.setText("Score: " + punten); } for(Enemy e : enemies) { e.yOld = e.y; } for(Rand p : randen){ p.x += this.vx; } mario.y += mario.vy; if(mario.y < mario.spring - 50 && mario.vy != 1) { mario.vy=1; } for(Enemy e : enemies) { e.x += e.vx + this.vx; e.y += e.vy; } for(Kogel k : kogels){ k.x += k.vx; if(k.y < 0 || k.y > scherm.getHeight() || k.x < 0 || k.x > scherm.getWidth()){ deleteKogel = k; } } kogels.remove(deleteKogel); controleerSchot(kogels, enemies, randen); controleerMario(mario, randen); controleerEnemies(randen, enemies); //Checkt of de coins moeten worden geupdate if(coin != punten){ updateCoins(punten); } t.repaint(); } scherm.dispose(); System.out.println("QUIT"); } public BufferedImage laadPlaatje(String fileName) { BufferedImage img = null; try{ img = ImageIO.read(new File(fileName)); } catch(IOException e){ System.out.println("Er is iets fout gegaan bij het laden van het plaatje " + fileName + "."); } return img; } private void createMap(){ image = laadPlaatje("grass.jpg"); for(int i=0; i<30; i++) { this.randen.add(new Rand(image, 50*i, 525, 50, 50)); } } //Hier alle enemies aanmaken --> Constructor Enemy: Enemy(image, x, y, breedte, hoogte); //Arguments: aantal van iedere enemy! private void createEnemies(int goombas, int koopatroopas, int parakoopatroopas) { //Goomba's BufferedImage image = laadPlaatje("goomba.png"); enemies = new ArrayList<Enemy>(); for(int i=0; i<goombas; i++) { this.enemies.add(new Goomba(image, 50*i, 0, 25, 25)); } //Koopa Troopa's image = laadPlaatje("koopatroopa.png"); for(int i=0; i<koopatroopas; i++) { this.enemies.add(new KoopaTroopa(image, 50*i, 50, 25, 25)); } //Para Koopa Troopa's image = laadPlaatje("parakoopatroopa.jpg"); for(int i=0; i<parakoopatroopas; i++) { this.enemies.add(new ParaKoopaTroopa(image, 50*i, 100, 25, 25)); } } public void keyPressed(KeyEvent e) { if(e.getKeyCode() == e.VK_ESCAPE){ running = false; } if(e.getKeyCode() == e.VK_RIGHT){ this.vx = -2; } if(e.getKeyCode() == e.VK_LEFT){ this.vx = 2; } if(e.getKeyCode() == e.VK_DOWN){ } if(e.getKeyCode() == e.VK_UP){ if(!teller) { if(mario.platform) { mario.spring(); teller = true; } } } if(e.getKeyCode() == e.VK_SPACE){ if(ammo > 0 && !teller){ maakKogel(); ammo--; ammunitie.setText(" Ammo: " + ammo); teller = true; } } } public void keyReleased(KeyEvent e) { if(e.getKeyCode() == e.VK_RIGHT){ this.vx = 0; } if(e.getKeyCode() == e.VK_LEFT){ this.vx = 0; } if(e.getKeyCode() == e.VK_UP){ mario.vy = 1; teller = false; } if(e.getKeyCode() == e.VK_SPACE) { teller = false; } } public void keyTyped(KeyEvent e) { } public void maakKogel(){ kogels.add(new Kogel(laadPlaatje("kogel.png"), mario.x + mario.breedte, mario.y + 20, 32, 26, 3, 0)); } public boolean controleerContact(Mario a, ArrayList<Enemy> enemies) { for(Enemy p : enemies){ if(a.x + a.breedte >= p.x && a.x <= p.x + p.breedte && a.y + a.breedte >= p.y && a.y <= p.y + p.breedte) { this.vijand = p; if(p instanceof KoopaTroopa) { punten++; } else { punten--; } return true; } } return false; } public boolean controleerSchot(ArrayList<Kogel> kogels, ArrayList<Enemy> enemies, ArrayList<Rand> randen) { for(Kogel k : kogels){ for(Enemy p : enemies){ if(k.x + k.breedte >= p.x && k.x <= p.x + p.breedte && k.y + k.breedte >= p.y && k.y <= p.y + p.breedte) { kogels.remove(k); enemies.remove(p); punten++; score.setText("Score: " + punten); t.repaint(); return true; } } for(Rand r : randen){ if(k.x + k.breedte >= r.x && k.x <= r.x + r.breedte && k.y + k.breedte >= r.y && k.y <= r.y + r.breedte) { kogels.remove(k); return true; } } } return false; } public void controleerEnemies(ArrayList<Rand> randen, ArrayList<Enemy> enemies){ for(Enemy e: enemies){ for(Rand r: randen){ if(e.x + e.breedte >= r.x && e.x <= r.x + r.breedte && e.y + e.breedte >= r.y && e.y <= r.y + r.breedte) { if(e instanceof ParaKoopaTroopa) { e.vy = -e.vy; } else { if(e.y + e.hoogte == r.y){ e.y = e.yOld; } else { e.vx = -e.vx; } } } } } } public void controleerMario(Mario a, ArrayList<Rand> rand){ a.platform = false; for(Rand p : rand) { if(a.x + a.breedte >= p.x && a.x <= p.x + p.breedte && a.y + a.breedte + 30 >= p.y && a.y <= p.y + p.breedte) { if(a.y + a.hoogte == p.y){ a.platform = true; a.y = a.yOld; } else { vx = 0; } } } } public void updateCoins(int p){ //Checkt of de code min. 1x is gerunt en cleart dan pas de coins list (anders komt er een error) if(!changed){ coins.clear(); } changed = false; //Als de punten nog niet hoger dan 10 zijn dan hoeven er geen twee cijfers getekent te worden if(p < 10){ plaatjes = Integer.toString(p) + ".png"; coins.add(new Coin(laadPlaatje(plaatjes), 50 ,20, 30, 30)); } //Nu moet er een cijfertje extra bij komen if(p > 10){ plaatjes = Integer.toString(p-10) + ".png"; coins.add(new Coin(laadPlaatje("1.png"), 50 ,20, 30, 30)); coins.add(new Coin(laadPlaatje(plaatjes), 70 ,20, 30, 30)); } //Tekent standaard de coin en stelt de coins gelijk aan punten (kijk while functie) coin = punten; coins.add(new Coin(laadPlaatje("coin.png"), 10,10, 50, 50)); } }
13-2 Niek
Game/src/Spel.java
13-2 Niek
Java
mit
68e9abd0fd6859e27a6388c95e8d9e2a372c88f4
0
freecode/FreeVoteBot,freecode/FreeVoteBot,freecode/FreeVoteBot
package org.freecode.irc.votebot.entity; import java.sql.ResultSet; import java.sql.SQLException; /** * Created with IntelliJ IDEA. * User: Deprecated * Date: 11/21/13 * Time: 7:29 PM */ public class Poll { private int id; private long expiry; private String question, options, creator; private boolean closed; public Poll(ResultSet rs) throws SQLException { id = rs.getInt(1); question = rs.getString(2); options = rs.getString(3); closed = rs.getBoolean(4); expiry = rs.getInt(5); creator = rs.getString(6); } public int getId() { return id; } public long getExpiry() { return expiry; } public String getQuestion() { return question; } public String getOptions() { return options; } public String getCreator() { return creator; } public boolean isClosed() { return closed; } }
src/main/java/org/freecode/irc/votebot/entity/Poll.java
package org.freecode.irc.votebot.entity; import java.sql.ResultSet; import java.sql.SQLException; /** * Created with IntelliJ IDEA. * User: Deprecated * Date: 11/21/13 * Time: 7:29 PM */ public class Poll { private int id, expiry; private String question, options, creator; private boolean closed; public Poll(ResultSet rs) throws SQLException { id = rs.getInt(1); question = rs.getString(2); options = rs.getString(3); closed = rs.getBoolean(4); expiry = rs.getInt(5); creator = rs.getString(6); } public int getId() { return id; } public int getExpiry() { return expiry; } public String getQuestion() { return question; } public String getOptions() { return options; } public String getCreator() { return creator; } public boolean isClosed() { return closed; } }
more fixing of deprecated's derps this time he stored a unix timestamp (in millis) with an int (in JAVA)
src/main/java/org/freecode/irc/votebot/entity/Poll.java
more fixing of deprecated's derps this time he stored a unix timestamp (in millis) with an int (in JAVA)
Java
mit
40a2a9679219bda59d1c40d64ae9c4df9a192bb5
0
kulcsartibor/jmxtrans,kevinconaway/jmxtrans,peterwoj/jmxtrans,magullo/jmxtrans,peterwoj/jmxtrans,RTBHOUSE/jmxtrans,Stackdriver/jmxtrans,magullo/jmxtrans,kulcsartibor/jmxtrans,allenbhuiyan/jmxtrans,jmxtrans/jmxtrans,kevinconaway/jmxtrans,yogoloth/jmxtrans,kevinconaway/jmxtrans,RTBHOUSE/jmxtrans,allenbhuiyan/jmxtrans,jmxtrans/jmxtrans,Shopify/jmxtrans,allenbhuiyan/jmxtrans,yogoloth/jmxtrans,derjust/jmxtrans,airbnb/jmxtrans,derjust/jmxtrans,peterwoj/jmxtrans,jmxtrans/jmxtrans,derjust/jmxtrans,Shopify/jmxtrans,kulcsartibor/jmxtrans,jmxtrans/jmxtrans,kevinconaway/jmxtrans,kulcsartibor/jmxtrans,derjust/jmxtrans,airbnb/jmxtrans,magullo/jmxtrans,RTBHOUSE/jmxtrans,peterwoj/jmxtrans,yogoloth/jmxtrans,RTBHOUSE/jmxtrans,Stackdriver/jmxtrans,magullo/jmxtrans,jmxtrans/jmxtrans,allenbhuiyan/jmxtrans,yogoloth/jmxtrans
package com.googlecode.jmxtrans; import java.util.ArrayList; import java.util.List; import java.util.TreeMap; import org.junit.Assert; import org.junit.Test; import com.googlecode.jmxtrans.util.PropertyResolver; public class PropertyResolverTests { @Test public void testProps() { System.setProperty("myhost", "w2"); System.setProperty("myport", "1099"); String s1 = "${xxx} : ${yyy}"; String s2 = PropertyResolver.resolveProps(s1); Assert.assertEquals(s1, s2); s1 = "${myhost} : ${myport}"; s2 = PropertyResolver.resolveProps(s1); Assert.assertEquals("w2 : 1099", s2); s1 = "${myhost} : ${myaltport:2099}"; s2 = PropertyResolver.resolveProps(s1); Assert.assertEquals("w2 : 2099", s2); s1 = "${myhost}:2099"; s2 = PropertyResolver.resolveProps(s1); Assert.assertEquals("w2:2099", s2); } @Test public void testMap() { TreeMap<String, Object> map = new TreeMap<String, Object>(); map.put("host", "${myhost}"); map.put("port", "${myport}"); map.put("count", new Integer(10)); PropertyResolver.resolveMap(map); Assert.assertEquals("w2", map.get("host")); Assert.assertEquals("1099", map.get("port")); Assert.assertEquals(new Integer(10), map.get("count")); } @Test public void testList() { List<String> list = new ArrayList<String>(); list.add("${myhost}"); list.add("${myport}"); list.add("count"); PropertyResolver.resolveList(list); Assert.assertEquals("w2", list.get(0)); Assert.assertEquals("1099", list.get(1)); Assert.assertEquals("count", list.get(2)); } }
test/com/googlecode/jmxtrans/PropertyResolverTests.java
package com.googlecode.jmxtrans; import java.util.ArrayList; import java.util.List; import java.util.TreeMap; import org.junit.Assert; import org.junit.Test; import com.googlecode.jmxtrans.util.PropertyResolver; public class PropertyResolverTests { @Test public void testProps() { System.setProperty("myhost", "w2"); System.setProperty("myport", "1099"); String s1 = "${xxx} : ${yyy}"; String s2 = PropertyResolver.resolveProps(s1); Assert.assertEquals(s1, s2); s1 = "${myhost} : ${myport}"; s2 = PropertyResolver.resolveProps(s1); Assert.assertEquals("w2 : 1099", s2); s1 = "${myhost} : ${myaltport:2099}"; s2 = PropertyResolver.resolveProps(s1); Assert.assertEquals("w2 : 2099", s2); } @Test public void testMap() { TreeMap<String, Object> map = new TreeMap<String, Object>(); map.put("host", "${myhost}"); map.put("port", "${myport}"); map.put("count", new Integer(10)); PropertyResolver.resolveMap(map); Assert.assertEquals("w2", map.get("host")); Assert.assertEquals("1099", map.get("port")); Assert.assertEquals(new Integer(10), map.get("count")); } @Test public void testList() { List<String> list = new ArrayList<String>(); list.add("${myhost}"); list.add("${myport}"); list.add("count"); PropertyResolver.resolveList(list); Assert.assertEquals("w2", list.get(0)); Assert.assertEquals("1099", list.get(1)); Assert.assertEquals("count", list.get(2)); } }
Unit test for mixed values
test/com/googlecode/jmxtrans/PropertyResolverTests.java
Unit test for mixed values
Java
agpl-3.0
3e039b67241a4115f1851c6cb7a0c57f4907c7b0
0
DPBandA/jmts,DPBandA/jmts
/* Job Management & Tracking System (JMTS) Copyright (C) 2017 D P Bennett & Associates Limited This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. Email: info@dpbennett.com.jm */ package jm.com.dpbennett.jmts.managers; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.Serializable; import java.math.BigDecimal; import java.sql.Connection; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.event.ActionEvent; import javax.faces.event.AjaxBehaviorEvent; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceUnit; import jm.com.dpbennett.business.entity.AccPacCustomer; import jm.com.dpbennett.business.entity.AccPacDocument; import jm.com.dpbennett.business.entity.AccountingCode; import jm.com.dpbennett.business.entity.Alert; import jm.com.dpbennett.business.entity.CashPayment; import jm.com.dpbennett.business.entity.Client; import jm.com.dpbennett.business.entity.CostCode; import jm.com.dpbennett.business.entity.CostComponent; import jm.com.dpbennett.business.entity.Department; import jm.com.dpbennett.business.entity.DepartmentUnit; import jm.com.dpbennett.business.entity.Discount; import jm.com.dpbennett.business.entity.Employee; import jm.com.dpbennett.business.entity.Job; import jm.com.dpbennett.business.entity.JobCosting; import jm.com.dpbennett.business.entity.JobCostingAndPayment; import jm.com.dpbennett.business.entity.JobManagerUser; import jm.com.dpbennett.business.entity.Laboratory; import jm.com.dpbennett.business.entity.Preference; import jm.com.dpbennett.business.entity.Service; import jm.com.dpbennett.business.entity.SystemOption; import jm.com.dpbennett.business.entity.Tax; import jm.com.dpbennett.business.entity.UnitCost; import jm.com.dpbennett.business.entity.management.MessageManagement; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import org.primefaces.event.CellEditEvent; import org.primefaces.event.SelectEvent; import org.primefaces.model.DefaultStreamedContent; import org.primefaces.model.StreamedContent; import jm.com.dpbennett.business.entity.management.BusinessEntityManagement; import jm.com.dpbennett.business.entity.utils.BusinessEntityUtils; import jm.com.dpbennett.wal.managers.HumanResourceManager; import jm.com.dpbennett.wal.utils.BeanUtils; import jm.com.dpbennett.wal.utils.DialogActionHandler; import jm.com.dpbennett.wal.utils.FinancialUtils; import jm.com.dpbennett.wal.utils.Utils; import jm.com.dpbennett.wal.utils.MainTabView; import jm.com.dpbennett.wal.utils.PrimeFacesUtils; import jm.com.dpbennett.wal.utils.ReportUtils; import net.sf.jasperreports.engine.JasperCompileManager; import net.sf.jasperreports.engine.JasperReport; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFDataFormat; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.primefaces.PrimeFaces; import org.primefaces.component.selectonemenu.SelectOneMenu; /** * This class handles financial matters pertaining to a job. * * @author Desmond P. Bennett (info@dpbenentt.com.jm) */ public class JobFinanceManager implements Serializable, BusinessEntityManagement, DialogActionHandler, MessageManagement { @PersistenceUnit(unitName = "JMTSPU") private EntityManagerFactory EMF1; @PersistenceUnit(unitName = "AccPacPU") private EntityManagerFactory EMF2; private CashPayment selectedCashPayment; private StreamedContent jobCostingFile; private Integer longProcessProgress; private AccPacCustomer accPacCustomer; private List<AccPacDocument> filteredAccPacCustomerDocuments; private Boolean useAccPacCustomerList; private CostComponent selectedCostComponent; private JobCostingAndPayment selectedJobCostingAndPayment; private String selectedJobCostingTemplate; private Department unitCostDepartment; private UnitCost currentUnitCost; private List<UnitCost> unitCosts; private String dialogActionHandlerId; private List<Job> jobsWithCostings; private Job currentJobWithCosting; private Department jobCostDepartment; private Boolean showPrepayments; private String invalidFormFieldMessage; private String dialogMessage; private String dialogMessageHeader; private String dialogMessageSeverity; private Boolean dialogRenderOkButton; private Boolean dialogRenderYesButton; private Boolean dialogRenderNoButton; private Boolean dialogRenderCancelButton; private DialogActionHandler dialogActionHandler; private Boolean enableOnlyPaymentEditing; private JobManager jobManager; private JobContractManager jobContractManager; private Boolean edit; private String fileDownloadErrorMessage; private MainTabView mainTabView; private JobManagerUser user; /** * Creates a new instance of the JobFinanceManager class. */ public JobFinanceManager() { init(); } /** * Attempts to approve the selected job costing(s). * @see JobFinanceManager#canChangeJobCostingApprovalStatus(jm.com.dpbennett.business.entity.Job) */ public void approveSelectedJobCostings() { int numCostingsCApproved = 0; if (getJobManager().getSelectedJobs().length > 0) { EntityManager em = getEntityManager1(); for (Job job : getJobManager().getSelectedJobs()) { if (!job.getJobCostingAndPayment().getCostingApproved()) { if (canChangeJobCostingApprovalStatus(job)) { numCostingsCApproved++; job.getJobCostingAndPayment().setCostingApproved(true); job.getJobStatusAndTracking().setDateCostingApproved(new Date()); job.getJobCostingAndPayment().setCostingApprovedBy( getUser().getEmployee()); job.getJobCostingAndPayment().setIsDirty(true); job.save(em); } else { return; } } else { PrimeFacesUtils.addMessage("Aready Approved", "The job costing for " + job.getJobNumber() + " was already approved", FacesMessage.SEVERITY_WARN); } } PrimeFacesUtils.addMessage("Job Costing(s) Approved", "" + numCostingsCApproved + " job costing(s) approved", FacesMessage.SEVERITY_INFO); } else { PrimeFacesUtils.addMessage("No Selection", "No job costing was selected", FacesMessage.SEVERITY_WARN); } } /** * Attempts to create an invoice for the job costing of the specified job. * @see JobFinanceManager#canChangeJobCostingApprovalStatus(jm.com.dpbennett.business.entity.Job) * @param job * @param invoice * @return */ public Boolean invoiceJobCosting(Job job, Boolean invoice) { prepareToInvoiceJobCosting(job); if (canInvoiceJobCosting(job)) { if (invoice) { job.getJobCostingAndPayment().setInvoiced(invoice); job.getJobStatusAndTracking().setDateCostingInvoiced(new Date()); job.getJobCostingAndPayment().setCostingInvoicedBy(getUser().getEmployee()); } else { job.getJobCostingAndPayment().setInvoiced(invoice); job.getJobStatusAndTracking().setDateCostingInvoiced(null); job.getJobCostingAndPayment().setCostingInvoicedBy(null); } setJobCostingAndPaymentDirty(job, true); return true; } else { // Reset invoiced status job.getJobCostingAndPayment().setInvoiced(!invoice); return false; } } /** * Attempts to create invoices for job costings of the selected jobs. */ public void invoiceSelectedJobCostings() { int numInvoicesCreated = 0; try { if (getJobManager().getSelectedJobs().length > 0) { EntityManager em = getEntityManager1(); for (Job job : getJobManager().getSelectedJobs()) { if (!job.getJobCostingAndPayment().getInvoiced()) { if (invoiceJobCosting(job, true)) { job.save(em); numInvoicesCreated++; } else { return; } } else { PrimeFacesUtils.addMessage("Aready Invoiced", "The job costing for " + job.getJobNumber() + " was already invoiced", FacesMessage.SEVERITY_WARN); return; } } PrimeFacesUtils.addMessage("Invoice(s) Created", "" + numInvoicesCreated + " invoice(s) created", FacesMessage.SEVERITY_INFO); } else { PrimeFacesUtils.addMessage("No Selection", "No job costing was selected", FacesMessage.SEVERITY_WARN); } } catch (Exception e) { System.out.println("Error occurred while invoicing: " + e); PrimeFacesUtils.addMessage("Invoicing Error", "An error occurred while creating one or more invoices. " + "Please check that all required information such as a client Id is provided.", FacesMessage.SEVERITY_ERROR); } } /** * Gets the total tax in the default currency associated with the specified job. * @param job * @return */ public Double getTotalTax(Job job) { return job.getJobCostingAndPayment().getTotalTax(); } /** * Gets the total discount in the default currency associated with the specified job. * @param job * @return */ public Double getTotalDiscount(Job job) { return job.getJobCostingAndPayment().getTotalDiscount(); } /** * Gets the tax object associated with the specified job. * A default tax object with a value of 0.0 is set and returned if the tax object is not set. * @param job * @return */ public Tax getTax(Job job) { Tax tax = job.getJobCostingAndPayment().getTax(); // Handle the case where the tax is not set if (tax.getId() == null) { if (job.getJobCostingAndPayment().getPercentageGCT() != null) { // Find and use tax object Tax tax2 = Tax.findByValue(getEntityManager1(), Double.parseDouble(job.getJobCostingAndPayment().getPercentageGCT())); if (tax2 != null) { tax = tax2; job.getJobCostingAndPayment().setTax(tax2); } else { tax = Tax.findDefault(getEntityManager1(), "0.0"); job.getJobCostingAndPayment().setTax(tax); } } else { tax = Tax.findDefault(getEntityManager1(), "0.0"); job.getJobCostingAndPayment().setTax(tax); } } return tax; } /** * Gets the tax associated with the current job. * @return */ public Tax getTax() { return getTax(getCurrentJob()); } /** * Sets the tax associated with the current job. * @param tax */ public void setTax(Tax tax) { getCurrentJob().getJobCostingAndPayment().setTax(tax); } public Discount getDiscount() { return getDiscount(getCurrentJob()); } public Discount getDiscount(Job job) { Discount discount = job.getJobCostingAndPayment().getDiscount(); // Handle the case where the discount object is not set. if (discount.getId() == null) { discount = Discount.findByValueAndType( getEntityManager1(), job.getJobCostingAndPayment().getDiscountValue(), job.getJobCostingAndPayment().getDiscountType()); if (discount == null) { discount = Discount.findDefault( getEntityManager1(), job.getJobCostingAndPayment().getDiscountValue().toString(), job.getJobCostingAndPayment().getDiscountValue(), job.getJobCostingAndPayment().getDiscountType()); job.getJobCostingAndPayment().setDiscount(discount); } else { job.getJobCostingAndPayment().setDiscount(discount); } } return discount; } public void setDiscount(Discount discount) { getCurrentJob().getJobCostingAndPayment().setDiscount(discount); } public List<Tax> completeTax(String query) { EntityManager em; try { em = getEntityManager1(); List<Tax> taxes = Tax.findActiveTaxesByNameAndDescription(em, query); return taxes; } catch (Exception e) { return new ArrayList<>(); } } public List<Discount> completeDiscount(String query) { EntityManager em; try { em = getEntityManager1(); List<Discount> discounts = Discount.findActiveDiscountsByNameAndDescription(em, query); return discounts; } catch (Exception e) { return new ArrayList<>(); } } /** * Returns the discount type that can be applied to a payment/amount * * @return */ public List getDiscountTypes() { return FinancialUtils.getDiscountTypes(); } public List getCostTypeList() { return FinancialUtils.getCostTypeList(); } public List getPaymentTypes() { return FinancialUtils.getPaymentTypes(); } public List getPaymentPurposes() { return FinancialUtils.getPaymentPurposes(); } public void closeDialog() { PrimeFacesUtils.closeDialog(null); } public JobCostingAndPayment getSelectedJobCostingAndPayment() { return selectedJobCostingAndPayment; } public void setSelectedJobCostingAndPayment(JobCostingAndPayment selectedJobCostingAndPayment) { this.selectedJobCostingAndPayment = selectedJobCostingAndPayment; } public void cancelDialogEdit(ActionEvent actionEvent) { PrimeFaces.current().dialog().closeDynamic(null); } public MainTabView getMainTabView() { return mainTabView; } public void setMainTabView(MainTabView mainTabView) { this.mainTabView = mainTabView; } public StreamedContent getInvoicesFile() { try { ByteArrayInputStream stream; stream = getInvoicesFileInputStream( new File(getClass().getClassLoader(). getResource("/reports/" + (String) SystemOption.getOptionValueObject(getEntityManager1(), "AccpacInvoicesFileTemplateName")).getFile())); setLongProcessProgress(100); return new DefaultStreamedContent(stream, "application/xlsx", "Invoices-" + BusinessEntityUtils.getDateInMediumDateAndTimeFormat(new Date()) + "-" + fileDownloadErrorMessage + ".xlsx"); } catch (Exception ex) { System.out.println(ex); } return null; } public ByteArrayInputStream getInvoicesFileInputStream( File file) { try { FileInputStream inp = new FileInputStream(file); int invoiceRow = 1; int invoiceCol; int invoiceDetailsRow = 1; int invoiceDetailsCol; int invoiceOptionalFieldsRow = 1; int invoiceOptionalFieldsCol; fileDownloadErrorMessage = ""; XSSFWorkbook wb = new XSSFWorkbook(inp); XSSFCellStyle stringCellStyle = wb.createCellStyle(); XSSFCellStyle integerCellStyle = wb.createCellStyle(); XSSFCellStyle doubleCellStyle = wb.createCellStyle(); XSSFDataFormat doubleFormat = wb.createDataFormat(); doubleCellStyle.setDataFormat(doubleFormat.getFormat("#,##0.00")); XSSFCellStyle dateCellStyle = wb.createCellStyle(); CreationHelper createHelper = wb.getCreationHelper(); // dateCellStyle.setDataFormat( // createHelper.createDataFormat().getFormat("m/d/yyyy")); dateCellStyle.setDataFormat( createHelper.createDataFormat().getFormat("M/D/YYYY")); // Output stream for modified Excel file ByteArrayOutputStream out = new ByteArrayOutputStream(); // Get sheets XSSFSheet invoices = wb.getSheet("Invoices"); XSSFSheet invoiceDetails = wb.getSheet("Invoice_Details"); XSSFSheet invoiceOptionalFields = wb.getSheet("Invoice_Optional_Fields"); // Get report data Job reportData[] = getJobManager().getSelectedJobs(); for (Job job : reportData) { // Export only if costing was invoiced if (job.getJobCostingAndPayment().getInvoiced()) { invoiceCol = 0; invoiceDetailsCol = 0; invoiceOptionalFieldsCol = 0; prepareToInvoiceJobCosting(job); // Fill out the Invoices sheet // CNTBTCH (batch number) ReportUtils.setExcelCellValue(wb, invoices, invoiceRow, invoiceCol++, 0, "java.lang.Integer", integerCellStyle); // CNTITEM (Item number) ReportUtils.setExcelCellValue(wb, invoices, invoiceRow, invoiceCol++, invoiceRow, "java.lang.Integer", integerCellStyle); // IDCUST (Customer Id) ReportUtils.setExcelCellValue(wb, invoices, invoiceRow, invoiceCol++, job.getClient().getFinancialAccount().getIdCust(), "java.lang.String", stringCellStyle); // IDINVC (Invoice No./Id) //ReportUtils.setExcelCellValue(wb, invoices, invoiceRow, invoiceCol++, // "JMTS" + job.getDepartmentAssignedToJob().getCode() // + job.getYearReceived() + "" // + BusinessEntityUtils.getFourDigitString(job.getJobSequenceNumber()), // "java.lang.String", stringCellStyle); // TEXTTRX ReportUtils.setExcelCellValue(wb, invoices, invoiceRow, invoiceCol++, 1, "java.lang.Integer", integerCellStyle); // IDTRX ReportUtils.setExcelCellValue(wb, invoices, invoiceRow, invoiceCol++, 11, "java.lang.Integer", integerCellStyle); // ORDRNBR ReportUtils.setExcelCellValue(wb, invoices, invoiceRow, invoiceCol++, "", "java.lang.String", stringCellStyle); // CUSTPO ReportUtils.setExcelCellValue(wb, invoices, invoiceRow, invoiceCol++, job.getJobCostingAndPayment().getPurchaseOrderNumber(), "java.lang.String", stringCellStyle); // INVCDESC ReportUtils.setExcelCellValue(wb, invoices, invoiceRow, invoiceCol++, job.getInstructions(), "java.lang.String", stringCellStyle); // DATEINVC ReportUtils.setExcelCellValue(wb, invoices, invoiceRow, invoiceCol++, job.getJobStatusAndTracking().getDateCostingInvoiced(), "java.util.Date", dateCellStyle); // INVCTYPE ReportUtils.setExcelCellValue(wb, invoices, invoiceRow, invoiceCol++, 1, // tk org. 2 "java.lang.Integer", integerCellStyle); // Fill out Invoice Details sheet // Add an item for each cost component // CNTBTCH (batch number) int index = 0; for (CostComponent costComponent : job.getJobCostingAndPayment().getAllSortedCostComponents()) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, 0, // CNTBTCH "java.lang.Integer", integerCellStyle); } // Add Tax row if any if (getTax(job).getTaxValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, 0, // CNTBTCH "java.lang.Integer", integerCellStyle); } // Add Discount row if any if (getDiscount(job).getDiscountValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, 0, // CNTBTCH "java.lang.Integer", integerCellStyle); } // CNTITEM (Item/Invoice number/index) index = 0; invoiceDetailsCol++; for (CostComponent costComponent : job.getJobCostingAndPayment().getAllSortedCostComponents()) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, invoiceRow, // CNTITEM "java.lang.Integer", integerCellStyle); } // Add Tax row if any if (getTax(job).getTaxValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, invoiceRow, // CNTITEM "java.lang.Integer", integerCellStyle); } // Add Discount row if any if (getDiscount(job).getDiscountValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, invoiceRow, // CNTITEM "java.lang.Integer", integerCellStyle); } // CNTLINE index = 0; invoiceDetailsCol++; for (CostComponent costComponent : job.getJobCostingAndPayment().getAllSortedCostComponents()) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, index, // CNTLINE "java.lang.Integer", integerCellStyle); } // Add Tax row if any if (getTax(job).getTaxValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, index, // CNTLINE "java.lang.Integer", integerCellStyle); } // Add Discount row if any if (getDiscount(job).getDiscountValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, index, // CNTLINE "java.lang.Integer", integerCellStyle); } // IDITEM index = 0; invoiceDetailsCol++; for (CostComponent costComponent : job.getJobCostingAndPayment().getAllSortedCostComponents()) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, getRevenueCodeAbbreviation(job), // IDITEM "java.lang.String", stringCellStyle); } // Add Tax row if any if (getTax(job).getTaxValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, getTaxCodeAbbreviation(job), // IDITEM "java.lang.String", stringCellStyle); } // Add Discount row if any if (getDiscount(job).getDiscountValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, getDiscountCodeAbbreviation(job), // IDITEM "java.lang.String", stringCellStyle); } // IDDIST index = 0; invoiceDetailsCol++; for (CostComponent costComponent : job.getJobCostingAndPayment().getAllSortedCostComponents()) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, getRevenueCodeAbbreviation(job), // IDDIST "java.lang.String", stringCellStyle); } // Add Tax row if any if (getTax(job).getTaxValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, getTaxCodeAbbreviation(job), // IDDIST "java.lang.String", stringCellStyle); } // Add Discount row if any if (getDiscount(job).getDiscountValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, getDiscountCodeAbbreviation(job), // IDDIST "java.lang.String", stringCellStyle); } // TEXTDESC index = 0; invoiceDetailsCol++; for (CostComponent costComponent : job.getJobCostingAndPayment().getAllSortedCostComponents()) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, costComponent.getName(), // TEXTDESC "java.lang.String", stringCellStyle); } // Add Tax row if any if (getTax(job).getTaxValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, job.getJobCostingAndPayment().getTax().getDescription(), // TEXTDESC "java.lang.String", stringCellStyle); } // Add Discount row if any if (getDiscount(job).getDiscountValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, job.getJobCostingAndPayment().getDiscount().getDescription(), // TEXTDESC "java.lang.String", stringCellStyle); } // UNITMEAS index = 0; invoiceDetailsCol++; for (CostComponent costComponent : job.getJobCostingAndPayment().getAllSortedCostComponents()) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, "EACH", // UNITMEAS "java.lang.String", stringCellStyle); } // Add Tax row if any if (getTax(job).getTaxValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, "EACH", // UNITMEAS "java.lang.String", stringCellStyle); } // Add Discount row if any if (getDiscount(job).getDiscountValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, "EACH", // UNITMEAS "java.lang.String", stringCellStyle); } // QTYINVC index = 0; invoiceDetailsCol++; for (CostComponent costComponent : job.getJobCostingAndPayment().getAllSortedCostComponents()) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, costComponent.getHoursOrQuantity().intValue(), // UNITMEAS "java.lang.Integer", integerCellStyle); } // Add Tax row if any if (getTax(job).getTaxValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, 1, // QTYINVC "java.lang.Integer", integerCellStyle); } // Add Discount row if any if (getDiscount(job).getDiscountValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, 1, // QTYINVC "java.lang.Integer", integerCellStyle); } // AMTPRIC index = 0; invoiceDetailsCol++; for (CostComponent costComponent : job.getJobCostingAndPayment().getAllSortedCostComponents()) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, costComponent.getRate(), // AMTPRIC "java.lang.Double", doubleCellStyle); } // Add Tax row if any if (getTax(job).getTaxValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, getTotalTax(job), // AMTPRIC "java.lang.Double", doubleCellStyle); } // Add Discount row if any if (getDiscount(job).getDiscountValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, -getTotalDiscount(job), // AMTPRIC "java.lang.Double", doubleCellStyle); } // AMTEXTN index = 0; invoiceDetailsCol++; for (CostComponent costComponent : job.getJobCostingAndPayment().getAllSortedCostComponents()) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, costComponent.getCost(), // AMTEXTN "java.lang.Double", doubleCellStyle); } // Add Tax row if any if (getTax(job).getTaxValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, getTotalTax(job), // AMTEXTN "java.lang.Double", doubleCellStyle); } // Add Discount row if any if (getDiscount(job).getDiscountValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, -getTotalDiscount(job), // AMTEXTN "java.lang.Double", doubleCellStyle); } // Fill out Invoice Optional Fields sheet // CNTBTCH (batch number) int index2 = 0; for (int i = 0; i < 4; i++) { ReportUtils.setExcelCellValue(wb, invoiceOptionalFields, invoiceOptionalFieldsRow + index2++, invoiceOptionalFieldsCol, 0, // CNTBTCH "java.lang.Integer", integerCellStyle); } // CNTITEM (Item/Invoice number/index) index2 = 0; ++invoiceOptionalFieldsCol; for (int i = 0; i < 4; i++) { ReportUtils.setExcelCellValue(wb, invoiceOptionalFields, invoiceOptionalFieldsRow + index2++, invoiceOptionalFieldsCol, invoiceRow, // CNTITEM "java.lang.Integer", integerCellStyle); } // OPTFIELD index2 = 0; ++invoiceOptionalFieldsCol; // DEPTCODE ReportUtils.setExcelCellValue(wb, invoiceOptionalFields, invoiceOptionalFieldsRow + index2++, invoiceOptionalFieldsCol, "DEPTCODE", // DEPTCODE "java.lang.String", stringCellStyle); // INVCONTACT ReportUtils.setExcelCellValue(wb, invoiceOptionalFields, invoiceOptionalFieldsRow + index2++, invoiceOptionalFieldsCol, "INVCONTACT", // INVCONTACT "java.lang.String", stringCellStyle); // JOBNO ReportUtils.setExcelCellValue(wb, invoiceOptionalFields, invoiceOptionalFieldsRow + index2++, invoiceOptionalFieldsCol, "JOBNO", // JOBNO "java.lang.String", stringCellStyle); // REFNO ReportUtils.setExcelCellValue(wb, invoiceOptionalFields, invoiceOptionalFieldsRow + index2++, invoiceOptionalFieldsCol, "REFNO", // REFNO "java.lang.String", stringCellStyle); // OPTFIELD/VALUE index2 = 0; ++invoiceOptionalFieldsCol; // DEPTCODE ReportUtils.setExcelCellValue(wb, invoiceOptionalFields, invoiceOptionalFieldsRow + index2++, invoiceOptionalFieldsCol, job.getDepartmentAssignedToJob().getCode(), // DEPTCODE "java.lang.String", stringCellStyle); // INVCONTACT ReportUtils.setExcelCellValue(wb, invoiceOptionalFields, invoiceOptionalFieldsRow + index2++, invoiceOptionalFieldsCol, job.getContact().getFirstName() + " " + job.getContact().getLastName(), // INVCONTACT "java.lang.String", stringCellStyle); // JOBNO ReportUtils.setExcelCellValue(wb, invoiceOptionalFields, invoiceOptionalFieldsRow + index2++, invoiceOptionalFieldsCol, job.getJobNumber(), // JOBNO "java.lang.String", stringCellStyle); // REFNO ReportUtils.setExcelCellValue(wb, invoiceOptionalFields, invoiceOptionalFieldsRow + index2++, invoiceOptionalFieldsCol, "", // REFNO "java.lang.String", stringCellStyle); // Prepare for next invoice invoiceDetailsRow = invoiceDetailsRow + index; invoiceOptionalFieldsRow = invoiceOptionalFieldsRow + index2; invoiceRow++; } } // Write modified Excel file and return it wb.write(out); return new ByteArrayInputStream(out.toByteArray()); } catch (IOException ex) { System.out.println(ex); } return null; } private String getDiscountCodeAbbreviation(Job job) { String currentDiscountCode = // This should be a 4-digit code eg 5133 getDiscount(job).getAccountingCode().getCode(); String deptFullCode = HumanResourceManager.getDepartmentFullCode(getEntityManager1(), job.getDepartmentAssignedToJob()); // Find an accounting code that contains the department's full code AccountingCode accountingCode = AccountingCode.findActiveByCode(getEntityManager1(), currentDiscountCode + "-" + deptFullCode); if (accountingCode != null) { return accountingCode.getAbbreviation(); } else { return getDiscount(job).getAccountingCode().getAbbreviation(); } } private String getTaxCodeAbbreviation(Job job) { String currentTaxCode = // This should be a 4-digit code eg 5133 getTax(job).getAccountingCode().getCode(); String deptFullCode = HumanResourceManager.getDepartmentFullCode(getEntityManager1(), job.getDepartmentAssignedToJob()); // Find an accounting code that contains the department's full code AccountingCode accountingCode = AccountingCode.findActiveByCode(getEntityManager1(), currentTaxCode + "-" + deptFullCode); if (accountingCode != null) { return accountingCode.getAbbreviation(); } else { return getTax(job).getAccountingCode().getAbbreviation(); } } private String getRevenueCodeAbbreviation(Job job) { String revenueCode; String revenueCodeAbbr; if (!job.getServices().isEmpty()) { revenueCode = job.getServices().get(0).getAccountingCode().getCode(); String deptFullCode = HumanResourceManager.getDepartmentFullCode(getEntityManager1(), job.getDepartmentAssignedToJob()); // Find an accounting code that contains the department's full code AccountingCode accountingCode = AccountingCode.findActiveByCode(getEntityManager1(), revenueCode + "-" + deptFullCode); if (accountingCode != null) { revenueCodeAbbr = accountingCode.getAbbreviation(); } else { revenueCodeAbbr = "MISC"; } } else { // Get and use default accounting code Service service = Service.findActiveByNameAndAccountingCode( getEntityManager1(), "Miscellaneous", HumanResourceManager.getDepartmentFullCode(getEntityManager1(), job.getDepartmentAssignedToJob())); if (service != null) { revenueCodeAbbr = service.getAccountingCode().getAbbreviation(); } else { // tk NB: Just using this revenue code for testing for now. // This value is to be obtained from system option. revenueCodeAbbr = "MISC"; } } return revenueCodeAbbr; } public Boolean getEdit() { return edit; } public void setEdit(Boolean edit) { this.edit = edit; } public JobManager getJobManager() { if (jobManager == null) { jobManager = BeanUtils.findBean("jobManager"); } return jobManager; } public JobContractManager getJobContractManager() { if (jobContractManager == null) { jobContractManager = BeanUtils.findBean("jobContractManager"); } return jobContractManager; } private void init() { longProcessProgress = 0; accPacCustomer = new AccPacCustomer(null); useAccPacCustomerList = false; selectedCashPayment = null; selectedCostComponent = null; unitCostDepartment = null; jobCostDepartment = null; filteredAccPacCustomerDocuments = new ArrayList<>(); } public void reset() { init(); } public Boolean getEnableOnlyPaymentEditing() { if (enableOnlyPaymentEditing == null) { enableOnlyPaymentEditing = false; } return enableOnlyPaymentEditing; } public void setEnableOnlyPaymentEditing(Boolean enableOnlyPaymentEditing) { this.enableOnlyPaymentEditing = enableOnlyPaymentEditing; } public Boolean getDialogRenderCancelButton() { return dialogRenderCancelButton; } public void setDialogRenderCancelButton(Boolean dialogRenderCancelButton) { this.dialogRenderCancelButton = dialogRenderCancelButton; } public void setDialogActionHandler(DialogActionHandler dialogActionHandler) { this.dialogActionHandler = dialogActionHandler; } public Boolean getDialogRenderOkButton() { return dialogRenderOkButton; } public void setDialogRenderOkButton(Boolean dialogRenderOkButton) { this.dialogRenderOkButton = dialogRenderOkButton; } public Boolean getDialogRenderYesButton() { return dialogRenderYesButton; } public void setDialogRenderYesButton(Boolean dialogRenderYesButton) { this.dialogRenderYesButton = dialogRenderYesButton; } public Boolean getDialogRenderNoButton() { return dialogRenderNoButton; } public void setDialogRenderNoButton(Boolean dialogRenderNoButton) { this.dialogRenderNoButton = dialogRenderNoButton; } public String getDialogMessage() { return dialogMessage; } public void setDialogMessage(String dialogMessage) { this.dialogMessage = dialogMessage; } public String getDialogMessageHeader() { return dialogMessageHeader; } public void setDialogMessageHeader(String dialogMessageHeader) { this.dialogMessageHeader = dialogMessageHeader; } public String getDialogMessageSeverity() { return dialogMessageSeverity; } public void setDialogMessageSeverity(String dialogMessageSeverity) { this.dialogMessageSeverity = dialogMessageSeverity; } public EntityManager getEntityManager1() { return EMF1.createEntityManager(); } public JobManagerUser getUser() { return user; } public void setUser(JobManagerUser user) { this.user = user; } @Override public String getInvalidFormFieldMessage() { return invalidFormFieldMessage; } @Override public void setInvalidFormFieldMessage(String invalidFormFieldMessage) { this.invalidFormFieldMessage = invalidFormFieldMessage; } public void displayCommonMessageDialog(DialogActionHandler dialogActionHandler, String dialogMessage, String dialogMessageHeader, String dialoMessageSeverity) { setDialogActionHandler(dialogActionHandler); setDialogRenderOkButton(true); setDialogRenderYesButton(false); setDialogRenderNoButton(false); setDialogMessage(dialogMessage); setDialogMessageHeader(dialogMessageHeader); setDialogMessageSeverity(dialoMessageSeverity); PrimeFaces.current().ajax().update("commonMessageDialogForm"); PrimeFaces.current().executeScript("PF('commonMessageDialog').show();"); } public void displayCommonConfirmationDialog(DialogActionHandler dialogActionHandler, String dialogMessage, String dialogMessageHeader, String dialoMessageSeverity) { setDialogActionHandler(dialogActionHandler); setDialogRenderOkButton(false); setDialogRenderYesButton(true); setDialogRenderNoButton(true); setDialogRenderCancelButton(true); setDialogMessage(dialogMessage); setDialogMessageHeader(dialogMessageHeader); setDialogMessageSeverity(dialoMessageSeverity); PrimeFaces.current().ajax().update("commonMessageDialogForm"); PrimeFaces.current().executeScript("PF('commonMessageDialog').show();"); } public void handleDialogOkButtonPressed() { if (dialogActionHandler != null) { dialogActionHandler.handleDialogOkButtonClick(); } } public void handleDialogYesButtonPressed() { if (dialogActionHandler != null) { dialogActionHandler.handleDialogYesButtonClick(); } } public void handleDialogNoButtonPressed() { if (dialogActionHandler != null) { dialogActionHandler.handleDialogNoButtonClick(); } } public void handleDialogCancelButtonPressed() { if (dialogActionHandler != null) { dialogActionHandler.handleDialogCancelButtonClick(); } } public List<AccPacDocument> getFilteredAccPacCustomerDocuments() { return filteredAccPacCustomerDocuments; } public void setFilteredAccPacCustomerDocuments(List<AccPacDocument> filteredAccPacCustomerDocuments) { this.filteredAccPacCustomerDocuments = filteredAccPacCustomerDocuments; } public Boolean getShowPrepayments() { if (showPrepayments == null) { showPrepayments = false; } return showPrepayments; } public void setShowPrepayments(Boolean showPrepayments) { this.showPrepayments = showPrepayments; } public Department getJobCostDepartment() { if (jobCostDepartment == null) { jobCostDepartment = new Department(""); } return jobCostDepartment; } public void setJobCostDepartment(Department jobCostDepartment) { this.jobCostDepartment = jobCostDepartment; } public Job getCurrentJobWithCosting() { if (currentJobWithCosting == null) { currentJobWithCosting = new Job(); } return currentJobWithCosting; } public void setCurrentJobWithCosting(Job currentJobWithCosting) { this.currentJobWithCosting = currentJobWithCosting; } public List<Job> getJobsWithCostings() { if (jobsWithCostings == null) { jobsWithCostings = new ArrayList<>(); } return jobsWithCostings; } public List<UnitCost> getUnitCosts() { if (unitCosts == null) { unitCosts = new ArrayList<>(); } return unitCosts; } public UnitCost getCurrentUnitCost() { if (currentUnitCost == null) { currentUnitCost = new UnitCost(); } return currentUnitCost; } public void setCurrentUnitCost(UnitCost currentUnitCost) { this.currentUnitCost = currentUnitCost; } public Department getUnitCostDepartment() { if (unitCostDepartment == null) { unitCostDepartment = new Department(""); } return unitCostDepartment; } public void setUnitCostDepartment(Department unitCostDepartment) { this.unitCostDepartment = unitCostDepartment; } public Boolean getCanEditJobCosting() { return getUser().getPrivilege().getCanBeFinancialAdministrator() || getCurrentJob().getJobCostingAndPayment().getCashPayments().isEmpty(); } public String getSelectedJobCostingTemplate() { return selectedJobCostingTemplate; } public void setSelectedJobCostingTemplate(String selectedJobCostingTemplate) { this.selectedJobCostingTemplate = selectedJobCostingTemplate; } private Boolean isJobAssignedToUserDepartment(Job job) { if (getUser() != null) { if (job.getDepartment().getId().longValue() == getUser().getEmployee().getDepartment().getId().longValue()) { return true; } else { return job.getSubContractedDepartment().getId().longValue() == getUser().getEmployee().getDepartment().getId().longValue(); } } else { return false; } } public void onCostComponentSelect(SelectEvent event) { selectedCostComponent = (CostComponent) event.getObject(); } public CostComponent getSelectedCostComponent() { return selectedCostComponent; } public void setSelectedCostComponent(CostComponent selectedCostComponent) { this.selectedCostComponent = selectedCostComponent; } public Boolean getUseAccPacCustomerList() { return useAccPacCustomerList; } public void setUseAccPacCustomerList(Boolean useAccPacCustomerList) { this.useAccPacCustomerList = useAccPacCustomerList; } public Integer getNumberOfDocumentsPassDocDate(Integer days) { Integer count = 0; for (AccPacDocument doc : filteredAccPacCustomerDocuments) { if (doc.getDaysOverDocumentDate() >= days) { ++count; } } return count; } public String getAccountStatus() { if (getTotalInvoicesAmountOverMaxInvDays().doubleValue() > 0.0 && getTotalInvoicesAmount().doubleValue() > 0.0) { return "hold"; } else { return "active"; } } public BigDecimal getTotalInvoicesAmountOverMaxInvDays() { BigDecimal total = new BigDecimal(0.0); for (AccPacDocument doc : filteredAccPacCustomerDocuments) { if (doc.getDaysOverdue() > getMaxDaysPassInvoiceDate()) { total = total.add(doc.getCustCurrencyAmountDue()); } } return total; } public BigDecimal getTotalInvoicesAmount() { BigDecimal total = new BigDecimal(0.0); for (AccPacDocument doc : filteredAccPacCustomerDocuments) { total = total.add(doc.getCustCurrencyAmountDue()); } return total; } public Integer getMaxDaysPassInvoiceDate() { EntityManager em = getEntityManager1(); int days = (Integer) SystemOption.getOptionValueObject(em, "maxDaysPassInvoiceDate"); return days; } /** * Get status based on the total amount on documents pass the max allowed * days pass the invoice date * * @return */ public String getAccPacCustomerAccountStatus() { if (getAccountStatus().equals("hold")) { return "HOLD"; } else { return "ACTIVE"; } } public Integer getNumDocumentsPassMaxInvDate() { return getNumberOfDocumentsPassDocDate(getMaxDaysPassInvoiceDate()); } public Integer getLongProcessProgress() { if (longProcessProgress == null) { longProcessProgress = 0; } else { if (longProcessProgress < 10) { // this is to ensure that this method does not make the progress // complete as this is done elsewhere. longProcessProgress = longProcessProgress + 1; } } return longProcessProgress; } public void onLongProcessComplete() { longProcessProgress = 0; } public void setLongProcessProgress(Integer longProcessProgress) { this.longProcessProgress = longProcessProgress; } // tk get forms public StreamedContent getJobCostingAnalysisFile(EntityManager em) { HashMap parameters = new HashMap(); try { parameters.put("jobId", getCurrentJob().getId()); Client client = getCurrentJob().getClient(); parameters.put("contactPersonName", BusinessEntityUtils.getContactFullName(getCurrentJob().getContact())); parameters.put("customerAddress", getCurrentJob().getBillingAddress().toString()); parameters.put("contactNumbers", client.getStringListOfContactPhoneNumbers()); parameters.put("jobDescription", getCurrentJob().getJobDescription()); parameters.put("totalCost", getCurrentJob().getJobCostingAndPayment().getTotalJobCostingsAmount()); parameters.put("depositReceiptNumbers", getCurrentJob().getJobCostingAndPayment().getReceiptNumbers()); parameters.put("discount", getCurrentJob().getJobCostingAndPayment().getDiscount().getDiscountValue()); parameters.put("discountType", getCurrentJob().getJobCostingAndPayment().getDiscount().getDiscountValueType()); parameters.put("deposit", getCurrentJob().getJobCostingAndPayment().getTotalPayment()); parameters.put("amountDue", getCurrentJob().getJobCostingAndPayment().getAmountDue()); parameters.put("totalTax", getTotalTax(getCurrentJob())); parameters.put("totalTaxLabel", getCurrentJob().getJobCostingAndPayment().getTotalTaxLabel()); parameters.put("grandTotalCostLabel", getCurrentJob().getJobCostingAndPayment().getTotalCostWithTaxLabel().toUpperCase().trim()); parameters.put("grandTotalCost", getCurrentJob().getJobCostingAndPayment().getTotalCost()); if (getCurrentJob().getJobCostingAndPayment().getCostingPreparedBy() != null) { parameters.put("preparedBy", getCurrentJob().getJobCostingAndPayment().getCostingPreparedBy().getFirstName() + " " + getCurrentJob().getJobCostingAndPayment().getCostingPreparedBy().getLastName()); } if (getCurrentJob().getJobCostingAndPayment().getCostingApprovedBy() != null) { parameters.put("approvedBy", getCurrentJob().getJobCostingAndPayment().getCostingApprovedBy().getFirstName() + " " + getCurrentJob().getJobCostingAndPayment().getCostingApprovedBy().getLastName()); } parameters.put("approvalDate", BusinessEntityUtils.getDateInMediumDateFormat( getCurrentJob().getJobStatusAndTracking().getDateCostingApproved())); Connection con = BusinessEntityUtils.establishConnection( (String) SystemOption.getOptionValueObject(em, "defaultDatabaseDriver"), (String) SystemOption.getOptionValueObject(em, "defaultDatabaseURL"), (String) SystemOption.getOptionValueObject(em, "defaultDatabaseUsername"), (String) SystemOption.getOptionValueObject(em, "defaultDatabasePassword")); if (con != null) { try { StreamedContent streamContent; // Compile report JasperReport jasperReport = JasperCompileManager. compileReport((String) SystemOption.getOptionValueObject(em, "jobCosting")); // Generate report JasperPrint print = JasperFillManager.fillReport(jasperReport, parameters, con); byte[] fileBytes = JasperExportManager.exportReportToPdf(print); streamContent = new DefaultStreamedContent(new ByteArrayInputStream(fileBytes), "application/pdf", "Job Costing - " + getCurrentJob().getJobNumber() + ".pdf"); setLongProcessProgress(100); return streamContent; } catch (JRException ex) { System.out.println(ex); return null; } } return null; } catch (Exception e) { System.out.println(e); return null; } } public StreamedContent getJobCostingFile() { EntityManager em; try { em = getEntityManager1(); if (getCurrentJob().getIsDirty()) { getCurrentJob().getJobCostingAndPayment().save(em); getCurrentJob().setIsDirty(false); } jobCostingFile = getJobCostingAnalysisFile(em); setLongProcessProgress(100); } catch (Exception e) { System.out.println(e); setLongProcessProgress(100); } return jobCostingFile; } public Boolean getCanExportJobCosting() { return !(getCurrentJob().getJobCostingAndPayment().getCostingApproved() && getCurrentJob().getJobCostingAndPayment().getCostingCompleted()); } private void prepareToInvoiceJobCosting(Job job) { // Ensure that services are added based on the service contract getJobContractManager().addServices(job); // Ensure that an accounting Id is added for the client AccPacCustomer financialAccount = AccPacCustomer.findByName( getEntityManager2(), job.getClient().getName()); if (financialAccount != null) { // Set accounting Id job.getClient().setAccountingId(financialAccount.getIdCust()); // Set credit limit job.getClient().setCreditLimit((financialAccount.getCreditLimit().doubleValue())); // Update and save job.getClient().setEditedBy(getUser().getEmployee()); job.getClient().setDateEdited(new Date()); job.getClient().save(getEntityManager1()); } // tk update costs, tax, discount updates } public void invoiceJobCosting() { invoiceJobCosting(getCurrentJob(), getCurrentJob().getJobCostingAndPayment().getInvoiced()); } public Boolean canInvoiceJobCosting(Job job) { // Check for permission to invoice by department that can do invoices // NB: This permission will be put in the user's profile in the future. if (!getUser().getEmployee().getDepartment().getPrivilege().getCanEditInvoicingAndPayment()) { PrimeFacesUtils.addMessage("Permission Denied", "You do not have permission to create an invoice for " + job.getJobNumber(), FacesMessage.SEVERITY_ERROR); return false; } // Check if approved if (!job.getJobCostingAndPayment().getCostingApproved()) { PrimeFacesUtils.addMessage("Job Costing NOT Approved", "The job costing was not approved for " + job.getJobNumber(), FacesMessage.SEVERITY_ERROR); return false; } // Check for a valid cleint Id if (job.getClient().getFinancialAccount().getIdCust().isEmpty()) { PrimeFacesUtils.addMessage("Client Identification required", "The client identification (Id) is not set for " + job.getJobNumber(), FacesMessage.SEVERITY_ERROR); return false; } return true; } public List<Preference> getJobTableViewPreferences() { EntityManager em = getEntityManager1(); List<Preference> prefs = Preference.findAllPreferencesByName(em, "jobTableView"); return prefs; } /** * Determine if the current user can mark the current job costing as being * completed. This is done by determining if the job was assigned to the * user. * * @param job * @return */ public Boolean canUserCompleteJobCosting(Job job) { return isJobAssignedToUserDepartment(job); } public CashPayment getSelectedCashPayment() { return selectedCashPayment; } public void setSelectedCashPayment(CashPayment selectedCashPayment) { this.selectedCashPayment = selectedCashPayment; // If this is a new cash payment ensure that all related costs are updated // and the job cost and payment saved. if (getSelectedCashPayment().getId() == null) { updateFinalCost(); updateAmountDue(); if (!getCurrentJob().prepareAndSave(getEntityManager1(), getUser()).isSuccess()) { PrimeFacesUtils.addMessage("Payment and Job NOT Saved!", "Payment and the job and the payment were NOT saved!", FacesMessage.SEVERITY_ERROR); } } } public EntityManager getEntityManager2() { return getEMF2().createEntityManager(); } public void updateJobCostingAndPayment() { setJobCostingAndPaymentDirty(true); } public void updateCashPayment() { getSelectedCashPayment().setIsDirty(true); } public void updateCostComponent() { updateCostType(); getSelectedCostComponent().setIsDirty(true); } public void updateSubcontract(AjaxBehaviorEvent event) { if (!((SelectOneMenu) event.getComponent()).getValue().toString().equals("null")) { Long subcontractId = new Long(((SelectOneMenu) event.getComponent()).getValue().toString()); Job subcontract = Job.findJobById(getEntityManager1(), subcontractId); selectedCostComponent.setCost(subcontract.getJobCostingAndPayment().getFinalCost()); selectedCostComponent.setName("Subcontract (" + subcontract.getJobNumber() + ")"); updateCostComponent(); } } public void updateAllTaxes(AjaxBehaviorEvent event) { EntityManager em = getEntityManager1(); if (getCurrentJob().getJobCostingAndPayment().getId() != null) { JobCostingAndPayment jcp = JobCostingAndPayment.findJobCostingAndPaymentById(em, getCurrentJob().getJobCostingAndPayment().getId()); em.refresh(jcp); if (!(jcp.getCashPayments().isEmpty() || getUser().getPrivilege().getCanBeFinancialAdministrator())) { // Reset cash payments getCurrentJob().getJobCostingAndPayment(). setCashPayments(jcp.getCashPayments()); PrimeFacesUtils.addMessage("Permission Denied", "A payment was made on this job so update of this field is not allowed", FacesMessage.SEVERITY_ERROR); setJobCostingAndPaymentDirty(false); } else { updateJobCostingEstimate(); updateTotalCost(); setJobCostingAndPaymentDirty(true); } } else { updateJobCostingEstimate(); updateTotalCost(); setJobCostingAndPaymentDirty(true); } } public String getSubcontractsMessage() { if (getCurrentJob().getId() != null) { if (!getCurrentJob().findSubcontracts(getEntityManager1()).isEmpty()) { return ("{ " + getCurrentJob().getSubcontracts(getEntityManager1()).size() + " subcontract(s) exist(s) that can be added as cost item(s) }"); } else if (!getCurrentJob().findPossibleSubcontracts(getEntityManager1()).isEmpty()) { return ("{ " + getCurrentJob().getPossibleSubcontracts(getEntityManager1()).size() + " possible subcontract(s) exist(s) that can be added as cost item(s) }"); } else { return ""; } } else { return ""; } } public void updateMinimumDepositRequired() { EntityManager em = getEntityManager1(); if (getCurrentJob().getJobCostingAndPayment().getId() != null) { JobCostingAndPayment jcp = JobCostingAndPayment.findJobCostingAndPaymentById(em, getCurrentJob().getJobCostingAndPayment().getId()); em.refresh(jcp); if (!(jcp.getCashPayments().isEmpty() || getUser().getPrivilege().getCanBeFinancialAdministrator())) { // Reset min deposit required getCurrentJob().getJobCostingAndPayment(). setMinDeposit(jcp.getMinDeposit()); // Reset cash payments getCurrentJob().getJobCostingAndPayment(). setCashPayments(jcp.getCashPayments()); PrimeFacesUtils.addMessage("Permission Denied", "A payment was made on this job so update of this field is not allowed", FacesMessage.SEVERITY_ERROR); setJobCostingAndPaymentDirty(false); } else { updateJobCostingEstimate(); setJobCostingAndPaymentDirty(true); } } else { updateJobCostingEstimate(); setJobCostingAndPaymentDirty(true); } } public void updatePurchaseOrderNumber() { EntityManager em = getEntityManager1(); if (getCurrentJob().getJobCostingAndPayment().getId() != null) { JobCostingAndPayment jcp = JobCostingAndPayment.findJobCostingAndPaymentById(em, getCurrentJob().getJobCostingAndPayment().getId()); em.refresh(jcp); if (!(jcp.getCashPayments().isEmpty() || getUser().getPrivilege().getCanBeFinancialAdministrator())) { // Reset PO# getCurrentJob().getJobCostingAndPayment(). setPurchaseOrderNumber(jcp.getPurchaseOrderNumber()); // Reset cash payments getCurrentJob().getJobCostingAndPayment(). setCashPayments(jcp.getCashPayments()); PrimeFacesUtils.addMessage("Permission Denied", "A payment was made on this job so update of this field is not allowed", FacesMessage.SEVERITY_ERROR); setJobCostingAndPaymentDirty(false); } else { setJobCostingAndPaymentDirty(true); } } else { setJobCostingAndPaymentDirty(true); } } public void updateEstimatedCostIncludingTaxes() { updateJobCostingEstimate(); } public void updateMinimumDepositIncludingTaxes() { updateJobCostingEstimate(); } public void updateJobCostingEstimate() { EntityManager em = getEntityManager1(); if (getCurrentJob().getJobCostingAndPayment().getId() != null) { JobCostingAndPayment jcp = JobCostingAndPayment.findJobCostingAndPaymentById(em, getCurrentJob().getJobCostingAndPayment().getId()); em.refresh(jcp); if (!(jcp.getCashPayments().isEmpty() || getUser().getPrivilege().getCanBeFinancialAdministrator())) { // Reset cost estimate getCurrentJob().getJobCostingAndPayment(). setEstimatedCost(jcp.getEstimatedCost()); // Reset cash payments getCurrentJob().getJobCostingAndPayment(). setCashPayments(jcp.getCashPayments()); PrimeFacesUtils.addMessage("Permission Denied", "A payment was made on this job so update of this field is not allowed", FacesMessage.SEVERITY_ERROR); setJobCostingAndPaymentDirty(false); } else { // Update estmated cost and min. deposit // tk may not need to do this here but in the respective get methods if (getCurrentJob().getJobCostingAndPayment().getEstimatedCost() != null) { Double estimatedCostWithTaxes = getCurrentJob().getJobCostingAndPayment().getEstimatedCost() + getCurrentJob().getJobCostingAndPayment().getEstimatedCost() * getCurrentJob().getJobCostingAndPayment().getTax().getValue(); getCurrentJob().getJobCostingAndPayment().setEstimatedCostIncludingTaxes(estimatedCostWithTaxes); setJobCostingAndPaymentDirty(true); } // tk may not need to do this here but in the respective get methods if (getCurrentJob().getJobCostingAndPayment().getMinDeposit() != null) { Double minDepositWithTaxes = getCurrentJob().getJobCostingAndPayment().getMinDeposit() + getCurrentJob().getJobCostingAndPayment().getMinDeposit() * getCurrentJob().getJobCostingAndPayment().getTax().getValue(); getCurrentJob().getJobCostingAndPayment().setMinDepositIncludingTaxes(minDepositWithTaxes); setJobCostingAndPaymentDirty(true); } } } else { setJobCostingAndPaymentDirty(true); } } public void updateTotalDeposit() { EntityManager em = getEntityManager1(); Employee employee = Employee.findEmployeeById(em, getUser().getEmployee().getId()); if (employee != null) { getCurrentJob().getJobCostingAndPayment().setLastPaymentEnteredBy(employee); } updateAmountDue(); setIsDirty(true); } public void update() { setIsDirty(true); } public void updateJobCostingValidity() { if (!validateCurrentJobCosting() && getCurrentJob().getJobCostingAndPayment().getCostingCompleted()) { getCurrentJob().getJobCostingAndPayment().setCostingCompleted(false); getCurrentJob().getJobCostingAndPayment().setCostingApproved(false); displayCommonMessageDialog(null, "Removing the content of a required field has invalidated this job costing", "Invalid Job Costing", "info"); } else { setJobCostingAndPaymentDirty(true); } } public void prepareJobCosting() { if (getCurrentJob().getJobCostingAndPayment().getCostingApproved()) { getCurrentJob().getJobCostingAndPayment().setCostingCompleted(!getCurrentJob().getJobCostingAndPayment().getCostingCompleted()); PrimeFacesUtils.addMessage("Job Costing Already Approved", "The job costing preparation status cannot be changed because it was already approved", FacesMessage.SEVERITY_ERROR); } else if (getCurrentJob().getJobCostingAndPayment().getCostingCompleted()) { getCurrentJob().getJobStatusAndTracking().setDateCostingCompleted(new Date()); getCurrentJob().getJobStatusAndTracking().setCostingDate(new Date()); getCurrentJob().getJobCostingAndPayment().setCostingPreparedBy( getUser().getEmployee()); } else if (!getCurrentJob().getJobCostingAndPayment().getCostingCompleted()) { getCurrentJob().getJobStatusAndTracking().setDateCostingCompleted(null); getCurrentJob().getJobStatusAndTracking().setCostingDate(null); getCurrentJob().getJobCostingAndPayment().setCostingPreparedBy(null); } setJobCostingAndPaymentDirty(true); } /** * Determine if the current user is the department's supervisor. This is * done by determining if the user is the head/active acting head of the * department to which the job was assigned. * * @param job * @return */ public Boolean isUserDepartmentSupervisor(Job job) { EntityManager em = getEntityManager1(); Job foundJob = Job.findJobById(em, job.getId()); if (Department.findDepartmentAssignedToJob(foundJob, em).getHead().getId().longValue() == getUser().getEmployee().getId().longValue()) { return true; } else { return (Department.findDepartmentAssignedToJob(foundJob, em).getActingHead().getId().longValue() == getUser().getEmployee().getId().longValue()) && Department.findDepartmentAssignedToJob(foundJob, em).getActingHeadActive(); } } public void approveJobCosting() { if (canChangeJobCostingApprovalStatus(getCurrentJob())) { if (getCurrentJob().getJobCostingAndPayment().getCostingApproved()) { getCurrentJob().getJobStatusAndTracking().setDateCostingApproved(new Date()); getCurrentJob().getJobCostingAndPayment().setCostingApprovedBy( getUser().getEmployee()); } else { getCurrentJob().getJobStatusAndTracking().setDateCostingApproved(null); getCurrentJob().getJobCostingAndPayment().setCostingApprovedBy(null); } setJobCostingAndPaymentDirty(true); } else { // Reset the costing status getCurrentJob().getJobCostingAndPayment(). setCostingApproved(!getCurrentJob().getJobCostingAndPayment().getCostingApproved()); } } public Boolean canChangeJobCostingApprovalStatus(Job job) { if (!job.getJobCostingAndPayment().getCostingCompleted() || job.getJobCostingAndPayment().getInvoiced()) { PrimeFacesUtils.addMessage("Cannot Change Approval Status", "The job costing approval status for " + job.getJobNumber() + " cannot be changed before the job costing is prepared or if it was already invoiced", FacesMessage.SEVERITY_ERROR); return false; } else if (isUserDepartmentSupervisor(job) || (isJobAssignedToUserDepartment(job) && getUser().getPrivilege().getCanApproveJobCosting())) { return true; } else { PrimeFacesUtils.addMessage("No Permission", "You do not have the permission to change the job costing approval status for " + job.getJobNumber(), FacesMessage.SEVERITY_ERROR); return false; } } public void updatePreferences() { setIsDirty(true); } public void updateCostType() { selectedCostComponent.update(); } public Boolean getAllowCostEdit() { if (selectedCostComponent != null) { if (null == selectedCostComponent.getType()) { return true; } else { switch (selectedCostComponent.getType()) { case "--": return true; default: return false; } } } else { return true; } } public void updateIsCostComponentHeading() { } public void updateIsCostComponentFixedCost() { if (getSelectedCostComponent().getIsFixedCost()) { } } public void updateNewClient() { setIsDirty(true); } public void updateJobNumber() { setIsDirty(true); } public void updateSamplesCollected() { setIsDirty(true); } public void closelJobCostingDialog() { PrimeFaces.current().dialog().closeDynamic(null); } public void closeUnitCostDialog() { // prompt to save modified job before attempting to create new job if (getIsDirty()) { // ask to save displayCommonConfirmationDialog(initDialogActionHandlerId("unitCostDirty"), "This unit cost was modified. Do you wish to save it?", "Unit Cost Not Saved", "info"); } else { PrimeFaces.current().executeScript("PF('unitCostDialog').hide();"); } } public void cancelJobCostingEdit(ActionEvent actionEvent) { setIsDirty(false); PrimeFaces.current().dialog().closeDynamic(null); } public void cancelJobCostingAndPayment(ActionEvent actionEvent) { EntityManager em = getEntityManager1(); // refetch costing data from database if (getCurrentJob() != null) { if (getCurrentJob().getId() != null) { Job job = Job.findJobById(em, getCurrentJob().getId()); getCurrentJob().setJobCostingAndPayment(job.getJobCostingAndPayment()); } } setIsDirty(false); } public void jobCostingDialogReturn() { if (getCurrentJob().getId() != null) { if (isJobCostingAndPaymentDirty()) { if (getCurrentJob().prepareAndSave(getEntityManager1(), getUser()).isSuccess()) { getCurrentJob().getJobStatusAndTracking().setEditStatus(""); PrimeFacesUtils.addMessage("Job Costing and Job Saved", "This job and the costing were saved", FacesMessage.SEVERITY_INFO); } else { PrimeFacesUtils.addMessage("Job Costing and Job NOT Saved", "This job and the costing were NOT saved", FacesMessage.SEVERITY_ERROR); } } } } public void okJobCosting(ActionEvent actionEvent) { try { if (getUser().getEmployee() != null) { getCurrentJob().getJobCostingAndPayment().setFinalCostDoneBy(getUser().getEmployee().getName()); } } catch (Exception e) { System.out.println(e); } PrimeFaces.current().dialog().closeDynamic(null); } public Boolean validateCurrentJobCosting() { try { // check for valid job if (getCurrentJob().getId() == null) { return false; } // check for job report # and description if ((getCurrentJob().getReportNumber() == null) || (getCurrentJob().getReportNumber().trim().equals(""))) { return false; } if (getCurrentJob().getJobDescription().trim().equals("")) { return false; } } catch (Exception e) { System.out.println(e); } return true; } public void saveUnitCost() { EntityManager em = getEntityManager1(); try { // Validate and save objects // Department Department department = Department.findDepartmentByName(em, getCurrentUnitCost().getDepartment().getName()); if (department == null) { setInvalidFormFieldMessage("This unit cost cannot be saved because a valid department was not entered."); return; } else { getCurrentUnitCost().setDepartment(department); } // Department unit DepartmentUnit departmentUnit = DepartmentUnit.findDepartmentUnitByName(em, getCurrentUnitCost().getDepartmentUnit().getName()); if (departmentUnit == null) { getCurrentUnitCost().setDepartmentUnit(DepartmentUnit.getDefaultDepartmentUnit(em, "--")); } else { getCurrentUnitCost().setDepartmentUnit(departmentUnit); } // Laboratory unit Laboratory laboratory = Laboratory.findLaboratoryByName(em, getCurrentUnitCost().getLaboratory().getName()); if (laboratory == null) { getCurrentUnitCost().setLaboratory(Laboratory.getDefaultLaboratory(em, "--")); } else { getCurrentUnitCost().setLaboratory(laboratory); } // Service if (getCurrentUnitCost().getService().trim().equals("")) { setInvalidFormFieldMessage("This unit cost cannot be saved because a valid service was not entered."); return; } // Cost if (getCurrentUnitCost().getCost() <= 0.0) { setInvalidFormFieldMessage("This unit cost cannot be saved because a valid cost was not entered."); return; } // Effective date if (getCurrentUnitCost().getEffectiveDate() == null) { setInvalidFormFieldMessage("This unit cost cannot be saved because a valid effective date was not entered."); return; } // save job to database and check for errors em.getTransaction().begin(); Long id = BusinessEntityUtils.saveBusinessEntity(em, currentUnitCost); if (id == null) { sendErrorEmail("An error occurred while saving this unit cost", "Unit cost save error occurred"); return; } em.getTransaction().commit(); setIsDirty(false); } catch (Exception e) { System.out.println(e); // send error message to developer's email sendErrorEmail("An exception occurred while saving a unit cost!", "\nJMTS User: " + getUser().getUsername() + "\nDate/time: " + new Date() + "\nException detail: " + e); } } public String getCompletedJobCostingEmailMessage(Job job) { String message = ""; DateFormat formatter = new SimpleDateFormat("MMM dd, yyyy"); message = message + "Dear Colleague,<br><br>"; message = message + "The costing for a job with the following details was completed via the <a href='http://boshrmapp:8080/jmts'>Job Management & Tracking System (JMTS)</a>:<br><br>"; message = message + "<span style='font-weight:bold'>Job number: </span>" + job.getJobNumber() + "<br>"; message = message + "<span style='font-weight:bold'>Client: </span>" + job.getClient().getName() + "<br>"; if (!job.getSubContractedDepartment().getName().equals("--")) { message = message + "<span style='font-weight:bold'>Department: </span>" + job.getSubContractedDepartment().getName() + "<br>"; } else { message = message + "<span style='font-weight:bold'>Department: </span>" + job.getDepartment().getName() + "<br>"; } message = message + "<span style='font-weight:bold'>Date submitted: </span>" + formatter.format(job.getJobStatusAndTracking().getDateSubmitted()) + "<br>"; message = message + "<span style='font-weight:bold'>Current assignee: </span>" + BusinessEntityUtils.getPersonFullName(job.getAssignedTo(), Boolean.FALSE) + "<br>"; message = message + "<span style='font-weight:bold'>Task/Sample descriptions: </span>" + job.getJobSampleDescriptions() + "<br><br>"; message = message + "As the department's supervisor/head, you are required to review and approve this costing. An email will be automatically sent to the Finance department after approval.<br><br>"; message = message + "If this job was incorrectly assigned to your department, the department supervisor should contact the person who entered/assigned the job.<br><br>"; message = message + "This email was automatically generated and sent by the <a href='http://boshrmapp:8080/jmts'>JMTS</a>. Please DO NOT reply.<br><br>"; message = message + "Signed<br>"; message = message + "Job Manager"; return message; } public String getApprovedJobCostingEmailMessage(Job job) { String message = ""; DateFormat formatter = new SimpleDateFormat("MMM dd, yyyy"); EntityManager em = getEntityManager1(); message = message + "Dear Colleague,<br><br>"; message = message + "The costing for a job with the following details was approved via the <a href='http://boshrmapp:8080/jmts'>Job Management & Tracking System (JMTS)</a>:<br><br>"; message = message + "<span style='font-weight:bold'>Job number: </span>" + job.getJobNumber() + "<br>"; message = message + "<span style='font-weight:bold'>Client: </span>" + job.getClient().getName() + "<br>"; if (!job.getSubContractedDepartment().getName().equals("--")) { message = message + "<span style='font-weight:bold'>Department: </span>" + job.getSubContractedDepartment().getName() + "<br>"; } else { message = message + "<span style='font-weight:bold'>Department: </span>" + job.getDepartment().getName() + "<br>"; } message = message + "<span style='font-weight:bold'>Date submitted: </span>" + formatter.format(job.getJobStatusAndTracking().getDateSubmitted()) + "<br>"; message = message + "<span style='font-weight:bold'>Department/Unit Head: </span>" + BusinessEntityUtils.getPersonFullName(Department.findDepartmentAssignedToJob(job, em).getHead(), false) + "<br>"; message = message + "<span style='font-weight:bold'>Task/Sample descriptions: </span>" + job.getJobSampleDescriptions() + "<br><br>"; message = message + "If this email was sent to you in error, please contact the department referred to above.<br><br>"; message = message + "This email was automatically generated and sent by the <a href='http://boshrmapp:8080/jmts'>JMTS</a>. Please DO NOT reply.<br><br>"; message = message + "Signed<br>"; message = message + "Job Manager"; return message; } public String getNewJobEmailMessage(Job job) { String message = ""; DateFormat formatter = new SimpleDateFormat("MMM dd, yyyy"); message = message + "Dear Colleague,<br><br>"; message = message + "A job with the following details was assigned to your department via the <a href='http://boshrmapp:8080/jmts'>Job Management & Tracking System (JMTS)</a>:<br><br>"; message = message + "<span style='font-weight:bold'>Job number: </span>" + job.getJobNumber() + "<br>"; message = message + "<span style='font-weight:bold'>Client: </span>" + job.getClient().getName() + "<br>"; if (!job.getSubContractedDepartment().getName().equals("--")) { message = message + "<span style='font-weight:bold'>Department: </span>" + job.getSubContractedDepartment().getName() + "<br>"; } else { message = message + "<span style='font-weight:bold'>Department: </span>" + job.getDepartment().getName() + "<br>"; } message = message + "<span style='font-weight:bold'>Date submitted: </span>" + formatter.format(job.getJobStatusAndTracking().getDateSubmitted()) + "<br>"; message = message + "<span style='font-weight:bold'>Current assignee: </span>" + BusinessEntityUtils.getPersonFullName(job.getAssignedTo(), Boolean.FALSE) + "<br>"; message = message + "<span style='font-weight:bold'>Entered by: </span>" + BusinessEntityUtils.getPersonFullName(job.getJobStatusAndTracking().getEnteredBy(), Boolean.FALSE) + "<br>"; message = message + "<span style='font-weight:bold'>Task/Sample descriptions: </span>" + job.getJobSampleDescriptions() + "<br><br>"; message = message + "If you are the department's supervisor, you should immediately ensure that the job was correctly assigned to your staff member who will see to its completion.<br><br>"; message = message + "If this job was incorrectly assigned to your department, the department supervisor should contact the person who entered/assigned the job.<br><br>"; message = message + "This email was automatically generated and sent by the <a href='http://boshrmapp:8080/jmts'>JMTS</a>. Please DO NOT reply.<br><br>"; message = message + "Signed<br>"; message = message + "Job Manager"; return message; } public String getUpdatedJobEmailMessage(Job job) { String message = ""; DateFormat formatter = new SimpleDateFormat("MMM dd, yyyy"); message = message + "Dear Colleague,<br><br>"; message = message + "A job with the following details was updated by someone outside of your department via the <a href='http://boshrmapp:8080/jmts'>Job Management & Tracking System (JMTS)</a>:<br><br>"; message = message + "<span style='font-weight:bold'>Job number: </span>" + job.getJobNumber() + "<br>"; message = message + "<span style='font-weight:bold'>Client: </span>" + job.getClient().getName() + "<br>"; if (!job.getSubContractedDepartment().getName().equals("--")) { message = message + "<span style='font-weight:bold'>Department: </span>" + job.getSubContractedDepartment().getName() + "<br>"; } else { message = message + "<span style='font-weight:bold'>Department: </span>" + job.getDepartment().getName() + "<br>"; } message = message + "<span style='font-weight:bold'>Date submitted: </span>" + formatter.format(job.getJobStatusAndTracking().getDateSubmitted()) + "<br>"; message = message + "<span style='font-weight:bold'>Current assignee: </span>" + BusinessEntityUtils.getPersonFullName(job.getAssignedTo(), Boolean.FALSE) + "<br>"; message = message + "<span style='font-weight:bold'>Updated by: </span>" + BusinessEntityUtils.getPersonFullName(job.getJobStatusAndTracking().getEditedBy(), Boolean.FALSE) + "<br>"; message = message + "<span style='font-weight:bold'>Task/Sample descriptions: </span>" + job.getJobSampleDescriptions() + "<br><br>"; message = message + "You are being informed of this update so that you may take the requisite action.<br><br>"; message = message + "This email was automatically generated and sent by the <a href='http://boshrmapp:8080/jmts'>JMTS</a>. Please DO NOT reply.<br><br>"; message = message + "Signed<br>"; message = message + "Job Manager"; return message; } /** * Update/create alert for the current job if the job is not completed. * * @param em * @throws java.lang.Exception */ public void updateAlert(EntityManager em) throws Exception { if (getCurrentJob().getJobStatusAndTracking().getCompleted() == null) { em.getTransaction().begin(); Alert alert = Alert.findFirstAlertByOwnerId(em, getCurrentJob().getId()); if (alert == null) { // This seems to be a new job alert = new Alert(getCurrentJob().getId(), new Date(), "Job entered"); em.persist(alert); } else { em.refresh(alert); alert.setActive(true); alert.setDueTime(new Date()); alert.setStatus("Job saved"); } em.getTransaction().commit(); } else if (!getCurrentJob().getJobStatusAndTracking().getCompleted()) { em.getTransaction().begin(); Alert alert = Alert.findFirstAlertByOwnerId(em, getCurrentJob().getId()); if (alert == null) { // This seems to be a new job alert = new Alert(getCurrentJob().getId(), new Date(), "Job saved"); em.persist(alert); } else { em.refresh(alert); alert.setActive(true); alert.setDueTime(new Date()); alert.setStatus("Job saved"); } em.getTransaction().commit(); } } public void sendErrorEmail(String subject, String message) { try { // Send error message to developer's email Utils.postMail(null, null, null, subject, message, "text/plain", getEntityManager1()); } catch (Exception ex) { System.out.println(ex); } } public void deleteCostComponent() { deleteCostComponentByName(selectedCostComponent.getName()); } // Remove this and other code out of JobManager? Put in JobCostingAndPayment or Job? public void deleteCostComponentByName(String componentName) { List<CostComponent> components = getCurrentJob().getJobCostingAndPayment().getAllSortedCostComponents(); int index = 0; for (CostComponent costComponent : components) { if (costComponent.getName().equals(componentName)) { components.remove(index); setJobCostingAndPaymentDirty(true); break; } ++index; } updateFinalCost(); updateAmountDue(); } public void editCostComponent(ActionEvent event) { setEdit(true); } public void createNewCashPayment(ActionEvent event) { if (getCurrentJob().getId() != null) { selectedCashPayment = new CashPayment(); // If there were other payments it is assumed that this is a final payment. // Otherwsie, it is assumed to be a deposit. if (getCurrentJob().getJobCostingAndPayment().getCashPayments().size() > 0) { selectedCashPayment.setPaymentPurpose("Final"); } else { selectedCashPayment.setPaymentPurpose("Deposit"); } PrimeFacesUtils.openDialog(null, "/job/finance/cashPaymentDialog", true, true, true, 350, 500); } else { PrimeFacesUtils.addMessage("Job NOT Saved", "Job must be saved before a new payment can be added", FacesMessage.SEVERITY_WARN); } } public void editCashPayment(ActionEvent event) { PrimeFacesUtils.openDialog(null, "/job/finance/cashPaymentDialog", true, true, true, 350, 500); } public void createNewCostComponent(ActionEvent event) { selectedCostComponent = new CostComponent(); setEdit(false); } public void cancelCashPaymentEdit() { selectedCashPayment.setIsDirty(false); PrimeFaces.current().dialog().closeDynamic(null); } public void cancelCostComponentEdit() { selectedCostComponent.setIsDirty(false); } public void cashPaymentDialogReturn() { if (getCurrentJob().getId() != null) { if (isJobCostingAndPaymentDirty()) { if (getCurrentJob().prepareAndSave(getEntityManager1(), getUser()).isSuccess()) { PrimeFacesUtils.addMessage("Payment and Job Saved", "Payment and the job and the payment were saved", FacesMessage.SEVERITY_INFO); } } } } /** * * @return */ public Boolean getIsJobCompleted() { if (getCurrentJob() != null) { return getCurrentJob().getJobStatusAndTracking().getCompleted(); } else { return false; } } public void okCostingComponent() { if (selectedCostComponent.getId() == null && !getEdit()) { getCurrentJob().getJobCostingAndPayment().getCostComponents().add(selectedCostComponent); } setEdit(false); updateFinalCost(); updateAmountDue(); PrimeFaces.current().executeScript("PF('costingComponentDialog').hide();"); } public void updateFinalCost() { getCurrentJob().getJobCostingAndPayment().setFinalCost(getCurrentJob().getJobCostingAndPayment().getTotalJobCostingsAmount()); setJobCostingAndPaymentDirty(true); } public void updateTotalCost() { updateAmountDue(); } public void updateAmountDue() { setJobCostingAndPaymentDirty(true); } public Boolean getCanApplyTax() { return JobCostingAndPayment.getCanApplyTax(getCurrentJob()) && getCanEditJobCosting(); } public void openJobCostingDialog() { if (getCurrentJob().getId() != null && !getCurrentJob().getIsDirty()) { // Reload cash payments if possible to avoid overwriting them // when saving EntityManager em = getEntityManager1(); JobCostingAndPayment jcp = JobCostingAndPayment.findJobCostingAndPaymentById(em, getCurrentJob().getJobCostingAndPayment().getId()); em.refresh(jcp); getCurrentJob().getJobCostingAndPayment().setCashPayments(jcp.getCashPayments()); PrimeFacesUtils.openDialog(null, "/job/finance/jobCostingDialog", true, true, true, 600, 850); } else { PrimeFacesUtils.addMessage("Job NOT Saved", "Job must be saved before the job costing can be viewed or edited", FacesMessage.SEVERITY_WARN); PrimeFaces.current().executeScript("PF('longProcessDialogVar').hide();"); } } public void editJobCosting() { PrimeFacesUtils.openDialog(null, "jobCostingDialog", true, true, true, 600, 850); } public void okCashPayment() { if (getSelectedCashPayment().getId() == null) { getCurrentJob().getJobCostingAndPayment().getCashPayments().add(selectedCashPayment); } updateFinalCost(); updateAmountDue(); PrimeFaces.current().dialog().closeDynamic(null); } public List<JobCostingAndPayment> completeJobCostingAndPaymentName(String query) { EntityManager em; try { em = getEntityManager1(); List<JobCostingAndPayment> results = JobCostingAndPayment.findAllJobCostingAndPaymentsByDepartmentAndName(em, getUser().getEmployee().getDepartment().getName(), query); return results; } catch (Exception e) { System.out.println(e); return new ArrayList<>(); } } public List<String> completeAccPacClientName(String query) { EntityManager em2; try { em2 = getEntityManager2(); List<AccPacCustomer> clients = AccPacCustomer.findAllByName(em2, query); List<String> suggestions = new ArrayList<>(); for (AccPacCustomer client : clients) { suggestions.add(client.getCustomerName()); } return suggestions; } catch (Exception e) { System.out.println(e); return new ArrayList<>(); } } // tk use the one in ClientManager? public List<AccPacCustomer> completeAccPacClient(String query) { EntityManager em2; try { em2 = getEntityManager2(); return AccPacCustomer.findAllByName(em2, query); } catch (Exception e) { System.out.println(e); return new ArrayList<>(); } } public List<CostCode> getAllCostCodes() { EntityManager em = getEntityManager1(); List<CostCode> codes = CostCode.findAllCostCodes(em); return codes; } public List<Job> getAllSubcontracts() { List<Job> subcontracts = new ArrayList<>(); if (getCurrentJob().getId() != null) { if (!getCurrentJob().findSubcontracts(getEntityManager1()).isEmpty()) { subcontracts.addAll(getCurrentJob().findSubcontracts(getEntityManager1())); } else { subcontracts.addAll(getCurrentJob().findPossibleSubcontracts(getEntityManager1())); } subcontracts.add(0, new Job("-- select a subcontract --")); } else { subcontracts.add(0, new Job("-- none exists --")); } return subcontracts; } private EntityManagerFactory getEMF2() { return EMF2; } public Job getCurrentJob() { return getJobManager().getCurrentJob(); } @Override public void setIsDirty(Boolean dirty) { getCurrentJob().setIsDirty(dirty); } @Override public Boolean getIsDirty() { return getCurrentJob().getIsDirty(); } public void setJobCostingAndPaymentDirty(Boolean dirty) { getCurrentJob().getJobCostingAndPayment().setIsDirty(dirty); if (dirty) { getCurrentJob().getJobStatusAndTracking().setEditStatus("(edited)"); } else { getCurrentJob().getJobStatusAndTracking().setEditStatus(""); } } public void setJobCostingAndPaymentDirty(Job job, Boolean dirty) { job.getJobCostingAndPayment().setIsDirty(dirty); if (dirty) { job.getJobStatusAndTracking().setEditStatus("(edited)"); } else { job.getJobStatusAndTracking().setEditStatus(""); } } public Boolean isJobCostingAndPaymentDirty() { return getCurrentJob().getJobCostingAndPayment().getIsDirty(); } public void updateCurrentUnitCostDepartment() { EntityManager em; try { em = getEntityManager1(); if (currentUnitCost.getDepartment().getName() != null) { Department department = Department.findDepartmentByName(em, currentUnitCost.getDepartment().getName()); if (department != null) { currentUnitCost.setDepartment(department); setIsDirty(true); } } } catch (Exception e) { System.out.println(e); } } public void updateCurrentUnitCostDepartmentUnit() { EntityManager em; try { em = getEntityManager1(); if (currentUnitCost.getDepartmentUnit().getName() != null) { DepartmentUnit departmentUnit = DepartmentUnit.findDepartmentUnitByName(em, currentUnitCost.getDepartmentUnit().getName()); if (departmentUnit != null) { currentUnitCost.setDepartmentUnit(departmentUnit); setIsDirty(true); } } } catch (Exception e) { System.out.println(e); } } public void updateCurrentUnitCostDepartmentLab() { EntityManager em; try { em = getEntityManager1(); if (currentUnitCost.getLaboratory().getName() != null) { Laboratory laboratory = Laboratory.findLaboratoryByName(em, currentUnitCost.getLaboratory().getName()); if (laboratory != null) { currentUnitCost.setLaboratory(laboratory); setIsDirty(true); } } } catch (Exception e) { System.out.println(e); } } public void updateUnitCostDepartment() { EntityManager em; try { em = getEntityManager1(); if (unitCostDepartment.getName() != null) { Department department = Department.findDepartmentByName(em, unitCostDepartment.getName()); if (department != null) { unitCostDepartment = department; //doUnitCostSearch(); } } } catch (Exception e) { System.out.println(e); } } public void updateJobCostDepartment() { EntityManager em; try { em = getEntityManager1(); if (jobCostDepartment.getName() != null) { Department department = Department.findDepartmentByName(em, jobCostDepartment.getName()); if (department != null) { jobCostDepartment = department; //doUnitCostSearch(); } } } catch (Exception e) { System.out.println(e); } } public void updateAccPacClient() { setShowPrepayments(false); filteredAccPacCustomerDocuments = new ArrayList<>(); try { if (getCurrentJob() != null) { if (!getCurrentJob().getClient().getName().equals("")) { accPacCustomer.setCustomerName(getCurrentJob().getClient().getName()); } else { accPacCustomer.setCustomerName("?"); } updateCreditStatus(null); } } catch (Exception e) { System.out.println(e); } } public void updateAccPacCustomer(SelectEvent event) { if (accPacCustomer != null) { try { EntityManager em = getEntityManager2(); accPacCustomer = AccPacCustomer.findByName(em, accPacCustomer.getCustomerName()); if (accPacCustomer == null) { accPacCustomer = new AccPacCustomer(); accPacCustomer.setCustomerName(""); } // set the found client name to the present job client if (accPacCustomer.getCustomerName() != null) { updateCreditStatus(null); } } catch (Exception e) { System.out.println(e); accPacCustomer = new AccPacCustomer(); accPacCustomer.setCustomerName(""); } } } public Integer getNumberOfFilteredAccPacCustomerDocuments() { if (filteredAccPacCustomerDocuments != null) { return filteredAccPacCustomerDocuments.size(); } return 0; } public Boolean getFilteredDocumentAvailable() { if (filteredAccPacCustomerDocuments != null) { return !filteredAccPacCustomerDocuments.isEmpty(); } else { return false; } } public void updateCreditStatusSearch() { accPacCustomer.setCustomerName(getCurrentJob().getClient().getName()); updateCreditStatus(null); } public void updateCreditStatus(SelectEvent event) { EntityManager em = getEntityManager2(); accPacCustomer = AccPacCustomer.findByName(em, accPacCustomer.getCustomerName().trim()); if (accPacCustomer != null) { if (getShowPrepayments()) { filteredAccPacCustomerDocuments = AccPacDocument.findAccPacInvoicesDueByCustomerId(em, accPacCustomer.getIdCust(), true); } else { filteredAccPacCustomerDocuments = AccPacDocument.findAccPacInvoicesDueByCustomerId(em, accPacCustomer.getIdCust(), false); } } else { createNewAccPacCustomer(); } } public void updateCreditStatus() { updateCreditStatus(null); } public void createNewAccPacCustomer() { if (accPacCustomer != null) { accPacCustomer = new AccPacCustomer(accPacCustomer.getCustomerName()); } else { accPacCustomer = new AccPacCustomer(null); } accPacCustomer.setIdCust(null); filteredAccPacCustomerDocuments = new ArrayList<>(); } public String getAccPacCustomerID() { if (accPacCustomer.getIdCust() == null) { return ""; } else { return accPacCustomer.getIdCust(); } } public String getAccPacCustomerName() { if (accPacCustomer.getCustomerName() == null) { return "{Not found}"; } else { return accPacCustomer.getCustomerName(); } } public String getCustomerType() { if (accPacCustomer.getIDACCTSET().equals("TRADE") && accPacCustomer.getCreditLimit().doubleValue() > 0.0) { return "CREDIT"; } else { return "REGULAR"; } } public AccPacCustomer getAccPacCustomer() { return accPacCustomer; } public void setAccPacCustomer(AccPacCustomer accPacCustomer) { this.accPacCustomer = accPacCustomer; } public void updateCostingComponents() { if (selectedJobCostingTemplate != null) { EntityManager em = getEntityManager1(); JobCostingAndPayment jcp = JobCostingAndPayment.findJobCostingAndPaymentByDepartmentAndName(em, getUser().getEmployee().getDepartment().getName(), selectedJobCostingTemplate); if (jcp != null) { getCurrentJob().getJobCostingAndPayment().getCostComponents().clear(); getCurrentJob().getJobCostingAndPayment().setCostComponents(copyCostComponents(jcp.getCostComponents())); setJobCostingAndPaymentDirty(true); } else { // Nothing yet } selectedJobCostingTemplate = null; } } public void removeCurrentJobCostingComponents(EntityManager em) { if (!getCurrentJob().getJobCostingAndPayment().getCostComponents().isEmpty()) { em.getTransaction().begin(); for (CostComponent costComponent : getCurrentJob().getJobCostingAndPayment().getCostComponents()) { if (costComponent.getId() != null) { costComponent = em.find(CostComponent.class, costComponent.getId()); em.remove(costComponent); } } getCurrentJob().getJobCostingAndPayment().getCostComponents().clear(); BusinessEntityUtils.saveBusinessEntity(em, getCurrentJob().getJobCostingAndPayment()); em.getTransaction().commit(); } } /* * Takes a list of job costings enties an set their ids and component ids * to null which will result in new job costings being created when * the job costins are commited to the database */ public List<JobCosting> copyJobCostings(List<JobCosting> srcCostings) { ArrayList<JobCosting> newJobCostings = new ArrayList<>(); for (JobCosting jobCosting : srcCostings) { JobCosting newJobCosting = new JobCosting(jobCosting); for (CostComponent costComponent : jobCosting.getCostComponents()) { CostComponent newCostComponent = new CostComponent(costComponent); newJobCosting.getCostComponents().add(newCostComponent); } newJobCostings.add(newJobCosting); } return newJobCostings; } public List<CostComponent> copyCostComponents(List<CostComponent> srcCostComponents) { ArrayList<CostComponent> newCostComponents = new ArrayList<>(); for (CostComponent costComponent : srcCostComponents) { CostComponent newCostComponent = new CostComponent(costComponent); newCostComponents.add(newCostComponent); } return newCostComponents; } // public Date getCurrentDate() { // return new Date(); // } public Long saveCashPayment(EntityManager em, CashPayment cashPayment) { return BusinessEntityUtils.saveBusinessEntity(em, cashPayment); } public List<CashPayment> getCashPaymentsByJobId(EntityManager em, Long jobId) { try { List<CashPayment> cashPayments = em.createQuery("SELECT c FROM CashPayment c " + "WHERE c.jobId " + "= '" + jobId + "'", CashPayment.class).getResultList(); return cashPayments; } catch (Exception e) { System.out.println(e); return null; } } public void deleteCashPayment() { List<CashPayment> payments = getCurrentJob().getJobCostingAndPayment().getCashPayments(); for (CashPayment payment : payments) { if (payment.equals(selectedCashPayment)) { payments.remove(selectedCashPayment); break; } } updateFinalCost(); updateAmountDue(); // Do job save if possible... if (getCurrentJob().getId() != null && getCurrentJob().prepareAndSave(getEntityManager1(), getUser()).isSuccess()) { PrimeFacesUtils.addMessage("Job Saved", "The payment was deleted and the job was saved", FacesMessage.SEVERITY_INFO); } else { setJobCostingAndPaymentDirty(true); PrimeFacesUtils.addMessage("Job NOT Saved", "The payment was deleted but the job was not saved", FacesMessage.SEVERITY_WARN); } PrimeFaces.current().dialog().closeDynamic(null); } public void checkForSubcontracts(ActionEvent event) { //PrimeFacesUtils.openDialog(null, "/job/finance/cashPaymentDeleteConfirmDialog", true, true, true, 110, 375); } public void openCashPaymentDeleteConfirmDialog(ActionEvent event) { PrimeFacesUtils.openDialog(null, "/job/finance/cashPaymentDeleteConfirmDialog", true, true, true, 110, 375); } public void closeJCashPaymentDeleteConfirmDialog() { PrimeFaces.current().dialog().closeDynamic(null); } public void openJobPricingsDialog() { PrimeFacesUtils.openDialog(null, "jobPricings", true, true, true, 600, 800); } public void openJobCostingsDialog() { PrimeFacesUtils.openDialog(null, "jobCostings", true, true, true, 600, 800); } public void doJobCostSearch() { System.out.println("To be implemented"); } public void createNewUnitCost() { currentUnitCost = new UnitCost(); PrimeFaces.current().ajax().update("unitCostForm"); PrimeFaces.current().executeScript("PF('unitCostDialog').show();"); } public void editUnitCost() { } @Override public void handleDialogOkButtonClick() { } @Override public void handleDialogYesButtonClick() { if (dialogActionHandlerId.equals("unitCostDirty")) { saveUnitCost(); PrimeFaces.current().executeScript("PF('unitCostDialog').hide();"); } } @Override public void handleDialogNoButtonClick() { if (dialogActionHandlerId.equals("unitCostDirty")) { setIsDirty(false); PrimeFaces.current().executeScript("PF('unitCostDialog').hide();"); } } @Override public DialogActionHandler initDialogActionHandlerId(String id) { dialogActionHandlerId = id; return this; } @Override public String getDialogActionHandlerId() { return dialogActionHandlerId; } @Override public void handleDialogCancelButtonClick() { } public void onJobCostingsTableCellEdit(CellEditEvent event) { System.out.println("Job number of costing: " + getJobsWithCostings().get(event.getRowIndex()).getJobNumber()); } /** * This is to be implemented further * * @return */ public Boolean getDisableSubContracting() { try { if (getCurrentJob().getIsSubContract() || getCurrentJob().getIsToBeCopied()) { return false; } else { return getCurrentJob().getId() == null; } } catch (Exception e) { System.out.println(e); } return false; } public List<String> getDepartmentSupervisorsEmailAddresses(Department department) { List<String> emails = new ArrayList<>(); emails.add(getEmployeeDefaultEmailAdress(department.getHead())); // Get the email of the acting head of he/she is currently acting if (department.getActingHeadActive()) { emails.add(getEmployeeDefaultEmailAdress(department.getActingHead())); } return emails; } public String getEmployeeDefaultEmailAdress(Employee employee) { String address = ""; // Get email1 which is treated as the employee's company email address if (!employee.getInternet().getEmail1().trim().equals("")) { address = employee.getInternet().getEmail1(); } else { // Get and set default email using company domain EntityManager em = getEntityManager1(); String listAsString = (String) SystemOption.getOptionValueObject(em, "domainNames"); String domainNames[] = listAsString.split(";"); JobManagerUser user1 = JobManagerUser.findActiveJobManagerUserByEmployeeId(em, employee.getId()); // Build email address if (user1 != null) { address = user1.getUsername(); if (domainNames.length > 0) { address = address + "@" + domainNames[0]; } } } return address; } public Boolean isCurrentJobNew() { return (getCurrentJob().getId() == null); } public Department getDepartmentBySystemOptionDeptId(String option) { EntityManager em = getEntityManager1(); Long id = (Long) SystemOption.getOptionValueObject(em, option); Department department = Department.findDepartmentById(em, id); em.refresh(department); if (department != null) { return department; } else { return new Department(""); } } public Boolean getIsMemberOfAccountsDept() { return getUser().getEmployee().isMemberOf(getDepartmentBySystemOptionDeptId("accountsDepartmentId")); } public Boolean getIsMemberOfCustomerServiceDept() { return getUser().getEmployee().isMemberOf(getDepartmentBySystemOptionDeptId("customerServiceDeptId")); } /** * Return discount types. NB: Discount types to be obtained from System * Options in the future * * @param query * @return */ public List<String> completeDiscountType(String query) { String discountTypes[] = {"Currency", "Percentage"}; List<String> matchedDiscountTypes = new ArrayList<>(); for (String discountType : discountTypes) { if (discountType.contains(query)) { matchedDiscountTypes.add(discountType); } } return matchedDiscountTypes; } }
src/main/java/jm/com/dpbennett/jmts/managers/JobFinanceManager.java
/* Job Management & Tracking System (JMTS) Copyright (C) 2017 D P Bennett & Associates Limited This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. Email: info@dpbennett.com.jm */ package jm.com.dpbennett.jmts.managers; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.Serializable; import java.math.BigDecimal; import java.sql.Connection; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.event.ActionEvent; import javax.faces.event.AjaxBehaviorEvent; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceUnit; import jm.com.dpbennett.business.entity.AccPacCustomer; import jm.com.dpbennett.business.entity.AccPacDocument; import jm.com.dpbennett.business.entity.AccountingCode; import jm.com.dpbennett.business.entity.Alert; import jm.com.dpbennett.business.entity.CashPayment; import jm.com.dpbennett.business.entity.Client; import jm.com.dpbennett.business.entity.CostCode; import jm.com.dpbennett.business.entity.CostComponent; import jm.com.dpbennett.business.entity.Department; import jm.com.dpbennett.business.entity.DepartmentUnit; import jm.com.dpbennett.business.entity.Discount; import jm.com.dpbennett.business.entity.Employee; import jm.com.dpbennett.business.entity.Job; import jm.com.dpbennett.business.entity.JobCosting; import jm.com.dpbennett.business.entity.JobCostingAndPayment; import jm.com.dpbennett.business.entity.JobManagerUser; import jm.com.dpbennett.business.entity.Laboratory; import jm.com.dpbennett.business.entity.Preference; import jm.com.dpbennett.business.entity.Service; import jm.com.dpbennett.business.entity.SystemOption; import jm.com.dpbennett.business.entity.Tax; import jm.com.dpbennett.business.entity.UnitCost; import jm.com.dpbennett.business.entity.management.MessageManagement; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import org.primefaces.event.CellEditEvent; import org.primefaces.event.SelectEvent; import org.primefaces.model.DefaultStreamedContent; import org.primefaces.model.StreamedContent; import jm.com.dpbennett.business.entity.management.BusinessEntityManagement; import jm.com.dpbennett.business.entity.utils.BusinessEntityUtils; import jm.com.dpbennett.wal.managers.HumanResourceManager; import jm.com.dpbennett.wal.utils.BeanUtils; import jm.com.dpbennett.wal.utils.DialogActionHandler; import jm.com.dpbennett.wal.utils.FinancialUtils; import jm.com.dpbennett.wal.utils.Utils; import jm.com.dpbennett.wal.utils.MainTabView; import jm.com.dpbennett.wal.utils.PrimeFacesUtils; import jm.com.dpbennett.wal.utils.ReportUtils; import net.sf.jasperreports.engine.JasperCompileManager; import net.sf.jasperreports.engine.JasperReport; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFDataFormat; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.primefaces.PrimeFaces; import org.primefaces.component.selectonemenu.SelectOneMenu; /** * This class handles financial matters pertaining to a job. * * @author Desmond P. Bennett (info@dpbenentt.com.jm) */ public class JobFinanceManager implements Serializable, BusinessEntityManagement, DialogActionHandler, MessageManagement { @PersistenceUnit(unitName = "JMTSPU") private EntityManagerFactory EMF1; @PersistenceUnit(unitName = "AccPacPU") private EntityManagerFactory EMF2; private CashPayment selectedCashPayment; private StreamedContent jobCostingFile; private Integer longProcessProgress; private AccPacCustomer accPacCustomer; private List<AccPacDocument> filteredAccPacCustomerDocuments; private Boolean useAccPacCustomerList; private CostComponent selectedCostComponent; private JobCostingAndPayment selectedJobCostingAndPayment; private String selectedJobCostingTemplate; private Department unitCostDepartment; private UnitCost currentUnitCost; private List<UnitCost> unitCosts; private String dialogActionHandlerId; private List<Job> jobsWithCostings; private Job currentJobWithCosting; private Department jobCostDepartment; private Boolean showPrepayments; private String invalidFormFieldMessage; private String dialogMessage; private String dialogMessageHeader; private String dialogMessageSeverity; private Boolean dialogRenderOkButton; private Boolean dialogRenderYesButton; private Boolean dialogRenderNoButton; private Boolean dialogRenderCancelButton; private DialogActionHandler dialogActionHandler; private Boolean enableOnlyPaymentEditing; private JobManager jobManager; private JobContractManager jobContractManager; private Boolean edit; private String fileDownloadErrorMessage; private MainTabView mainTabView; private JobManagerUser user; /** * Creates a new instance of the JobFinanceManager class. */ public JobFinanceManager() { init(); } /** * Attempts to approve the selected job costing(s). * @see JobFinanceManager#canChangeJobCostingApprovalStatus(jm.com.dpbennett.business.entity.Job) */ public void approveSelectedJobCostings() { int numCostingsCApproved = 0; if (getJobManager().getSelectedJobs().length > 0) { EntityManager em = getEntityManager1(); for (Job job : getJobManager().getSelectedJobs()) { if (!job.getJobCostingAndPayment().getCostingApproved()) { if (canChangeJobCostingApprovalStatus(job)) { numCostingsCApproved++; job.getJobCostingAndPayment().setCostingApproved(true); job.getJobStatusAndTracking().setDateCostingApproved(new Date()); job.getJobCostingAndPayment().setCostingApprovedBy( getUser().getEmployee()); job.getJobCostingAndPayment().setIsDirty(true); job.save(em); } else { return; } } else { PrimeFacesUtils.addMessage("Aready Approved", "The job costing for " + job.getJobNumber() + " was already approved", FacesMessage.SEVERITY_WARN); } } PrimeFacesUtils.addMessage("Job Costing(s) Approved", "" + numCostingsCApproved + " job costing(s) approved", FacesMessage.SEVERITY_INFO); } else { PrimeFacesUtils.addMessage("No Selection", "No job costing was selected", FacesMessage.SEVERITY_WARN); } } /** * Attempts to create an invoice for the job costing of the specified job. * @see JobFinanceManager#canChangeJobCostingApprovalStatus(jm.com.dpbennett.business.entity.Job) * @param job * @param invoice * @return */ public Boolean invoiceJobCosting(Job job, Boolean invoice) { prepareToInvoiceJobCosting(job); if (canInvoiceJobCosting(job)) { if (invoice) { job.getJobCostingAndPayment().setInvoiced(invoice); job.getJobStatusAndTracking().setDateCostingInvoiced(new Date()); job.getJobCostingAndPayment().setCostingInvoicedBy(getUser().getEmployee()); } else { job.getJobCostingAndPayment().setInvoiced(invoice); job.getJobStatusAndTracking().setDateCostingInvoiced(null); job.getJobCostingAndPayment().setCostingInvoicedBy(null); } setJobCostingAndPaymentDirty(job, true); return true; } else { // Reset invoiced status job.getJobCostingAndPayment().setInvoiced(!invoice); return false; } } /** * Attempts to create invoices for job costings of the selected jobs. */ public void invoiceSelectedJobCostings() { int numInvoicesCreated = 0; try { if (getJobManager().getSelectedJobs().length > 0) { EntityManager em = getEntityManager1(); for (Job job : getJobManager().getSelectedJobs()) { if (!job.getJobCostingAndPayment().getInvoiced()) { if (invoiceJobCosting(job, true)) { job.save(em); numInvoicesCreated++; } else { return; } } else { PrimeFacesUtils.addMessage("Aready Invoiced", "The job costing for " + job.getJobNumber() + " was already invoiced", FacesMessage.SEVERITY_WARN); return; } } PrimeFacesUtils.addMessage("Invoice(s) Created", "" + numInvoicesCreated + " invoice(s) created", FacesMessage.SEVERITY_INFO); } else { PrimeFacesUtils.addMessage("No Selection", "No job costing was selected", FacesMessage.SEVERITY_WARN); } } catch (Exception e) { System.out.println("Error occurred while invoicing: " + e); PrimeFacesUtils.addMessage("Invoicing Error", "An error occurred while creating one or more invoices. " + "Please check that all required information such as a client Id is provided.", FacesMessage.SEVERITY_ERROR); } } public Double getTotalTax(Job job) { return job.getJobCostingAndPayment().getTotalTax(); } public Double getTotalDiscount(Job job) { return job.getJobCostingAndPayment().getTotalDiscount(); } public Tax getTax(Job job) { Tax tax = job.getJobCostingAndPayment().getTax(); // Handle the case where the tax is not set if (tax.getId() == null) { if (job.getJobCostingAndPayment().getPercentageGCT() != null) { // Find and use tax object Tax tax2 = Tax.findByValue(getEntityManager1(), Double.parseDouble(job.getJobCostingAndPayment().getPercentageGCT())); if (tax2 != null) { tax = tax2; job.getJobCostingAndPayment().setTax(tax2); } else { tax = Tax.findDefault(getEntityManager1(), "0.0"); job.getJobCostingAndPayment().setTax(tax); } } else { tax = Tax.findDefault(getEntityManager1(), "0.0"); job.getJobCostingAndPayment().setTax(tax); } } return tax; } public Tax getTax() { return getTax(getCurrentJob()); } public void setTax(Tax tax) { getCurrentJob().getJobCostingAndPayment().setTax(tax); } public Discount getDiscount() { return getDiscount(getCurrentJob()); } public Discount getDiscount(Job job) { Discount discount = job.getJobCostingAndPayment().getDiscount(); // Handle the case where the discount object is not set. if (discount.getId() == null) { discount = Discount.findByValueAndType( getEntityManager1(), job.getJobCostingAndPayment().getDiscountValue(), job.getJobCostingAndPayment().getDiscountType()); if (discount == null) { discount = Discount.findDefault( getEntityManager1(), job.getJobCostingAndPayment().getDiscountValue().toString(), job.getJobCostingAndPayment().getDiscountValue(), job.getJobCostingAndPayment().getDiscountType()); job.getJobCostingAndPayment().setDiscount(discount); } else { job.getJobCostingAndPayment().setDiscount(discount); } } return discount; } public void setDiscount(Discount discount) { getCurrentJob().getJobCostingAndPayment().setDiscount(discount); } public List<Tax> completeTax(String query) { EntityManager em; try { em = getEntityManager1(); List<Tax> taxes = Tax.findActiveTaxesByNameAndDescription(em, query); return taxes; } catch (Exception e) { return new ArrayList<>(); } } public List<Discount> completeDiscount(String query) { EntityManager em; try { em = getEntityManager1(); List<Discount> discounts = Discount.findActiveDiscountsByNameAndDescription(em, query); return discounts; } catch (Exception e) { return new ArrayList<>(); } } /** * Returns the discount type that can be applied to a payment/amount * * @return */ public List getDiscountTypes() { return FinancialUtils.getDiscountTypes(); } public List getCostTypeList() { return FinancialUtils.getCostTypeList(); } public List getPaymentTypes() { return FinancialUtils.getPaymentTypes(); } public List getPaymentPurposes() { return FinancialUtils.getPaymentPurposes(); } public void closeDialog() { PrimeFacesUtils.closeDialog(null); } public JobCostingAndPayment getSelectedJobCostingAndPayment() { return selectedJobCostingAndPayment; } public void setSelectedJobCostingAndPayment(JobCostingAndPayment selectedJobCostingAndPayment) { this.selectedJobCostingAndPayment = selectedJobCostingAndPayment; } public void cancelDialogEdit(ActionEvent actionEvent) { PrimeFaces.current().dialog().closeDynamic(null); } public MainTabView getMainTabView() { return mainTabView; } public void setMainTabView(MainTabView mainTabView) { this.mainTabView = mainTabView; } public StreamedContent getInvoicesFile() { try { ByteArrayInputStream stream; stream = getInvoicesFileInputStream( new File(getClass().getClassLoader(). getResource("/reports/" + (String) SystemOption.getOptionValueObject(getEntityManager1(), "AccpacInvoicesFileTemplateName")).getFile())); setLongProcessProgress(100); return new DefaultStreamedContent(stream, "application/xlsx", "Invoices-" + BusinessEntityUtils.getDateInMediumDateAndTimeFormat(new Date()) + "-" + fileDownloadErrorMessage + ".xlsx"); } catch (Exception ex) { System.out.println(ex); } return null; } public ByteArrayInputStream getInvoicesFileInputStream( File file) { try { FileInputStream inp = new FileInputStream(file); int invoiceRow = 1; int invoiceCol; int invoiceDetailsRow = 1; int invoiceDetailsCol; int invoiceOptionalFieldsRow = 1; int invoiceOptionalFieldsCol; fileDownloadErrorMessage = ""; XSSFWorkbook wb = new XSSFWorkbook(inp); XSSFCellStyle stringCellStyle = wb.createCellStyle(); XSSFCellStyle integerCellStyle = wb.createCellStyle(); XSSFCellStyle doubleCellStyle = wb.createCellStyle(); XSSFDataFormat doubleFormat = wb.createDataFormat(); doubleCellStyle.setDataFormat(doubleFormat.getFormat("#,##0.00")); XSSFCellStyle dateCellStyle = wb.createCellStyle(); CreationHelper createHelper = wb.getCreationHelper(); // dateCellStyle.setDataFormat( // createHelper.createDataFormat().getFormat("m/d/yyyy")); dateCellStyle.setDataFormat( createHelper.createDataFormat().getFormat("M/D/YYYY")); // Output stream for modified Excel file ByteArrayOutputStream out = new ByteArrayOutputStream(); // Get sheets XSSFSheet invoices = wb.getSheet("Invoices"); XSSFSheet invoiceDetails = wb.getSheet("Invoice_Details"); XSSFSheet invoiceOptionalFields = wb.getSheet("Invoice_Optional_Fields"); // Get report data Job reportData[] = getJobManager().getSelectedJobs(); for (Job job : reportData) { // Export only if costing was invoiced if (job.getJobCostingAndPayment().getInvoiced()) { invoiceCol = 0; invoiceDetailsCol = 0; invoiceOptionalFieldsCol = 0; prepareToInvoiceJobCosting(job); // Fill out the Invoices sheet // CNTBTCH (batch number) ReportUtils.setExcelCellValue(wb, invoices, invoiceRow, invoiceCol++, 0, "java.lang.Integer", integerCellStyle); // CNTITEM (Item number) ReportUtils.setExcelCellValue(wb, invoices, invoiceRow, invoiceCol++, invoiceRow, "java.lang.Integer", integerCellStyle); // IDCUST (Customer Id) ReportUtils.setExcelCellValue(wb, invoices, invoiceRow, invoiceCol++, job.getClient().getFinancialAccount().getIdCust(), "java.lang.String", stringCellStyle); // IDINVC (Invoice No./Id) //ReportUtils.setExcelCellValue(wb, invoices, invoiceRow, invoiceCol++, // "JMTS" + job.getDepartmentAssignedToJob().getCode() // + job.getYearReceived() + "" // + BusinessEntityUtils.getFourDigitString(job.getJobSequenceNumber()), // "java.lang.String", stringCellStyle); // TEXTTRX ReportUtils.setExcelCellValue(wb, invoices, invoiceRow, invoiceCol++, 1, "java.lang.Integer", integerCellStyle); // IDTRX ReportUtils.setExcelCellValue(wb, invoices, invoiceRow, invoiceCol++, 11, "java.lang.Integer", integerCellStyle); // ORDRNBR ReportUtils.setExcelCellValue(wb, invoices, invoiceRow, invoiceCol++, "", "java.lang.String", stringCellStyle); // CUSTPO ReportUtils.setExcelCellValue(wb, invoices, invoiceRow, invoiceCol++, job.getJobCostingAndPayment().getPurchaseOrderNumber(), "java.lang.String", stringCellStyle); // INVCDESC ReportUtils.setExcelCellValue(wb, invoices, invoiceRow, invoiceCol++, job.getInstructions(), "java.lang.String", stringCellStyle); // DATEINVC ReportUtils.setExcelCellValue(wb, invoices, invoiceRow, invoiceCol++, job.getJobStatusAndTracking().getDateCostingInvoiced(), "java.util.Date", dateCellStyle); // INVCTYPE ReportUtils.setExcelCellValue(wb, invoices, invoiceRow, invoiceCol++, 1, // tk org. 2 "java.lang.Integer", integerCellStyle); // Fill out Invoice Details sheet // Add an item for each cost component // CNTBTCH (batch number) int index = 0; for (CostComponent costComponent : job.getJobCostingAndPayment().getAllSortedCostComponents()) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, 0, // CNTBTCH "java.lang.Integer", integerCellStyle); } // Add Tax row if any if (getTax(job).getTaxValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, 0, // CNTBTCH "java.lang.Integer", integerCellStyle); } // Add Discount row if any if (getDiscount(job).getDiscountValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, 0, // CNTBTCH "java.lang.Integer", integerCellStyle); } // CNTITEM (Item/Invoice number/index) index = 0; invoiceDetailsCol++; for (CostComponent costComponent : job.getJobCostingAndPayment().getAllSortedCostComponents()) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, invoiceRow, // CNTITEM "java.lang.Integer", integerCellStyle); } // Add Tax row if any if (getTax(job).getTaxValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, invoiceRow, // CNTITEM "java.lang.Integer", integerCellStyle); } // Add Discount row if any if (getDiscount(job).getDiscountValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, invoiceRow, // CNTITEM "java.lang.Integer", integerCellStyle); } // CNTLINE index = 0; invoiceDetailsCol++; for (CostComponent costComponent : job.getJobCostingAndPayment().getAllSortedCostComponents()) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, index, // CNTLINE "java.lang.Integer", integerCellStyle); } // Add Tax row if any if (getTax(job).getTaxValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, index, // CNTLINE "java.lang.Integer", integerCellStyle); } // Add Discount row if any if (getDiscount(job).getDiscountValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, index, // CNTLINE "java.lang.Integer", integerCellStyle); } // IDITEM index = 0; invoiceDetailsCol++; for (CostComponent costComponent : job.getJobCostingAndPayment().getAllSortedCostComponents()) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, getRevenueCodeAbbreviation(job), // IDITEM "java.lang.String", stringCellStyle); } // Add Tax row if any if (getTax(job).getTaxValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, getTaxCodeAbbreviation(job), // IDITEM "java.lang.String", stringCellStyle); } // Add Discount row if any if (getDiscount(job).getDiscountValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, getDiscountCodeAbbreviation(job), // IDITEM "java.lang.String", stringCellStyle); } // IDDIST index = 0; invoiceDetailsCol++; for (CostComponent costComponent : job.getJobCostingAndPayment().getAllSortedCostComponents()) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, getRevenueCodeAbbreviation(job), // IDDIST "java.lang.String", stringCellStyle); } // Add Tax row if any if (getTax(job).getTaxValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, getTaxCodeAbbreviation(job), // IDDIST "java.lang.String", stringCellStyle); } // Add Discount row if any if (getDiscount(job).getDiscountValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, getDiscountCodeAbbreviation(job), // IDDIST "java.lang.String", stringCellStyle); } // TEXTDESC index = 0; invoiceDetailsCol++; for (CostComponent costComponent : job.getJobCostingAndPayment().getAllSortedCostComponents()) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, costComponent.getName(), // TEXTDESC "java.lang.String", stringCellStyle); } // Add Tax row if any if (getTax(job).getTaxValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, job.getJobCostingAndPayment().getTax().getDescription(), // TEXTDESC "java.lang.String", stringCellStyle); } // Add Discount row if any if (getDiscount(job).getDiscountValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, job.getJobCostingAndPayment().getDiscount().getDescription(), // TEXTDESC "java.lang.String", stringCellStyle); } // UNITMEAS index = 0; invoiceDetailsCol++; for (CostComponent costComponent : job.getJobCostingAndPayment().getAllSortedCostComponents()) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, "EACH", // UNITMEAS "java.lang.String", stringCellStyle); } // Add Tax row if any if (getTax(job).getTaxValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, "EACH", // UNITMEAS "java.lang.String", stringCellStyle); } // Add Discount row if any if (getDiscount(job).getDiscountValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, "EACH", // UNITMEAS "java.lang.String", stringCellStyle); } // QTYINVC index = 0; invoiceDetailsCol++; for (CostComponent costComponent : job.getJobCostingAndPayment().getAllSortedCostComponents()) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, costComponent.getHoursOrQuantity().intValue(), // UNITMEAS "java.lang.Integer", integerCellStyle); } // Add Tax row if any if (getTax(job).getTaxValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, 1, // QTYINVC "java.lang.Integer", integerCellStyle); } // Add Discount row if any if (getDiscount(job).getDiscountValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, 1, // QTYINVC "java.lang.Integer", integerCellStyle); } // AMTPRIC index = 0; invoiceDetailsCol++; for (CostComponent costComponent : job.getJobCostingAndPayment().getAllSortedCostComponents()) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, costComponent.getRate(), // AMTPRIC "java.lang.Double", doubleCellStyle); } // Add Tax row if any if (getTax(job).getTaxValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, getTotalTax(job), // AMTPRIC "java.lang.Double", doubleCellStyle); } // Add Discount row if any if (getDiscount(job).getDiscountValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, -getTotalDiscount(job), // AMTPRIC "java.lang.Double", doubleCellStyle); } // AMTEXTN index = 0; invoiceDetailsCol++; for (CostComponent costComponent : job.getJobCostingAndPayment().getAllSortedCostComponents()) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, costComponent.getCost(), // AMTEXTN "java.lang.Double", doubleCellStyle); } // Add Tax row if any if (getTax(job).getTaxValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, getTotalTax(job), // AMTEXTN "java.lang.Double", doubleCellStyle); } // Add Discount row if any if (getDiscount(job).getDiscountValue() > 0.0) { ReportUtils.setExcelCellValue(wb, invoiceDetails, invoiceDetailsRow + index++, invoiceDetailsCol, -getTotalDiscount(job), // AMTEXTN "java.lang.Double", doubleCellStyle); } // Fill out Invoice Optional Fields sheet // CNTBTCH (batch number) int index2 = 0; for (int i = 0; i < 4; i++) { ReportUtils.setExcelCellValue(wb, invoiceOptionalFields, invoiceOptionalFieldsRow + index2++, invoiceOptionalFieldsCol, 0, // CNTBTCH "java.lang.Integer", integerCellStyle); } // CNTITEM (Item/Invoice number/index) index2 = 0; ++invoiceOptionalFieldsCol; for (int i = 0; i < 4; i++) { ReportUtils.setExcelCellValue(wb, invoiceOptionalFields, invoiceOptionalFieldsRow + index2++, invoiceOptionalFieldsCol, invoiceRow, // CNTITEM "java.lang.Integer", integerCellStyle); } // OPTFIELD index2 = 0; ++invoiceOptionalFieldsCol; // DEPTCODE ReportUtils.setExcelCellValue(wb, invoiceOptionalFields, invoiceOptionalFieldsRow + index2++, invoiceOptionalFieldsCol, "DEPTCODE", // DEPTCODE "java.lang.String", stringCellStyle); // INVCONTACT ReportUtils.setExcelCellValue(wb, invoiceOptionalFields, invoiceOptionalFieldsRow + index2++, invoiceOptionalFieldsCol, "INVCONTACT", // INVCONTACT "java.lang.String", stringCellStyle); // JOBNO ReportUtils.setExcelCellValue(wb, invoiceOptionalFields, invoiceOptionalFieldsRow + index2++, invoiceOptionalFieldsCol, "JOBNO", // JOBNO "java.lang.String", stringCellStyle); // REFNO ReportUtils.setExcelCellValue(wb, invoiceOptionalFields, invoiceOptionalFieldsRow + index2++, invoiceOptionalFieldsCol, "REFNO", // REFNO "java.lang.String", stringCellStyle); // OPTFIELD/VALUE index2 = 0; ++invoiceOptionalFieldsCol; // DEPTCODE ReportUtils.setExcelCellValue(wb, invoiceOptionalFields, invoiceOptionalFieldsRow + index2++, invoiceOptionalFieldsCol, job.getDepartmentAssignedToJob().getCode(), // DEPTCODE "java.lang.String", stringCellStyle); // INVCONTACT ReportUtils.setExcelCellValue(wb, invoiceOptionalFields, invoiceOptionalFieldsRow + index2++, invoiceOptionalFieldsCol, job.getContact().getFirstName() + " " + job.getContact().getLastName(), // INVCONTACT "java.lang.String", stringCellStyle); // JOBNO ReportUtils.setExcelCellValue(wb, invoiceOptionalFields, invoiceOptionalFieldsRow + index2++, invoiceOptionalFieldsCol, job.getJobNumber(), // JOBNO "java.lang.String", stringCellStyle); // REFNO ReportUtils.setExcelCellValue(wb, invoiceOptionalFields, invoiceOptionalFieldsRow + index2++, invoiceOptionalFieldsCol, "", // REFNO "java.lang.String", stringCellStyle); // Prepare for next invoice invoiceDetailsRow = invoiceDetailsRow + index; invoiceOptionalFieldsRow = invoiceOptionalFieldsRow + index2; invoiceRow++; } } // Write modified Excel file and return it wb.write(out); return new ByteArrayInputStream(out.toByteArray()); } catch (IOException ex) { System.out.println(ex); } return null; } private String getDiscountCodeAbbreviation(Job job) { String currentDiscountCode = // This should be a 4-digit code eg 5133 getDiscount(job).getAccountingCode().getCode(); String deptFullCode = HumanResourceManager.getDepartmentFullCode(getEntityManager1(), job.getDepartmentAssignedToJob()); // Find an accounting code that contains the department's full code AccountingCode accountingCode = AccountingCode.findActiveByCode(getEntityManager1(), currentDiscountCode + "-" + deptFullCode); if (accountingCode != null) { return accountingCode.getAbbreviation(); } else { return getDiscount(job).getAccountingCode().getAbbreviation(); } } private String getTaxCodeAbbreviation(Job job) { String currentTaxCode = // This should be a 4-digit code eg 5133 getTax(job).getAccountingCode().getCode(); String deptFullCode = HumanResourceManager.getDepartmentFullCode(getEntityManager1(), job.getDepartmentAssignedToJob()); // Find an accounting code that contains the department's full code AccountingCode accountingCode = AccountingCode.findActiveByCode(getEntityManager1(), currentTaxCode + "-" + deptFullCode); if (accountingCode != null) { return accountingCode.getAbbreviation(); } else { return getTax(job).getAccountingCode().getAbbreviation(); } } private String getRevenueCodeAbbreviation(Job job) { String revenueCode; String revenueCodeAbbr; if (!job.getServices().isEmpty()) { revenueCode = job.getServices().get(0).getAccountingCode().getCode(); String deptFullCode = HumanResourceManager.getDepartmentFullCode(getEntityManager1(), job.getDepartmentAssignedToJob()); // Find an accounting code that contains the department's full code AccountingCode accountingCode = AccountingCode.findActiveByCode(getEntityManager1(), revenueCode + "-" + deptFullCode); if (accountingCode != null) { revenueCodeAbbr = accountingCode.getAbbreviation(); } else { revenueCodeAbbr = "MISC"; } } else { // Get and use default accounting code Service service = Service.findActiveByNameAndAccountingCode( getEntityManager1(), "Miscellaneous", HumanResourceManager.getDepartmentFullCode(getEntityManager1(), job.getDepartmentAssignedToJob())); if (service != null) { revenueCodeAbbr = service.getAccountingCode().getAbbreviation(); } else { // tk NB: Just using this revenue code for testing for now. // This value is to be obtained from system option. revenueCodeAbbr = "MISC"; } } return revenueCodeAbbr; } public Boolean getEdit() { return edit; } public void setEdit(Boolean edit) { this.edit = edit; } public JobManager getJobManager() { if (jobManager == null) { jobManager = BeanUtils.findBean("jobManager"); } return jobManager; } public JobContractManager getJobContractManager() { if (jobContractManager == null) { jobContractManager = BeanUtils.findBean("jobContractManager"); } return jobContractManager; } private void init() { longProcessProgress = 0; accPacCustomer = new AccPacCustomer(null); useAccPacCustomerList = false; selectedCashPayment = null; selectedCostComponent = null; unitCostDepartment = null; jobCostDepartment = null; filteredAccPacCustomerDocuments = new ArrayList<>(); } public void reset() { init(); } public Boolean getEnableOnlyPaymentEditing() { if (enableOnlyPaymentEditing == null) { enableOnlyPaymentEditing = false; } return enableOnlyPaymentEditing; } public void setEnableOnlyPaymentEditing(Boolean enableOnlyPaymentEditing) { this.enableOnlyPaymentEditing = enableOnlyPaymentEditing; } public Boolean getDialogRenderCancelButton() { return dialogRenderCancelButton; } public void setDialogRenderCancelButton(Boolean dialogRenderCancelButton) { this.dialogRenderCancelButton = dialogRenderCancelButton; } public void setDialogActionHandler(DialogActionHandler dialogActionHandler) { this.dialogActionHandler = dialogActionHandler; } public Boolean getDialogRenderOkButton() { return dialogRenderOkButton; } public void setDialogRenderOkButton(Boolean dialogRenderOkButton) { this.dialogRenderOkButton = dialogRenderOkButton; } public Boolean getDialogRenderYesButton() { return dialogRenderYesButton; } public void setDialogRenderYesButton(Boolean dialogRenderYesButton) { this.dialogRenderYesButton = dialogRenderYesButton; } public Boolean getDialogRenderNoButton() { return dialogRenderNoButton; } public void setDialogRenderNoButton(Boolean dialogRenderNoButton) { this.dialogRenderNoButton = dialogRenderNoButton; } public String getDialogMessage() { return dialogMessage; } public void setDialogMessage(String dialogMessage) { this.dialogMessage = dialogMessage; } public String getDialogMessageHeader() { return dialogMessageHeader; } public void setDialogMessageHeader(String dialogMessageHeader) { this.dialogMessageHeader = dialogMessageHeader; } public String getDialogMessageSeverity() { return dialogMessageSeverity; } public void setDialogMessageSeverity(String dialogMessageSeverity) { this.dialogMessageSeverity = dialogMessageSeverity; } public EntityManager getEntityManager1() { return EMF1.createEntityManager(); } public JobManagerUser getUser() { return user; } public void setUser(JobManagerUser user) { this.user = user; } @Override public String getInvalidFormFieldMessage() { return invalidFormFieldMessage; } @Override public void setInvalidFormFieldMessage(String invalidFormFieldMessage) { this.invalidFormFieldMessage = invalidFormFieldMessage; } public void displayCommonMessageDialog(DialogActionHandler dialogActionHandler, String dialogMessage, String dialogMessageHeader, String dialoMessageSeverity) { setDialogActionHandler(dialogActionHandler); setDialogRenderOkButton(true); setDialogRenderYesButton(false); setDialogRenderNoButton(false); setDialogMessage(dialogMessage); setDialogMessageHeader(dialogMessageHeader); setDialogMessageSeverity(dialoMessageSeverity); PrimeFaces.current().ajax().update("commonMessageDialogForm"); PrimeFaces.current().executeScript("PF('commonMessageDialog').show();"); } public void displayCommonConfirmationDialog(DialogActionHandler dialogActionHandler, String dialogMessage, String dialogMessageHeader, String dialoMessageSeverity) { setDialogActionHandler(dialogActionHandler); setDialogRenderOkButton(false); setDialogRenderYesButton(true); setDialogRenderNoButton(true); setDialogRenderCancelButton(true); setDialogMessage(dialogMessage); setDialogMessageHeader(dialogMessageHeader); setDialogMessageSeverity(dialoMessageSeverity); PrimeFaces.current().ajax().update("commonMessageDialogForm"); PrimeFaces.current().executeScript("PF('commonMessageDialog').show();"); } public void handleDialogOkButtonPressed() { if (dialogActionHandler != null) { dialogActionHandler.handleDialogOkButtonClick(); } } public void handleDialogYesButtonPressed() { if (dialogActionHandler != null) { dialogActionHandler.handleDialogYesButtonClick(); } } public void handleDialogNoButtonPressed() { if (dialogActionHandler != null) { dialogActionHandler.handleDialogNoButtonClick(); } } public void handleDialogCancelButtonPressed() { if (dialogActionHandler != null) { dialogActionHandler.handleDialogCancelButtonClick(); } } public List<AccPacDocument> getFilteredAccPacCustomerDocuments() { return filteredAccPacCustomerDocuments; } public void setFilteredAccPacCustomerDocuments(List<AccPacDocument> filteredAccPacCustomerDocuments) { this.filteredAccPacCustomerDocuments = filteredAccPacCustomerDocuments; } public Boolean getShowPrepayments() { if (showPrepayments == null) { showPrepayments = false; } return showPrepayments; } public void setShowPrepayments(Boolean showPrepayments) { this.showPrepayments = showPrepayments; } public Department getJobCostDepartment() { if (jobCostDepartment == null) { jobCostDepartment = new Department(""); } return jobCostDepartment; } public void setJobCostDepartment(Department jobCostDepartment) { this.jobCostDepartment = jobCostDepartment; } public Job getCurrentJobWithCosting() { if (currentJobWithCosting == null) { currentJobWithCosting = new Job(); } return currentJobWithCosting; } public void setCurrentJobWithCosting(Job currentJobWithCosting) { this.currentJobWithCosting = currentJobWithCosting; } public List<Job> getJobsWithCostings() { if (jobsWithCostings == null) { jobsWithCostings = new ArrayList<>(); } return jobsWithCostings; } public List<UnitCost> getUnitCosts() { if (unitCosts == null) { unitCosts = new ArrayList<>(); } return unitCosts; } public UnitCost getCurrentUnitCost() { if (currentUnitCost == null) { currentUnitCost = new UnitCost(); } return currentUnitCost; } public void setCurrentUnitCost(UnitCost currentUnitCost) { this.currentUnitCost = currentUnitCost; } public Department getUnitCostDepartment() { if (unitCostDepartment == null) { unitCostDepartment = new Department(""); } return unitCostDepartment; } public void setUnitCostDepartment(Department unitCostDepartment) { this.unitCostDepartment = unitCostDepartment; } public Boolean getCanEditJobCosting() { return getUser().getPrivilege().getCanBeFinancialAdministrator() || getCurrentJob().getJobCostingAndPayment().getCashPayments().isEmpty(); } public String getSelectedJobCostingTemplate() { return selectedJobCostingTemplate; } public void setSelectedJobCostingTemplate(String selectedJobCostingTemplate) { this.selectedJobCostingTemplate = selectedJobCostingTemplate; } private Boolean isJobAssignedToUserDepartment(Job job) { if (getUser() != null) { if (job.getDepartment().getId().longValue() == getUser().getEmployee().getDepartment().getId().longValue()) { return true; } else { return job.getSubContractedDepartment().getId().longValue() == getUser().getEmployee().getDepartment().getId().longValue(); } } else { return false; } } public void onCostComponentSelect(SelectEvent event) { selectedCostComponent = (CostComponent) event.getObject(); } public CostComponent getSelectedCostComponent() { return selectedCostComponent; } public void setSelectedCostComponent(CostComponent selectedCostComponent) { this.selectedCostComponent = selectedCostComponent; } public Boolean getUseAccPacCustomerList() { return useAccPacCustomerList; } public void setUseAccPacCustomerList(Boolean useAccPacCustomerList) { this.useAccPacCustomerList = useAccPacCustomerList; } public Integer getNumberOfDocumentsPassDocDate(Integer days) { Integer count = 0; for (AccPacDocument doc : filteredAccPacCustomerDocuments) { if (doc.getDaysOverDocumentDate() >= days) { ++count; } } return count; } public String getAccountStatus() { if (getTotalInvoicesAmountOverMaxInvDays().doubleValue() > 0.0 && getTotalInvoicesAmount().doubleValue() > 0.0) { return "hold"; } else { return "active"; } } public BigDecimal getTotalInvoicesAmountOverMaxInvDays() { BigDecimal total = new BigDecimal(0.0); for (AccPacDocument doc : filteredAccPacCustomerDocuments) { if (doc.getDaysOverdue() > getMaxDaysPassInvoiceDate()) { total = total.add(doc.getCustCurrencyAmountDue()); } } return total; } public BigDecimal getTotalInvoicesAmount() { BigDecimal total = new BigDecimal(0.0); for (AccPacDocument doc : filteredAccPacCustomerDocuments) { total = total.add(doc.getCustCurrencyAmountDue()); } return total; } public Integer getMaxDaysPassInvoiceDate() { EntityManager em = getEntityManager1(); int days = (Integer) SystemOption.getOptionValueObject(em, "maxDaysPassInvoiceDate"); return days; } /** * Get status based on the total amount on documents pass the max allowed * days pass the invoice date * * @return */ public String getAccPacCustomerAccountStatus() { if (getAccountStatus().equals("hold")) { return "HOLD"; } else { return "ACTIVE"; } } public Integer getNumDocumentsPassMaxInvDate() { return getNumberOfDocumentsPassDocDate(getMaxDaysPassInvoiceDate()); } public Integer getLongProcessProgress() { if (longProcessProgress == null) { longProcessProgress = 0; } else { if (longProcessProgress < 10) { // this is to ensure that this method does not make the progress // complete as this is done elsewhere. longProcessProgress = longProcessProgress + 1; } } return longProcessProgress; } public void onLongProcessComplete() { longProcessProgress = 0; } public void setLongProcessProgress(Integer longProcessProgress) { this.longProcessProgress = longProcessProgress; } // tk get forms public StreamedContent getJobCostingAnalysisFile(EntityManager em) { HashMap parameters = new HashMap(); try { parameters.put("jobId", getCurrentJob().getId()); Client client = getCurrentJob().getClient(); parameters.put("contactPersonName", BusinessEntityUtils.getContactFullName(getCurrentJob().getContact())); parameters.put("customerAddress", getCurrentJob().getBillingAddress().toString()); parameters.put("contactNumbers", client.getStringListOfContactPhoneNumbers()); parameters.put("jobDescription", getCurrentJob().getJobDescription()); parameters.put("totalCost", getCurrentJob().getJobCostingAndPayment().getTotalJobCostingsAmount()); parameters.put("depositReceiptNumbers", getCurrentJob().getJobCostingAndPayment().getReceiptNumbers()); parameters.put("discount", getCurrentJob().getJobCostingAndPayment().getDiscount().getDiscountValue()); parameters.put("discountType", getCurrentJob().getJobCostingAndPayment().getDiscount().getDiscountValueType()); parameters.put("deposit", getCurrentJob().getJobCostingAndPayment().getTotalPayment()); parameters.put("amountDue", getCurrentJob().getJobCostingAndPayment().getAmountDue()); parameters.put("totalTax", getTotalTax(getCurrentJob())); parameters.put("totalTaxLabel", getCurrentJob().getJobCostingAndPayment().getTotalTaxLabel()); parameters.put("grandTotalCostLabel", getCurrentJob().getJobCostingAndPayment().getTotalCostWithTaxLabel().toUpperCase().trim()); parameters.put("grandTotalCost", getCurrentJob().getJobCostingAndPayment().getTotalCost()); if (getCurrentJob().getJobCostingAndPayment().getCostingPreparedBy() != null) { parameters.put("preparedBy", getCurrentJob().getJobCostingAndPayment().getCostingPreparedBy().getFirstName() + " " + getCurrentJob().getJobCostingAndPayment().getCostingPreparedBy().getLastName()); } if (getCurrentJob().getJobCostingAndPayment().getCostingApprovedBy() != null) { parameters.put("approvedBy", getCurrentJob().getJobCostingAndPayment().getCostingApprovedBy().getFirstName() + " " + getCurrentJob().getJobCostingAndPayment().getCostingApprovedBy().getLastName()); } parameters.put("approvalDate", BusinessEntityUtils.getDateInMediumDateFormat( getCurrentJob().getJobStatusAndTracking().getDateCostingApproved())); Connection con = BusinessEntityUtils.establishConnection( (String) SystemOption.getOptionValueObject(em, "defaultDatabaseDriver"), (String) SystemOption.getOptionValueObject(em, "defaultDatabaseURL"), (String) SystemOption.getOptionValueObject(em, "defaultDatabaseUsername"), (String) SystemOption.getOptionValueObject(em, "defaultDatabasePassword")); if (con != null) { try { StreamedContent streamContent; // Compile report JasperReport jasperReport = JasperCompileManager. compileReport((String) SystemOption.getOptionValueObject(em, "jobCosting")); // Generate report JasperPrint print = JasperFillManager.fillReport(jasperReport, parameters, con); byte[] fileBytes = JasperExportManager.exportReportToPdf(print); streamContent = new DefaultStreamedContent(new ByteArrayInputStream(fileBytes), "application/pdf", "Job Costing - " + getCurrentJob().getJobNumber() + ".pdf"); setLongProcessProgress(100); return streamContent; } catch (JRException ex) { System.out.println(ex); return null; } } return null; } catch (Exception e) { System.out.println(e); return null; } } public StreamedContent getJobCostingFile() { EntityManager em; try { em = getEntityManager1(); if (getCurrentJob().getIsDirty()) { getCurrentJob().getJobCostingAndPayment().save(em); getCurrentJob().setIsDirty(false); } jobCostingFile = getJobCostingAnalysisFile(em); setLongProcessProgress(100); } catch (Exception e) { System.out.println(e); setLongProcessProgress(100); } return jobCostingFile; } public Boolean getCanExportJobCosting() { return !(getCurrentJob().getJobCostingAndPayment().getCostingApproved() && getCurrentJob().getJobCostingAndPayment().getCostingCompleted()); } private void prepareToInvoiceJobCosting(Job job) { // Ensure that services are added based on the service contract getJobContractManager().addServices(job); // Ensure that an accounting Id is added for the client AccPacCustomer financialAccount = AccPacCustomer.findByName( getEntityManager2(), job.getClient().getName()); if (financialAccount != null) { // Set accounting Id job.getClient().setAccountingId(financialAccount.getIdCust()); // Set credit limit job.getClient().setCreditLimit((financialAccount.getCreditLimit().doubleValue())); // Update and save job.getClient().setEditedBy(getUser().getEmployee()); job.getClient().setDateEdited(new Date()); job.getClient().save(getEntityManager1()); } // tk update costs, tax, discount updates } public void invoiceJobCosting() { invoiceJobCosting(getCurrentJob(), getCurrentJob().getJobCostingAndPayment().getInvoiced()); } public Boolean canInvoiceJobCosting(Job job) { // Check for permission to invoice by department that can do invoices // NB: This permission will be put in the user's profile in the future. if (!getUser().getEmployee().getDepartment().getPrivilege().getCanEditInvoicingAndPayment()) { PrimeFacesUtils.addMessage("Permission Denied", "You do not have permission to create an invoice for " + job.getJobNumber(), FacesMessage.SEVERITY_ERROR); return false; } // Check if approved if (!job.getJobCostingAndPayment().getCostingApproved()) { PrimeFacesUtils.addMessage("Job Costing NOT Approved", "The job costing was not approved for " + job.getJobNumber(), FacesMessage.SEVERITY_ERROR); return false; } // Check for a valid cleint Id if (job.getClient().getFinancialAccount().getIdCust().isEmpty()) { PrimeFacesUtils.addMessage("Client Identification required", "The client identification (Id) is not set for " + job.getJobNumber(), FacesMessage.SEVERITY_ERROR); return false; } return true; } public List<Preference> getJobTableViewPreferences() { EntityManager em = getEntityManager1(); List<Preference> prefs = Preference.findAllPreferencesByName(em, "jobTableView"); return prefs; } /** * Determine if the current user can mark the current job costing as being * completed. This is done by determining if the job was assigned to the * user. * * @param job * @return */ public Boolean canUserCompleteJobCosting(Job job) { return isJobAssignedToUserDepartment(job); } public CashPayment getSelectedCashPayment() { return selectedCashPayment; } public void setSelectedCashPayment(CashPayment selectedCashPayment) { this.selectedCashPayment = selectedCashPayment; // If this is a new cash payment ensure that all related costs are updated // and the job cost and payment saved. if (getSelectedCashPayment().getId() == null) { updateFinalCost(); updateAmountDue(); if (!getCurrentJob().prepareAndSave(getEntityManager1(), getUser()).isSuccess()) { PrimeFacesUtils.addMessage("Payment and Job NOT Saved!", "Payment and the job and the payment were NOT saved!", FacesMessage.SEVERITY_ERROR); } } } public EntityManager getEntityManager2() { return getEMF2().createEntityManager(); } public void updateJobCostingAndPayment() { setJobCostingAndPaymentDirty(true); } public void updateCashPayment() { getSelectedCashPayment().setIsDirty(true); } public void updateCostComponent() { updateCostType(); getSelectedCostComponent().setIsDirty(true); } public void updateSubcontract(AjaxBehaviorEvent event) { if (!((SelectOneMenu) event.getComponent()).getValue().toString().equals("null")) { Long subcontractId = new Long(((SelectOneMenu) event.getComponent()).getValue().toString()); Job subcontract = Job.findJobById(getEntityManager1(), subcontractId); selectedCostComponent.setCost(subcontract.getJobCostingAndPayment().getFinalCost()); selectedCostComponent.setName("Subcontract (" + subcontract.getJobNumber() + ")"); updateCostComponent(); } } public void updateAllTaxes(AjaxBehaviorEvent event) { EntityManager em = getEntityManager1(); if (getCurrentJob().getJobCostingAndPayment().getId() != null) { JobCostingAndPayment jcp = JobCostingAndPayment.findJobCostingAndPaymentById(em, getCurrentJob().getJobCostingAndPayment().getId()); em.refresh(jcp); if (!(jcp.getCashPayments().isEmpty() || getUser().getPrivilege().getCanBeFinancialAdministrator())) { // Reset cash payments getCurrentJob().getJobCostingAndPayment(). setCashPayments(jcp.getCashPayments()); PrimeFacesUtils.addMessage("Permission Denied", "A payment was made on this job so update of this field is not allowed", FacesMessage.SEVERITY_ERROR); setJobCostingAndPaymentDirty(false); } else { updateJobCostingEstimate(); updateTotalCost(); setJobCostingAndPaymentDirty(true); } } else { updateJobCostingEstimate(); updateTotalCost(); setJobCostingAndPaymentDirty(true); } } public String getSubcontractsMessage() { if (getCurrentJob().getId() != null) { if (!getCurrentJob().findSubcontracts(getEntityManager1()).isEmpty()) { return ("{ " + getCurrentJob().getSubcontracts(getEntityManager1()).size() + " subcontract(s) exist(s) that can be added as cost item(s) }"); } else if (!getCurrentJob().findPossibleSubcontracts(getEntityManager1()).isEmpty()) { return ("{ " + getCurrentJob().getPossibleSubcontracts(getEntityManager1()).size() + " possible subcontract(s) exist(s) that can be added as cost item(s) }"); } else { return ""; } } else { return ""; } } public void updateMinimumDepositRequired() { EntityManager em = getEntityManager1(); if (getCurrentJob().getJobCostingAndPayment().getId() != null) { JobCostingAndPayment jcp = JobCostingAndPayment.findJobCostingAndPaymentById(em, getCurrentJob().getJobCostingAndPayment().getId()); em.refresh(jcp); if (!(jcp.getCashPayments().isEmpty() || getUser().getPrivilege().getCanBeFinancialAdministrator())) { // Reset min deposit required getCurrentJob().getJobCostingAndPayment(). setMinDeposit(jcp.getMinDeposit()); // Reset cash payments getCurrentJob().getJobCostingAndPayment(). setCashPayments(jcp.getCashPayments()); PrimeFacesUtils.addMessage("Permission Denied", "A payment was made on this job so update of this field is not allowed", FacesMessage.SEVERITY_ERROR); setJobCostingAndPaymentDirty(false); } else { updateJobCostingEstimate(); setJobCostingAndPaymentDirty(true); } } else { updateJobCostingEstimate(); setJobCostingAndPaymentDirty(true); } } public void updatePurchaseOrderNumber() { EntityManager em = getEntityManager1(); if (getCurrentJob().getJobCostingAndPayment().getId() != null) { JobCostingAndPayment jcp = JobCostingAndPayment.findJobCostingAndPaymentById(em, getCurrentJob().getJobCostingAndPayment().getId()); em.refresh(jcp); if (!(jcp.getCashPayments().isEmpty() || getUser().getPrivilege().getCanBeFinancialAdministrator())) { // Reset PO# getCurrentJob().getJobCostingAndPayment(). setPurchaseOrderNumber(jcp.getPurchaseOrderNumber()); // Reset cash payments getCurrentJob().getJobCostingAndPayment(). setCashPayments(jcp.getCashPayments()); PrimeFacesUtils.addMessage("Permission Denied", "A payment was made on this job so update of this field is not allowed", FacesMessage.SEVERITY_ERROR); setJobCostingAndPaymentDirty(false); } else { setJobCostingAndPaymentDirty(true); } } else { setJobCostingAndPaymentDirty(true); } } public void updateEstimatedCostIncludingTaxes() { updateJobCostingEstimate(); } public void updateMinimumDepositIncludingTaxes() { updateJobCostingEstimate(); } public void updateJobCostingEstimate() { EntityManager em = getEntityManager1(); if (getCurrentJob().getJobCostingAndPayment().getId() != null) { JobCostingAndPayment jcp = JobCostingAndPayment.findJobCostingAndPaymentById(em, getCurrentJob().getJobCostingAndPayment().getId()); em.refresh(jcp); if (!(jcp.getCashPayments().isEmpty() || getUser().getPrivilege().getCanBeFinancialAdministrator())) { // Reset cost estimate getCurrentJob().getJobCostingAndPayment(). setEstimatedCost(jcp.getEstimatedCost()); // Reset cash payments getCurrentJob().getJobCostingAndPayment(). setCashPayments(jcp.getCashPayments()); PrimeFacesUtils.addMessage("Permission Denied", "A payment was made on this job so update of this field is not allowed", FacesMessage.SEVERITY_ERROR); setJobCostingAndPaymentDirty(false); } else { // Update estmated cost and min. deposit // tk may not need to do this here but in the respective get methods if (getCurrentJob().getJobCostingAndPayment().getEstimatedCost() != null) { Double estimatedCostWithTaxes = getCurrentJob().getJobCostingAndPayment().getEstimatedCost() + getCurrentJob().getJobCostingAndPayment().getEstimatedCost() * getCurrentJob().getJobCostingAndPayment().getTax().getValue(); getCurrentJob().getJobCostingAndPayment().setEstimatedCostIncludingTaxes(estimatedCostWithTaxes); setJobCostingAndPaymentDirty(true); } // tk may not need to do this here but in the respective get methods if (getCurrentJob().getJobCostingAndPayment().getMinDeposit() != null) { Double minDepositWithTaxes = getCurrentJob().getJobCostingAndPayment().getMinDeposit() + getCurrentJob().getJobCostingAndPayment().getMinDeposit() * getCurrentJob().getJobCostingAndPayment().getTax().getValue(); getCurrentJob().getJobCostingAndPayment().setMinDepositIncludingTaxes(minDepositWithTaxes); setJobCostingAndPaymentDirty(true); } } } else { setJobCostingAndPaymentDirty(true); } } public void updateTotalDeposit() { EntityManager em = getEntityManager1(); Employee employee = Employee.findEmployeeById(em, getUser().getEmployee().getId()); if (employee != null) { getCurrentJob().getJobCostingAndPayment().setLastPaymentEnteredBy(employee); } updateAmountDue(); setIsDirty(true); } public void update() { setIsDirty(true); } public void updateJobCostingValidity() { if (!validateCurrentJobCosting() && getCurrentJob().getJobCostingAndPayment().getCostingCompleted()) { getCurrentJob().getJobCostingAndPayment().setCostingCompleted(false); getCurrentJob().getJobCostingAndPayment().setCostingApproved(false); displayCommonMessageDialog(null, "Removing the content of a required field has invalidated this job costing", "Invalid Job Costing", "info"); } else { setJobCostingAndPaymentDirty(true); } } public void prepareJobCosting() { if (getCurrentJob().getJobCostingAndPayment().getCostingApproved()) { getCurrentJob().getJobCostingAndPayment().setCostingCompleted(!getCurrentJob().getJobCostingAndPayment().getCostingCompleted()); PrimeFacesUtils.addMessage("Job Costing Already Approved", "The job costing preparation status cannot be changed because it was already approved", FacesMessage.SEVERITY_ERROR); } else if (getCurrentJob().getJobCostingAndPayment().getCostingCompleted()) { getCurrentJob().getJobStatusAndTracking().setDateCostingCompleted(new Date()); getCurrentJob().getJobStatusAndTracking().setCostingDate(new Date()); getCurrentJob().getJobCostingAndPayment().setCostingPreparedBy( getUser().getEmployee()); } else if (!getCurrentJob().getJobCostingAndPayment().getCostingCompleted()) { getCurrentJob().getJobStatusAndTracking().setDateCostingCompleted(null); getCurrentJob().getJobStatusAndTracking().setCostingDate(null); getCurrentJob().getJobCostingAndPayment().setCostingPreparedBy(null); } setJobCostingAndPaymentDirty(true); } /** * Determine if the current user is the department's supervisor. This is * done by determining if the user is the head/active acting head of the * department to which the job was assigned. * * @param job * @return */ public Boolean isUserDepartmentSupervisor(Job job) { EntityManager em = getEntityManager1(); Job foundJob = Job.findJobById(em, job.getId()); if (Department.findDepartmentAssignedToJob(foundJob, em).getHead().getId().longValue() == getUser().getEmployee().getId().longValue()) { return true; } else { return (Department.findDepartmentAssignedToJob(foundJob, em).getActingHead().getId().longValue() == getUser().getEmployee().getId().longValue()) && Department.findDepartmentAssignedToJob(foundJob, em).getActingHeadActive(); } } public void approveJobCosting() { if (canChangeJobCostingApprovalStatus(getCurrentJob())) { if (getCurrentJob().getJobCostingAndPayment().getCostingApproved()) { getCurrentJob().getJobStatusAndTracking().setDateCostingApproved(new Date()); getCurrentJob().getJobCostingAndPayment().setCostingApprovedBy( getUser().getEmployee()); } else { getCurrentJob().getJobStatusAndTracking().setDateCostingApproved(null); getCurrentJob().getJobCostingAndPayment().setCostingApprovedBy(null); } setJobCostingAndPaymentDirty(true); } else { // Reset the costing status getCurrentJob().getJobCostingAndPayment(). setCostingApproved(!getCurrentJob().getJobCostingAndPayment().getCostingApproved()); } } public Boolean canChangeJobCostingApprovalStatus(Job job) { if (!job.getJobCostingAndPayment().getCostingCompleted() || job.getJobCostingAndPayment().getInvoiced()) { PrimeFacesUtils.addMessage("Cannot Change Approval Status", "The job costing approval status for " + job.getJobNumber() + " cannot be changed before the job costing is prepared or if it was already invoiced", FacesMessage.SEVERITY_ERROR); return false; } else if (isUserDepartmentSupervisor(job) || (isJobAssignedToUserDepartment(job) && getUser().getPrivilege().getCanApproveJobCosting())) { return true; } else { PrimeFacesUtils.addMessage("No Permission", "You do not have the permission to change the job costing approval status for " + job.getJobNumber(), FacesMessage.SEVERITY_ERROR); return false; } } public void updatePreferences() { setIsDirty(true); } public void updateCostType() { selectedCostComponent.update(); } public Boolean getAllowCostEdit() { if (selectedCostComponent != null) { if (null == selectedCostComponent.getType()) { return true; } else { switch (selectedCostComponent.getType()) { case "--": return true; default: return false; } } } else { return true; } } public void updateIsCostComponentHeading() { } public void updateIsCostComponentFixedCost() { if (getSelectedCostComponent().getIsFixedCost()) { } } public void updateNewClient() { setIsDirty(true); } public void updateJobNumber() { setIsDirty(true); } public void updateSamplesCollected() { setIsDirty(true); } public void closelJobCostingDialog() { PrimeFaces.current().dialog().closeDynamic(null); } public void closeUnitCostDialog() { // prompt to save modified job before attempting to create new job if (getIsDirty()) { // ask to save displayCommonConfirmationDialog(initDialogActionHandlerId("unitCostDirty"), "This unit cost was modified. Do you wish to save it?", "Unit Cost Not Saved", "info"); } else { PrimeFaces.current().executeScript("PF('unitCostDialog').hide();"); } } public void cancelJobCostingEdit(ActionEvent actionEvent) { setIsDirty(false); PrimeFaces.current().dialog().closeDynamic(null); } public void cancelJobCostingAndPayment(ActionEvent actionEvent) { EntityManager em = getEntityManager1(); // refetch costing data from database if (getCurrentJob() != null) { if (getCurrentJob().getId() != null) { Job job = Job.findJobById(em, getCurrentJob().getId()); getCurrentJob().setJobCostingAndPayment(job.getJobCostingAndPayment()); } } setIsDirty(false); } public void jobCostingDialogReturn() { if (getCurrentJob().getId() != null) { if (isJobCostingAndPaymentDirty()) { if (getCurrentJob().prepareAndSave(getEntityManager1(), getUser()).isSuccess()) { getCurrentJob().getJobStatusAndTracking().setEditStatus(""); PrimeFacesUtils.addMessage("Job Costing and Job Saved", "This job and the costing were saved", FacesMessage.SEVERITY_INFO); } else { PrimeFacesUtils.addMessage("Job Costing and Job NOT Saved", "This job and the costing were NOT saved", FacesMessage.SEVERITY_ERROR); } } } } public void okJobCosting(ActionEvent actionEvent) { try { if (getUser().getEmployee() != null) { getCurrentJob().getJobCostingAndPayment().setFinalCostDoneBy(getUser().getEmployee().getName()); } } catch (Exception e) { System.out.println(e); } PrimeFaces.current().dialog().closeDynamic(null); } public Boolean validateCurrentJobCosting() { try { // check for valid job if (getCurrentJob().getId() == null) { return false; } // check for job report # and description if ((getCurrentJob().getReportNumber() == null) || (getCurrentJob().getReportNumber().trim().equals(""))) { return false; } if (getCurrentJob().getJobDescription().trim().equals("")) { return false; } } catch (Exception e) { System.out.println(e); } return true; } public void saveUnitCost() { EntityManager em = getEntityManager1(); try { // Validate and save objects // Department Department department = Department.findDepartmentByName(em, getCurrentUnitCost().getDepartment().getName()); if (department == null) { setInvalidFormFieldMessage("This unit cost cannot be saved because a valid department was not entered."); return; } else { getCurrentUnitCost().setDepartment(department); } // Department unit DepartmentUnit departmentUnit = DepartmentUnit.findDepartmentUnitByName(em, getCurrentUnitCost().getDepartmentUnit().getName()); if (departmentUnit == null) { getCurrentUnitCost().setDepartmentUnit(DepartmentUnit.getDefaultDepartmentUnit(em, "--")); } else { getCurrentUnitCost().setDepartmentUnit(departmentUnit); } // Laboratory unit Laboratory laboratory = Laboratory.findLaboratoryByName(em, getCurrentUnitCost().getLaboratory().getName()); if (laboratory == null) { getCurrentUnitCost().setLaboratory(Laboratory.getDefaultLaboratory(em, "--")); } else { getCurrentUnitCost().setLaboratory(laboratory); } // Service if (getCurrentUnitCost().getService().trim().equals("")) { setInvalidFormFieldMessage("This unit cost cannot be saved because a valid service was not entered."); return; } // Cost if (getCurrentUnitCost().getCost() <= 0.0) { setInvalidFormFieldMessage("This unit cost cannot be saved because a valid cost was not entered."); return; } // Effective date if (getCurrentUnitCost().getEffectiveDate() == null) { setInvalidFormFieldMessage("This unit cost cannot be saved because a valid effective date was not entered."); return; } // save job to database and check for errors em.getTransaction().begin(); Long id = BusinessEntityUtils.saveBusinessEntity(em, currentUnitCost); if (id == null) { sendErrorEmail("An error occurred while saving this unit cost", "Unit cost save error occurred"); return; } em.getTransaction().commit(); setIsDirty(false); } catch (Exception e) { System.out.println(e); // send error message to developer's email sendErrorEmail("An exception occurred while saving a unit cost!", "\nJMTS User: " + getUser().getUsername() + "\nDate/time: " + new Date() + "\nException detail: " + e); } } public String getCompletedJobCostingEmailMessage(Job job) { String message = ""; DateFormat formatter = new SimpleDateFormat("MMM dd, yyyy"); message = message + "Dear Colleague,<br><br>"; message = message + "The costing for a job with the following details was completed via the <a href='http://boshrmapp:8080/jmts'>Job Management & Tracking System (JMTS)</a>:<br><br>"; message = message + "<span style='font-weight:bold'>Job number: </span>" + job.getJobNumber() + "<br>"; message = message + "<span style='font-weight:bold'>Client: </span>" + job.getClient().getName() + "<br>"; if (!job.getSubContractedDepartment().getName().equals("--")) { message = message + "<span style='font-weight:bold'>Department: </span>" + job.getSubContractedDepartment().getName() + "<br>"; } else { message = message + "<span style='font-weight:bold'>Department: </span>" + job.getDepartment().getName() + "<br>"; } message = message + "<span style='font-weight:bold'>Date submitted: </span>" + formatter.format(job.getJobStatusAndTracking().getDateSubmitted()) + "<br>"; message = message + "<span style='font-weight:bold'>Current assignee: </span>" + BusinessEntityUtils.getPersonFullName(job.getAssignedTo(), Boolean.FALSE) + "<br>"; message = message + "<span style='font-weight:bold'>Task/Sample descriptions: </span>" + job.getJobSampleDescriptions() + "<br><br>"; message = message + "As the department's supervisor/head, you are required to review and approve this costing. An email will be automatically sent to the Finance department after approval.<br><br>"; message = message + "If this job was incorrectly assigned to your department, the department supervisor should contact the person who entered/assigned the job.<br><br>"; message = message + "This email was automatically generated and sent by the <a href='http://boshrmapp:8080/jmts'>JMTS</a>. Please DO NOT reply.<br><br>"; message = message + "Signed<br>"; message = message + "Job Manager"; return message; } public String getApprovedJobCostingEmailMessage(Job job) { String message = ""; DateFormat formatter = new SimpleDateFormat("MMM dd, yyyy"); EntityManager em = getEntityManager1(); message = message + "Dear Colleague,<br><br>"; message = message + "The costing for a job with the following details was approved via the <a href='http://boshrmapp:8080/jmts'>Job Management & Tracking System (JMTS)</a>:<br><br>"; message = message + "<span style='font-weight:bold'>Job number: </span>" + job.getJobNumber() + "<br>"; message = message + "<span style='font-weight:bold'>Client: </span>" + job.getClient().getName() + "<br>"; if (!job.getSubContractedDepartment().getName().equals("--")) { message = message + "<span style='font-weight:bold'>Department: </span>" + job.getSubContractedDepartment().getName() + "<br>"; } else { message = message + "<span style='font-weight:bold'>Department: </span>" + job.getDepartment().getName() + "<br>"; } message = message + "<span style='font-weight:bold'>Date submitted: </span>" + formatter.format(job.getJobStatusAndTracking().getDateSubmitted()) + "<br>"; message = message + "<span style='font-weight:bold'>Department/Unit Head: </span>" + BusinessEntityUtils.getPersonFullName(Department.findDepartmentAssignedToJob(job, em).getHead(), false) + "<br>"; message = message + "<span style='font-weight:bold'>Task/Sample descriptions: </span>" + job.getJobSampleDescriptions() + "<br><br>"; message = message + "If this email was sent to you in error, please contact the department referred to above.<br><br>"; message = message + "This email was automatically generated and sent by the <a href='http://boshrmapp:8080/jmts'>JMTS</a>. Please DO NOT reply.<br><br>"; message = message + "Signed<br>"; message = message + "Job Manager"; return message; } public String getNewJobEmailMessage(Job job) { String message = ""; DateFormat formatter = new SimpleDateFormat("MMM dd, yyyy"); message = message + "Dear Colleague,<br><br>"; message = message + "A job with the following details was assigned to your department via the <a href='http://boshrmapp:8080/jmts'>Job Management & Tracking System (JMTS)</a>:<br><br>"; message = message + "<span style='font-weight:bold'>Job number: </span>" + job.getJobNumber() + "<br>"; message = message + "<span style='font-weight:bold'>Client: </span>" + job.getClient().getName() + "<br>"; if (!job.getSubContractedDepartment().getName().equals("--")) { message = message + "<span style='font-weight:bold'>Department: </span>" + job.getSubContractedDepartment().getName() + "<br>"; } else { message = message + "<span style='font-weight:bold'>Department: </span>" + job.getDepartment().getName() + "<br>"; } message = message + "<span style='font-weight:bold'>Date submitted: </span>" + formatter.format(job.getJobStatusAndTracking().getDateSubmitted()) + "<br>"; message = message + "<span style='font-weight:bold'>Current assignee: </span>" + BusinessEntityUtils.getPersonFullName(job.getAssignedTo(), Boolean.FALSE) + "<br>"; message = message + "<span style='font-weight:bold'>Entered by: </span>" + BusinessEntityUtils.getPersonFullName(job.getJobStatusAndTracking().getEnteredBy(), Boolean.FALSE) + "<br>"; message = message + "<span style='font-weight:bold'>Task/Sample descriptions: </span>" + job.getJobSampleDescriptions() + "<br><br>"; message = message + "If you are the department's supervisor, you should immediately ensure that the job was correctly assigned to your staff member who will see to its completion.<br><br>"; message = message + "If this job was incorrectly assigned to your department, the department supervisor should contact the person who entered/assigned the job.<br><br>"; message = message + "This email was automatically generated and sent by the <a href='http://boshrmapp:8080/jmts'>JMTS</a>. Please DO NOT reply.<br><br>"; message = message + "Signed<br>"; message = message + "Job Manager"; return message; } public String getUpdatedJobEmailMessage(Job job) { String message = ""; DateFormat formatter = new SimpleDateFormat("MMM dd, yyyy"); message = message + "Dear Colleague,<br><br>"; message = message + "A job with the following details was updated by someone outside of your department via the <a href='http://boshrmapp:8080/jmts'>Job Management & Tracking System (JMTS)</a>:<br><br>"; message = message + "<span style='font-weight:bold'>Job number: </span>" + job.getJobNumber() + "<br>"; message = message + "<span style='font-weight:bold'>Client: </span>" + job.getClient().getName() + "<br>"; if (!job.getSubContractedDepartment().getName().equals("--")) { message = message + "<span style='font-weight:bold'>Department: </span>" + job.getSubContractedDepartment().getName() + "<br>"; } else { message = message + "<span style='font-weight:bold'>Department: </span>" + job.getDepartment().getName() + "<br>"; } message = message + "<span style='font-weight:bold'>Date submitted: </span>" + formatter.format(job.getJobStatusAndTracking().getDateSubmitted()) + "<br>"; message = message + "<span style='font-weight:bold'>Current assignee: </span>" + BusinessEntityUtils.getPersonFullName(job.getAssignedTo(), Boolean.FALSE) + "<br>"; message = message + "<span style='font-weight:bold'>Updated by: </span>" + BusinessEntityUtils.getPersonFullName(job.getJobStatusAndTracking().getEditedBy(), Boolean.FALSE) + "<br>"; message = message + "<span style='font-weight:bold'>Task/Sample descriptions: </span>" + job.getJobSampleDescriptions() + "<br><br>"; message = message + "You are being informed of this update so that you may take the requisite action.<br><br>"; message = message + "This email was automatically generated and sent by the <a href='http://boshrmapp:8080/jmts'>JMTS</a>. Please DO NOT reply.<br><br>"; message = message + "Signed<br>"; message = message + "Job Manager"; return message; } /** * Update/create alert for the current job if the job is not completed. * * @param em * @throws java.lang.Exception */ public void updateAlert(EntityManager em) throws Exception { if (getCurrentJob().getJobStatusAndTracking().getCompleted() == null) { em.getTransaction().begin(); Alert alert = Alert.findFirstAlertByOwnerId(em, getCurrentJob().getId()); if (alert == null) { // This seems to be a new job alert = new Alert(getCurrentJob().getId(), new Date(), "Job entered"); em.persist(alert); } else { em.refresh(alert); alert.setActive(true); alert.setDueTime(new Date()); alert.setStatus("Job saved"); } em.getTransaction().commit(); } else if (!getCurrentJob().getJobStatusAndTracking().getCompleted()) { em.getTransaction().begin(); Alert alert = Alert.findFirstAlertByOwnerId(em, getCurrentJob().getId()); if (alert == null) { // This seems to be a new job alert = new Alert(getCurrentJob().getId(), new Date(), "Job saved"); em.persist(alert); } else { em.refresh(alert); alert.setActive(true); alert.setDueTime(new Date()); alert.setStatus("Job saved"); } em.getTransaction().commit(); } } public void sendErrorEmail(String subject, String message) { try { // Send error message to developer's email Utils.postMail(null, null, null, subject, message, "text/plain", getEntityManager1()); } catch (Exception ex) { System.out.println(ex); } } public void deleteCostComponent() { deleteCostComponentByName(selectedCostComponent.getName()); } // Remove this and other code out of JobManager? Put in JobCostingAndPayment or Job? public void deleteCostComponentByName(String componentName) { List<CostComponent> components = getCurrentJob().getJobCostingAndPayment().getAllSortedCostComponents(); int index = 0; for (CostComponent costComponent : components) { if (costComponent.getName().equals(componentName)) { components.remove(index); setJobCostingAndPaymentDirty(true); break; } ++index; } updateFinalCost(); updateAmountDue(); } public void editCostComponent(ActionEvent event) { setEdit(true); } public void createNewCashPayment(ActionEvent event) { if (getCurrentJob().getId() != null) { selectedCashPayment = new CashPayment(); // If there were other payments it is assumed that this is a final payment. // Otherwsie, it is assumed to be a deposit. if (getCurrentJob().getJobCostingAndPayment().getCashPayments().size() > 0) { selectedCashPayment.setPaymentPurpose("Final"); } else { selectedCashPayment.setPaymentPurpose("Deposit"); } PrimeFacesUtils.openDialog(null, "/job/finance/cashPaymentDialog", true, true, true, 350, 500); } else { PrimeFacesUtils.addMessage("Job NOT Saved", "Job must be saved before a new payment can be added", FacesMessage.SEVERITY_WARN); } } public void editCashPayment(ActionEvent event) { PrimeFacesUtils.openDialog(null, "/job/finance/cashPaymentDialog", true, true, true, 350, 500); } public void createNewCostComponent(ActionEvent event) { selectedCostComponent = new CostComponent(); setEdit(false); } public void cancelCashPaymentEdit() { selectedCashPayment.setIsDirty(false); PrimeFaces.current().dialog().closeDynamic(null); } public void cancelCostComponentEdit() { selectedCostComponent.setIsDirty(false); } public void cashPaymentDialogReturn() { if (getCurrentJob().getId() != null) { if (isJobCostingAndPaymentDirty()) { if (getCurrentJob().prepareAndSave(getEntityManager1(), getUser()).isSuccess()) { PrimeFacesUtils.addMessage("Payment and Job Saved", "Payment and the job and the payment were saved", FacesMessage.SEVERITY_INFO); } } } } /** * * @return */ public Boolean getIsJobCompleted() { if (getCurrentJob() != null) { return getCurrentJob().getJobStatusAndTracking().getCompleted(); } else { return false; } } public void okCostingComponent() { if (selectedCostComponent.getId() == null && !getEdit()) { getCurrentJob().getJobCostingAndPayment().getCostComponents().add(selectedCostComponent); } setEdit(false); updateFinalCost(); updateAmountDue(); PrimeFaces.current().executeScript("PF('costingComponentDialog').hide();"); } public void updateFinalCost() { getCurrentJob().getJobCostingAndPayment().setFinalCost(getCurrentJob().getJobCostingAndPayment().getTotalJobCostingsAmount()); setJobCostingAndPaymentDirty(true); } public void updateTotalCost() { updateAmountDue(); } public void updateAmountDue() { setJobCostingAndPaymentDirty(true); } public Boolean getCanApplyTax() { return JobCostingAndPayment.getCanApplyTax(getCurrentJob()) && getCanEditJobCosting(); } public void openJobCostingDialog() { if (getCurrentJob().getId() != null && !getCurrentJob().getIsDirty()) { // Reload cash payments if possible to avoid overwriting them // when saving EntityManager em = getEntityManager1(); JobCostingAndPayment jcp = JobCostingAndPayment.findJobCostingAndPaymentById(em, getCurrentJob().getJobCostingAndPayment().getId()); em.refresh(jcp); getCurrentJob().getJobCostingAndPayment().setCashPayments(jcp.getCashPayments()); PrimeFacesUtils.openDialog(null, "/job/finance/jobCostingDialog", true, true, true, 600, 850); } else { PrimeFacesUtils.addMessage("Job NOT Saved", "Job must be saved before the job costing can be viewed or edited", FacesMessage.SEVERITY_WARN); PrimeFaces.current().executeScript("PF('longProcessDialogVar').hide();"); } } public void editJobCosting() { PrimeFacesUtils.openDialog(null, "jobCostingDialog", true, true, true, 600, 850); } public void okCashPayment() { if (getSelectedCashPayment().getId() == null) { getCurrentJob().getJobCostingAndPayment().getCashPayments().add(selectedCashPayment); } updateFinalCost(); updateAmountDue(); PrimeFaces.current().dialog().closeDynamic(null); } public List<JobCostingAndPayment> completeJobCostingAndPaymentName(String query) { EntityManager em; try { em = getEntityManager1(); List<JobCostingAndPayment> results = JobCostingAndPayment.findAllJobCostingAndPaymentsByDepartmentAndName(em, getUser().getEmployee().getDepartment().getName(), query); return results; } catch (Exception e) { System.out.println(e); return new ArrayList<>(); } } public List<String> completeAccPacClientName(String query) { EntityManager em2; try { em2 = getEntityManager2(); List<AccPacCustomer> clients = AccPacCustomer.findAllByName(em2, query); List<String> suggestions = new ArrayList<>(); for (AccPacCustomer client : clients) { suggestions.add(client.getCustomerName()); } return suggestions; } catch (Exception e) { System.out.println(e); return new ArrayList<>(); } } // tk use the one in ClientManager? public List<AccPacCustomer> completeAccPacClient(String query) { EntityManager em2; try { em2 = getEntityManager2(); return AccPacCustomer.findAllByName(em2, query); } catch (Exception e) { System.out.println(e); return new ArrayList<>(); } } public List<CostCode> getAllCostCodes() { EntityManager em = getEntityManager1(); List<CostCode> codes = CostCode.findAllCostCodes(em); return codes; } public List<Job> getAllSubcontracts() { List<Job> subcontracts = new ArrayList<>(); if (getCurrentJob().getId() != null) { if (!getCurrentJob().findSubcontracts(getEntityManager1()).isEmpty()) { subcontracts.addAll(getCurrentJob().findSubcontracts(getEntityManager1())); } else { subcontracts.addAll(getCurrentJob().findPossibleSubcontracts(getEntityManager1())); } subcontracts.add(0, new Job("-- select a subcontract --")); } else { subcontracts.add(0, new Job("-- none exists --")); } return subcontracts; } private EntityManagerFactory getEMF2() { return EMF2; } public Job getCurrentJob() { return getJobManager().getCurrentJob(); } @Override public void setIsDirty(Boolean dirty) { getCurrentJob().setIsDirty(dirty); } @Override public Boolean getIsDirty() { return getCurrentJob().getIsDirty(); } public void setJobCostingAndPaymentDirty(Boolean dirty) { getCurrentJob().getJobCostingAndPayment().setIsDirty(dirty); if (dirty) { getCurrentJob().getJobStatusAndTracking().setEditStatus("(edited)"); } else { getCurrentJob().getJobStatusAndTracking().setEditStatus(""); } } public void setJobCostingAndPaymentDirty(Job job, Boolean dirty) { job.getJobCostingAndPayment().setIsDirty(dirty); if (dirty) { job.getJobStatusAndTracking().setEditStatus("(edited)"); } else { job.getJobStatusAndTracking().setEditStatus(""); } } public Boolean isJobCostingAndPaymentDirty() { return getCurrentJob().getJobCostingAndPayment().getIsDirty(); } public void updateCurrentUnitCostDepartment() { EntityManager em; try { em = getEntityManager1(); if (currentUnitCost.getDepartment().getName() != null) { Department department = Department.findDepartmentByName(em, currentUnitCost.getDepartment().getName()); if (department != null) { currentUnitCost.setDepartment(department); setIsDirty(true); } } } catch (Exception e) { System.out.println(e); } } public void updateCurrentUnitCostDepartmentUnit() { EntityManager em; try { em = getEntityManager1(); if (currentUnitCost.getDepartmentUnit().getName() != null) { DepartmentUnit departmentUnit = DepartmentUnit.findDepartmentUnitByName(em, currentUnitCost.getDepartmentUnit().getName()); if (departmentUnit != null) { currentUnitCost.setDepartmentUnit(departmentUnit); setIsDirty(true); } } } catch (Exception e) { System.out.println(e); } } public void updateCurrentUnitCostDepartmentLab() { EntityManager em; try { em = getEntityManager1(); if (currentUnitCost.getLaboratory().getName() != null) { Laboratory laboratory = Laboratory.findLaboratoryByName(em, currentUnitCost.getLaboratory().getName()); if (laboratory != null) { currentUnitCost.setLaboratory(laboratory); setIsDirty(true); } } } catch (Exception e) { System.out.println(e); } } public void updateUnitCostDepartment() { EntityManager em; try { em = getEntityManager1(); if (unitCostDepartment.getName() != null) { Department department = Department.findDepartmentByName(em, unitCostDepartment.getName()); if (department != null) { unitCostDepartment = department; //doUnitCostSearch(); } } } catch (Exception e) { System.out.println(e); } } public void updateJobCostDepartment() { EntityManager em; try { em = getEntityManager1(); if (jobCostDepartment.getName() != null) { Department department = Department.findDepartmentByName(em, jobCostDepartment.getName()); if (department != null) { jobCostDepartment = department; //doUnitCostSearch(); } } } catch (Exception e) { System.out.println(e); } } public void updateAccPacClient() { setShowPrepayments(false); filteredAccPacCustomerDocuments = new ArrayList<>(); try { if (getCurrentJob() != null) { if (!getCurrentJob().getClient().getName().equals("")) { accPacCustomer.setCustomerName(getCurrentJob().getClient().getName()); } else { accPacCustomer.setCustomerName("?"); } updateCreditStatus(null); } } catch (Exception e) { System.out.println(e); } } public void updateAccPacCustomer(SelectEvent event) { if (accPacCustomer != null) { try { EntityManager em = getEntityManager2(); accPacCustomer = AccPacCustomer.findByName(em, accPacCustomer.getCustomerName()); if (accPacCustomer == null) { accPacCustomer = new AccPacCustomer(); accPacCustomer.setCustomerName(""); } // set the found client name to the present job client if (accPacCustomer.getCustomerName() != null) { updateCreditStatus(null); } } catch (Exception e) { System.out.println(e); accPacCustomer = new AccPacCustomer(); accPacCustomer.setCustomerName(""); } } } public Integer getNumberOfFilteredAccPacCustomerDocuments() { if (filteredAccPacCustomerDocuments != null) { return filteredAccPacCustomerDocuments.size(); } return 0; } public Boolean getFilteredDocumentAvailable() { if (filteredAccPacCustomerDocuments != null) { return !filteredAccPacCustomerDocuments.isEmpty(); } else { return false; } } public void updateCreditStatusSearch() { accPacCustomer.setCustomerName(getCurrentJob().getClient().getName()); updateCreditStatus(null); } public void updateCreditStatus(SelectEvent event) { EntityManager em = getEntityManager2(); accPacCustomer = AccPacCustomer.findByName(em, accPacCustomer.getCustomerName().trim()); if (accPacCustomer != null) { if (getShowPrepayments()) { filteredAccPacCustomerDocuments = AccPacDocument.findAccPacInvoicesDueByCustomerId(em, accPacCustomer.getIdCust(), true); } else { filteredAccPacCustomerDocuments = AccPacDocument.findAccPacInvoicesDueByCustomerId(em, accPacCustomer.getIdCust(), false); } } else { createNewAccPacCustomer(); } } public void updateCreditStatus() { updateCreditStatus(null); } public void createNewAccPacCustomer() { if (accPacCustomer != null) { accPacCustomer = new AccPacCustomer(accPacCustomer.getCustomerName()); } else { accPacCustomer = new AccPacCustomer(null); } accPacCustomer.setIdCust(null); filteredAccPacCustomerDocuments = new ArrayList<>(); } public String getAccPacCustomerID() { if (accPacCustomer.getIdCust() == null) { return ""; } else { return accPacCustomer.getIdCust(); } } public String getAccPacCustomerName() { if (accPacCustomer.getCustomerName() == null) { return "{Not found}"; } else { return accPacCustomer.getCustomerName(); } } public String getCustomerType() { if (accPacCustomer.getIDACCTSET().equals("TRADE") && accPacCustomer.getCreditLimit().doubleValue() > 0.0) { return "CREDIT"; } else { return "REGULAR"; } } public AccPacCustomer getAccPacCustomer() { return accPacCustomer; } public void setAccPacCustomer(AccPacCustomer accPacCustomer) { this.accPacCustomer = accPacCustomer; } public void updateCostingComponents() { if (selectedJobCostingTemplate != null) { EntityManager em = getEntityManager1(); JobCostingAndPayment jcp = JobCostingAndPayment.findJobCostingAndPaymentByDepartmentAndName(em, getUser().getEmployee().getDepartment().getName(), selectedJobCostingTemplate); if (jcp != null) { getCurrentJob().getJobCostingAndPayment().getCostComponents().clear(); getCurrentJob().getJobCostingAndPayment().setCostComponents(copyCostComponents(jcp.getCostComponents())); setJobCostingAndPaymentDirty(true); } else { // Nothing yet } selectedJobCostingTemplate = null; } } public void removeCurrentJobCostingComponents(EntityManager em) { if (!getCurrentJob().getJobCostingAndPayment().getCostComponents().isEmpty()) { em.getTransaction().begin(); for (CostComponent costComponent : getCurrentJob().getJobCostingAndPayment().getCostComponents()) { if (costComponent.getId() != null) { costComponent = em.find(CostComponent.class, costComponent.getId()); em.remove(costComponent); } } getCurrentJob().getJobCostingAndPayment().getCostComponents().clear(); BusinessEntityUtils.saveBusinessEntity(em, getCurrentJob().getJobCostingAndPayment()); em.getTransaction().commit(); } } /* * Takes a list of job costings enties an set their ids and component ids * to null which will result in new job costings being created when * the job costins are commited to the database */ public List<JobCosting> copyJobCostings(List<JobCosting> srcCostings) { ArrayList<JobCosting> newJobCostings = new ArrayList<>(); for (JobCosting jobCosting : srcCostings) { JobCosting newJobCosting = new JobCosting(jobCosting); for (CostComponent costComponent : jobCosting.getCostComponents()) { CostComponent newCostComponent = new CostComponent(costComponent); newJobCosting.getCostComponents().add(newCostComponent); } newJobCostings.add(newJobCosting); } return newJobCostings; } public List<CostComponent> copyCostComponents(List<CostComponent> srcCostComponents) { ArrayList<CostComponent> newCostComponents = new ArrayList<>(); for (CostComponent costComponent : srcCostComponents) { CostComponent newCostComponent = new CostComponent(costComponent); newCostComponents.add(newCostComponent); } return newCostComponents; } // public Date getCurrentDate() { // return new Date(); // } public Long saveCashPayment(EntityManager em, CashPayment cashPayment) { return BusinessEntityUtils.saveBusinessEntity(em, cashPayment); } public List<CashPayment> getCashPaymentsByJobId(EntityManager em, Long jobId) { try { List<CashPayment> cashPayments = em.createQuery("SELECT c FROM CashPayment c " + "WHERE c.jobId " + "= '" + jobId + "'", CashPayment.class).getResultList(); return cashPayments; } catch (Exception e) { System.out.println(e); return null; } } public void deleteCashPayment() { List<CashPayment> payments = getCurrentJob().getJobCostingAndPayment().getCashPayments(); for (CashPayment payment : payments) { if (payment.equals(selectedCashPayment)) { payments.remove(selectedCashPayment); break; } } updateFinalCost(); updateAmountDue(); // Do job save if possible... if (getCurrentJob().getId() != null && getCurrentJob().prepareAndSave(getEntityManager1(), getUser()).isSuccess()) { PrimeFacesUtils.addMessage("Job Saved", "The payment was deleted and the job was saved", FacesMessage.SEVERITY_INFO); } else { setJobCostingAndPaymentDirty(true); PrimeFacesUtils.addMessage("Job NOT Saved", "The payment was deleted but the job was not saved", FacesMessage.SEVERITY_WARN); } PrimeFaces.current().dialog().closeDynamic(null); } public void checkForSubcontracts(ActionEvent event) { //PrimeFacesUtils.openDialog(null, "/job/finance/cashPaymentDeleteConfirmDialog", true, true, true, 110, 375); } public void openCashPaymentDeleteConfirmDialog(ActionEvent event) { PrimeFacesUtils.openDialog(null, "/job/finance/cashPaymentDeleteConfirmDialog", true, true, true, 110, 375); } public void closeJCashPaymentDeleteConfirmDialog() { PrimeFaces.current().dialog().closeDynamic(null); } public void openJobPricingsDialog() { PrimeFacesUtils.openDialog(null, "jobPricings", true, true, true, 600, 800); } public void openJobCostingsDialog() { PrimeFacesUtils.openDialog(null, "jobCostings", true, true, true, 600, 800); } public void doJobCostSearch() { System.out.println("To be implemented"); } public void createNewUnitCost() { currentUnitCost = new UnitCost(); PrimeFaces.current().ajax().update("unitCostForm"); PrimeFaces.current().executeScript("PF('unitCostDialog').show();"); } public void editUnitCost() { } @Override public void handleDialogOkButtonClick() { } @Override public void handleDialogYesButtonClick() { if (dialogActionHandlerId.equals("unitCostDirty")) { saveUnitCost(); PrimeFaces.current().executeScript("PF('unitCostDialog').hide();"); } } @Override public void handleDialogNoButtonClick() { if (dialogActionHandlerId.equals("unitCostDirty")) { setIsDirty(false); PrimeFaces.current().executeScript("PF('unitCostDialog').hide();"); } } @Override public DialogActionHandler initDialogActionHandlerId(String id) { dialogActionHandlerId = id; return this; } @Override public String getDialogActionHandlerId() { return dialogActionHandlerId; } @Override public void handleDialogCancelButtonClick() { } public void onJobCostingsTableCellEdit(CellEditEvent event) { System.out.println("Job number of costing: " + getJobsWithCostings().get(event.getRowIndex()).getJobNumber()); } /** * This is to be implemented further * * @return */ public Boolean getDisableSubContracting() { try { if (getCurrentJob().getIsSubContract() || getCurrentJob().getIsToBeCopied()) { return false; } else { return getCurrentJob().getId() == null; } } catch (Exception e) { System.out.println(e); } return false; } public List<String> getDepartmentSupervisorsEmailAddresses(Department department) { List<String> emails = new ArrayList<>(); emails.add(getEmployeeDefaultEmailAdress(department.getHead())); // Get the email of the acting head of he/she is currently acting if (department.getActingHeadActive()) { emails.add(getEmployeeDefaultEmailAdress(department.getActingHead())); } return emails; } public String getEmployeeDefaultEmailAdress(Employee employee) { String address = ""; // Get email1 which is treated as the employee's company email address if (!employee.getInternet().getEmail1().trim().equals("")) { address = employee.getInternet().getEmail1(); } else { // Get and set default email using company domain EntityManager em = getEntityManager1(); String listAsString = (String) SystemOption.getOptionValueObject(em, "domainNames"); String domainNames[] = listAsString.split(";"); JobManagerUser user1 = JobManagerUser.findActiveJobManagerUserByEmployeeId(em, employee.getId()); // Build email address if (user1 != null) { address = user1.getUsername(); if (domainNames.length > 0) { address = address + "@" + domainNames[0]; } } } return address; } public Boolean isCurrentJobNew() { return (getCurrentJob().getId() == null); } public Department getDepartmentBySystemOptionDeptId(String option) { EntityManager em = getEntityManager1(); Long id = (Long) SystemOption.getOptionValueObject(em, option); Department department = Department.findDepartmentById(em, id); em.refresh(department); if (department != null) { return department; } else { return new Department(""); } } public Boolean getIsMemberOfAccountsDept() { return getUser().getEmployee().isMemberOf(getDepartmentBySystemOptionDeptId("accountsDepartmentId")); } public Boolean getIsMemberOfCustomerServiceDept() { return getUser().getEmployee().isMemberOf(getDepartmentBySystemOptionDeptId("customerServiceDeptId")); } /** * Return discount types. NB: Discount types to be obtained from System * Options in the future * * @param query * @return */ public List<String> completeDiscountType(String query) { String discountTypes[] = {"Currency", "Percentage"}; List<String> matchedDiscountTypes = new ArrayList<>(); for (String discountType : discountTypes) { if (discountType.contains(query)) { matchedDiscountTypes.add(discountType); } } return matchedDiscountTypes; } }
General updates.
src/main/java/jm/com/dpbennett/jmts/managers/JobFinanceManager.java
General updates.
Java
agpl-3.0
5cf5454e6eac217c46b537d0cd5ce0a39090379f
0
jwillia/kc-old1,iu-uits-es/kc,geothomasp/kcmit,kuali/kc,geothomasp/kcmit,UniversityOfHawaiiORS/kc,UniversityOfHawaiiORS/kc,geothomasp/kcmit,mukadder/kc,ColostateResearchServices/kc,kuali/kc,geothomasp/kcmit,jwillia/kc-old1,UniversityOfHawaiiORS/kc,jwillia/kc-old1,mukadder/kc,ColostateResearchServices/kc,ColostateResearchServices/kc,jwillia/kc-old1,iu-uits-es/kc,iu-uits-es/kc,mukadder/kc,kuali/kc,geothomasp/kcmit
/* * Copyright 2006-2008 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kra.infrastructure; public interface Constants { public static final String KRA_SESSION_KEY = "kra.session"; public static final String APP_CONTEXT_KEY = "app.context.name"; public static final String DATASOURCE = "kraDataSource"; public static final String DATA_DICTIONARY_SERVICE_NAME = "dataDictionaryService"; public static final String BUSINESS_OBJECT_DICTIONARY_SERVICE_NAME = "businessObjectDictionaryService"; public static final String DATE_TIME_SERVICE_NAME = "dateTimeService"; public static final String BUSINESS_OBJECT_DAO_NAME = "businessObjectDao"; public static final String HTML_FORM_ACTION = "htmlFormAction"; public static final String TEXT_AREA_FIELD_NAME = "textAreaFieldName"; public static final String TEXT_AREA_FIELD_LABEL = "textAreaFieldLabel"; public static final String TEXT_AREA_FIELD_ANCHOR = "textAreaFieldAnchor"; public static final Integer APPROVAL_STATUS = 2; public static final String MAINTENANCE_NEW_ACTION = "New"; public static final String KEY_PERSON_ROLE = "KP"; public static final String PRINCIPAL_INVESTIGATOR_ROLE = "PI"; public static final String CO_INVESTIGATOR_ROLE = "COI"; public static final String MULTIPLE_VALUE = "multipleValues"; public static final String KEYWORD_PANEL_DISPLAY = "proposaldevelopment.displayKeywordPanel"; public static final String MAPPING_BASIC = "basic"; public static final String MAPPING_ERROR = "error"; public static final String MAPPING_PROPOSAL_ACTIONS = "actions"; public static final String NEW_PROPOSAL_PERSON_PROPERTY_NAME = "newProposalPerson"; public static final String NEW_PERSON_LOOKUP_FLAG = "newPersonLookupFlag"; public static final String MAPPING_CLOSE_PAGE = "closePage"; public static final String MAPPING_NARRATIVE_ATTACHMENT_RIGHTS_PAGE = "attachmentRights"; public static final String MAPPING_INSTITUTE_ATTACHMENT_RIGHTS_PAGE = "instituteAttachmentRights"; public static final String CREDIT_SPLIT_ENABLED_RULE_NAME = "proposaldevelopment.creditsplit.enabled"; public static final String CREDIT_SPLIT_ENABLED_FLAG = "creditSplitEnabledFlag"; public static final String NARRATIVE_MODULE_NUMBER = "proposalDevelopment.narrative.moduleNumber"; public static final String NARRATIVE_MODULE_SEQUENCE_NUMBER = "proposalDevelopment.narrative.moduleSequenceNumber"; public static final String PROP_PERSON_BIO_NUMBER = "proposalDevelopment.proposalPersonBiography.biographyNumber"; public static final String PROPOSAL_LOCATION_SEQUENCE_NUMBER = "proposalDevelopment.proposalLocation.locationSequenceNumber"; public static final String PROPOSAL_SPECIALREVIEW_NUMBER = "proposalDevelopment.proposalSpecialReview.specialReviewNumber"; public static final String PROPOSAL_PERSON_DEGREE_SEQUENCE_NUMBER = "proposalDevelopment.proposalPerson.degree.degreeSequenceNumber"; public static final String PROPOSAL_PERSON_NUMBER = "proposalDevelopment.proposalPerson.proposalPersonNumber"; public static final String PROPOSAL_NARRATIVE_TYPE_GROUP = "proposalNarrativeTypeGroup"; public static final String INSTITUTE_NARRATIVE_TYPE_GROUP = "instituteNarrativeTypeGroup"; public static final String INSTITUTIONAL_ATTACHMENT_TYPE_NAME = "Institutional Attachment"; public static final String PERSONNEL_ATTACHMENT_TYPE_NAME = "Personnel Attachment"; public static final String PROPOSAL_ATTACHMENT_TYPE_NAME = "Proposal Attachment"; public static final String NEW_NARRATIVE_USER_RIGHTS_PROPERTY_KEY = "newNarrativeUserRight"; public static final String PROPOSAL_PERSON_ROLE_PARAMETER_PREFIX = "proposaldevelopment.personrole."; public static final String NIH_SPONSOR_ACRONYM = "NIH"; public static final String NIH_SPONSOR_CODE = "000340"; public static final String SPONSOR_LEVEL_HIERARCHY = "sponsorLevelHierarchy"; public static final String SPONSOR_HIERARCHY_NAME = "sponsorGroupHierarchyName"; public static final String PARAMETER_MODULE_PROTOCOL = "KC-PROTOCOL"; public static final String PARAMETER_MODULE_PROTOCOL_REFERENCEID1 = "irb.protocol.referenceID1"; public static final String PARAMETER_MODULE_PROTOCOL_REFERENCEID2 = "irb.protocol.referenceID2"; public static final String PARAMETER_MODULE_PROPOSAL_DEVELOPMENT = "KRA-PD"; public static final String PARAMETER_COMPONENT_DOCUMENT = "D"; public static final String INSTITUTE_NARRATIVE_TYPE_GROUP_CODE = "O"; public static final String NARRATIVE_MODULE_STATUS_COMPLETE = "C"; public static final String ABSTRACTS_PROPERTY_KEY = "newProposalAbstract"; public static final String SPONSOR_PROPOSAL_NUMBER_PROPERTY_KEY = "sponsorProposalNumber"; public static final String DEADLINE_DATE_KEY = "document.deadlineDate"; public static final String PROJECT_TITLE_KEY = "document.title"; public static final String SPONSOR_PROPOSAL_NUMBER_LABEL = "Sponsor Proposal ID"; public static final String AUDIT_ERRORS = "Validation Errors"; public static final String AUDIT_WARNINGS = "Warnings"; public static final String GRANTSGOV_ERRORS= "Grants.Gov Errors"; public static final String PROPOSAL_PAGE = "proposal"; public static final String CUSTOM_ATTRIBUTES_PAGE = "customData"; public static final String QUESTIONS_PAGE = "questions"; public static final String PERMISSIONS_PAGE = "permissions"; public static final String PROPOSAL_ACTIONS_PAGE = "actions"; public static final String ATTACHMENTS_PAGE = "abstractsAttachments"; public static final String SPONSOR_PROGRAM_INFORMATION_PANEL_ANCHOR = "SponsorProgramInformation"; public static final String SPONSOR_PROGRAM_INFORMATION_PANEL_NAME = "Sponsor & Program Information"; public static final String REQUIRED_FIELDS_PANEL_ANCHOR = "RequiredFieldsforSavingDocument"; public static final String REQUIRED_FIELDS_PANEL_NAME = "Required Fields for Saving Document "; public static final String BUDGET_EXPENSES_PAGE = "budgetExpenses"; public static final String BUDGET_EXPENSES_OVERVIEW_PANEL_ANCHOR = "BudgetOvervieV"; public static final String BUDGET_EXPENSES_OVERVIEW_PANEL_NAME = "Budget Overview (Period "; // Proposal Document Property Constants public static final String PROPOSAL_NUMBER = "proposalNumber"; public static final String BUDGET_VERSION_PANEL_NAME = "Budget Versions"; public static final String BUDGET_VERSION_OVERVIEWS = "budgetVersionOverviews"; // Budget Document Property Constants public static final String BUDGET_VERSION_NUMBER = "budgetVersionNumber"; // Key Personnel Mojo public static final String KEY_PERSONNEL_PAGE = "keyPersonnel"; public static final String PROPOSAL_PERSON_INVESTIGATOR = "investigator"; public static final String KEY_PERSONNEL_PANEL_ANCHOR = "KeyPersonnel"; public static final String KEY_PERSONNEL_PANEL_NAME = "Key Personnel Information"; public static final String PERSON_EDITABLE_FIELD_NAME_PROPERTY_KEY = "fieldName"; public static final String INVESTIGATOR_CREDIT_TYPE_CODE_PROPERTY_KEY = "invCreditTypeCode"; public static final String EMPTY_STRING = ""; public static final String PROPOSAL_PERSON_KEY = "document.proposalPerson*"; public static final String PRINCIPAL_INVESTIGATOR_KEY = "newProposalPerson*"; public static final String CREDIT_SPLIT_KEY = "document.creditSplit"; /* set values for ynq */ public static final Integer ANSWER_YES_NO = 2; public static final Integer ANSWER_YES_NO_NA = 3; public static final String QUESTION_TYPE_PROPOSAL = "P"; public static final String QUESTION_TYPE_INDIVIDUAL = "I"; // Investigator - Certification questions public static final String YNQ_EXPLANATION_REQUIRED = "Explanation required: if answer = "; public static final String YNQ_REVIEW_DATE_REQUIRED = "Date required: if answer = "; public static final String STATUS_ACTIVE = "A"; public static final String ANSWER_NA = "X"; public static final String DEFAULT_DATE_FORMAT_PATTERN = "MM/dd/yyyy"; public static final String PARAMETER_MODULE_BUDGET = "KRA-B"; // Budget Versions Constants public static final String BUDGET_STATUS_COMPLETE_CODE = "budgetStatusCompleteCode"; public static final String BUDGET_STATUS_INCOMPLETE_CODE = "budgetStatusIncompleteCode"; public static final String PROPOSAL_BUDGET_VERSION_NUMBER = "proposalDevelopment.budget.versionNumber"; public static final String BUDGET_DEFAULT_OVERHEAD_RATE_CODE = "defaultOverheadRateClassCode"; public static final String BUDGET_DEFAULT_OVERHEAD_RATE_TYPE_CODE = "defaultOverheadRateTypeCode"; public static final String BUDGET_DEFAULT_UNDERRECOVERY_RATE_CODE = "defaultUnderrecoveryRateClassCode"; public static final String BUDGET_DEFAULT_MODULAR_FLAG = "defaultModularFlag"; // Budget Distribution And Income public static final String BUDGET_CURRENT_FISCAL_YEAR = "budgetCurrentFiscalYear"; public static final String BUDGET_COST_SHARING_APPLICABILITY_FLAG = "budgetCostSharingApplicabilityFlag"; public static final String BUDGET_UNRECOVERED_F_AND_A_APPLICABILITY_FLAG = "budgetUnrecoveredFandAApplicabilityFlag"; // Budget Personnel public static final String BUDGET_PERSON_DEFAULT_JOB_CODE = "budgetPersonDefaultJobCode"; public static final String BUDGET_PERSON_DEFAULT_APPOINTMENT_TYPE = "budgetPersonDefaultAppointmentType"; public static final String BUDGET_PERSON_DEFAULT_PERIOD_TYPE = "budgetPersonDefaultPeriodType"; public static final String BUDGET_PERSON_DEFAULT_CALCULATION_BASE = "budgetPersonDefaultCalculationBase"; public static final String BUDGET_PERSON_DEFAULT_EFFECTIVE_DATE = "budgetPersonDefaultEffectiveDate"; public static final String PERSON_SEQUENCE_NUMBER = "personSequenceNumber"; public static final String BUDGET_PERSONNEL_PAGE = "personnel"; public static final String JOB_CODE = "jobCode"; // KIM Authorization Namespace for KRA public static final String KRA_NAMESPACE = "KRA"; // Key Permissions Info public static final String CONFIRM_DELETE_PROPOSAL_USER_KEY = "confirmDeleteProposalUser"; public static final String PERMISSION_PROPOSAL_USERS_PROPERTY_KEY = "newProposalUser"; public static final String EDIT_ROLES_PROPERTY_KEY = "proposalUserEditRole"; public static final String PERMISSIONS_EDIT_ROLES_PROPERTY_KEY = "permissionsUserEditRole"; public static final String MAPPING_PERMISSIONS_ROLE_RIGHTS_PAGE = "permissionsRoleRights"; public static final String MAPPING_PERMISSIONS_EDIT_ROLES_PAGE = "permissionsEditRoles"; public static final String MAPPING_PERMISSIONS_CLOSE_EDIT_ROLES_PAGE = "permissionsCloseEditRoles"; // Permission constants public static final String PERMISSION_USERS_PROPERTY_KEY = "newPermissionsUser"; // Task Authorization public static final String TASK_AUTHORIZATION = "taskAuthorization"; //Budget Rates public static final String ON_CAMUS_FLAG = "N"; public static final String OFF_CAMUS_FLAG = "F"; public static final String DEFALUT_CAMUS_FLAG = "D"; //Budget Expenses public static final String BUDGET_LINEITEM_NUMBER = "budget.budgetLineItem.lineItemNumber"; public static final String BUDGET_EXPENSE_LOOKUP_MESSAGE1 = "budget.expense.lookup.message1"; public static final String BUDGET_EXPENSE_LOOKUP_MESSAGE2 = "budget.expense.lookup.message2"; public static final String PERCENT_EFFORT_FIELD = "Percent Effort"; public static final String PERCENT_CHARGED_FIELD = "Percent Charged"; //Grants.gov public static final String S2S_SUBMISSIONTYPE_CODE_KEY="document.s2sOpportunity.s2sSubmissionTypeCode"; public static final String GRANTS_GOV_PANEL_ANCHOR = "Opportunity"; public static final String GRANTS_GOV_OPPORTUNITY_PANEL = "GrantsGov"; public static final String OPPORTUNITY_ID_KEY="document.programAnnouncementNumber"; public static final String OPPORTUNITY_TITLE_KEY="document.programAnnouncementTitle"; public static final String CFDA_NUMBER_KEY="document.cfdaNumber"; public static final String GRANTS_GOV_PAGE = "grantsGov"; public static final String ORIGINAL_PROPOSAL_ID_KEY = "document.sponsorProposalNumber"; public static final String CFDA_NUMBER = "cfdaNumber"; public static final String OPPORTUNITY_ID= "opportunityId"; public static final String NO_FIELD= "noField"; public static final String GRANTS_GOV_LINK="message.grantsgov.link"; public static final String GRANTS_GOV_GENERIC_ERROR_KEY= "error.grantsgov.schemavalidation.generic.errorkey"; public static final String GRANTS_GOV_SUBMISSION_SUCCESSFUL_MESSAGE = "message.grantsGov.submission.successful"; // custom attribute public static final String CUSTOM_ATTRIBUTE_ID = "customAttributeId"; public static final String DOCUMENT_NEWMAINTAINABLEOBJECT_ACTIVE = "document.newMaintainableObject.active"; public static final String DOCUMENT_NEWMAINTAINABLEOBJECT_LOOKUPRETURN = "document.newMaintainableObject.lookupReturn"; public static final String LOOKUP_RETURN_FIELDS = "lookupReturnFields"; public static final String LOOKUP_CLASS_NAME = "lookupClassName"; public static final String MAPPING_PERSONNEL_BUDGET = "personnelBudget"; public static final String MAPPING_EXPENSES_BUDGET = "expenses"; public static final String BUDGET_PERSON_LINE_NUMBER = "budget.budgetPersonnelDetails.personNumber"; public static final String BUDGET_PERSON_LINE_SEQUENCE_NUMBER = "budget.budgetPersonnelDetails.sequenceNumber"; public static final String DATA_TYPE_STRING = "String - Any Character"; public static final String DATA_TYPE_NUMBER = "Number - [0-9]"; public static final String DATA_TYPE_DATE = "Date - [xx/xx/xxxx]"; // Change Password public static final String CHANGE_PASSWORD_PROPERTY_KEY = "changePassword"; public static final String TRUE_FLAG = "Y"; public static final String FALSE_FLAG = "N"; public static final String PROPOSAL_SPECIAL_REVIEW_KEY = "document.proposalSpecialReview*"; public static final String SPECIAL_REVIEW_PAGE = "specialReview"; public static final String SPECIAL_REVIEW_PANEL_ANCHOR = "SpecialReview"; public static final String SPECIAL_REVIEW_PANEL_NAME = "Special Review Information"; public static final String BUDGET_PERIOD_PANEL_NAME = "Budget Period And Totals Information"; public static final String BUDGET_RATE_PANEL_NAME = "Budget Rate"; public static final String BUDGET_PERIOD_PAGE = "summary"; public static final String BUDGET_RATE_PAGE = "budgetRate"; public static final String BUDGET_VERSIONS_PAGE = "budgetVersions"; public static final String PD_BUDGET_VERSIONS_PAGE = "budgetVersions"; public static final String BUDGET_PERIOD_PANEL_ANCHOR = "BudgetPeriodsAmpTotals"; public static final String BUDGET_RATE_PANEL_ANCHOR = "BudgetProposalRate"; public static final String BUDGET_VERSIONS_PANEL_ANCHOR = "BudgetVersions"; public static final String BUDGET_PERIOD_KEY = "document.budgetPeriod*"; // Copy proposal public static final String COPY_PROPOSAL_PROPERTY_KEY = "copyProposal"; public static final String MAPPING_COPY_PROPOSAL_PAGE = "copyProposal"; public static final String HEADER_TAB = "headerTab"; public static final String ON_OFF_CAMPUS_FLAG = "onOffCampusFlag"; // Budget Rates public static final int APPLICABLE_RATE_PRECISION = 3; public static final int APPLICABLE_RATE_SCALE = 2; public static final String APPLICABLE_RATE_LIMIT = "999.99"; public static final String APPLICABLE_RATE_DECIMAL_CHAR = "."; // Modular Budget public static final String PARAMETER_FNA_COST_ELEMENTS = "consortiumFnaCostElements"; public static final String PARAMETER_FNA_RATE_CLASS_TYPE = "fnaRateClassTypeCode"; public static final String PROPOSALDATA_OVERRIDE_PROPERTY_KEY = "newProposalChangedData"; public static final String PROPOSALDATA_CHANGED_VAL_KEY = "newProposalChangedData.changedValue"; public static final String PROPOSALDATA_DISPLAY_VAL_KEY = "newProposalChangedData.displayValue"; public static final String PROPOSALDATA_CURRENT_DISPLAY_KEY = "newProposalChangedData.oldDisplayValue"; public static final String PROPOSALDATA_COMMENTS_KEY = "newProposalChangedData.comments"; public static final String BUDGET_SALARY_REPORT = "ProposalBudget/Salaries"; public static final String PERSONNEL_BUDGET_PANEL_NAME = "Personnel Budget"; public static final String INITIAL_UNIT_HIERARCHY_LOAD_DEPTH = "initialUnitLoadDepth"; public static final String NUMBER_PER_SPONSOR_HIERARCHY_GROUP = "numberPerSponsorHierarchyGroup"; public static final String PROPOSAL_EDITABLECOLUMN_DATATYPE = "document.newMaintainableObject.dataType"; public static final String PROPOSAL_EDITABLECOLUMN_DATALENGTH = "document.newMaintainableObject.dataLength"; public static final String PROPOSAL_EDITABLECOLUMN_LOOKUPRETURN = "document.newMaintainableObject.lookupReturn"; public static final String PDF_REPORT_CONTENT_TYPE = "application/pdf"; public static final String PDF_FILE_EXTENSION = ".pdf"; public static final String GENERIC_SPONSOR_CODE = "GENERIC_SPONSOR_CODE"; public static final String CUSTOM_ERROR = "error.custom"; public static final String SUBAWARD_FILE_REQUIERED = "newSubAward.subAwardFile.required"; public static final String SUBAWARD_FILE = "newSubAward.subAwardFile"; public static final String SUBAWARD_FILE_NOT_POPULATED = "newSubAward.subAwardFile.notExtracted"; public static final String SUBAWARD_ORG_NAME = "newSubAward.organizationName"; public static final String SUBAWARD_ORG_NAME_REQUIERED = "newSubAward.organizationName.required"; // sponsor hierarchy public static final String HIERARCHY_NAME = "hierarchyName"; public static final String SPONSOR_CODE = "sponsorCode"; public static final String SPONSOR_HIERARCHY_SEPARATOR_C1C = ";1;"; public static final String SPONSOR_HIERARCHY_SEPARATOR_P1P = "#1#"; //Award public static final String MAPPING_AWARD_BASIC = "basic"; public static final String MAPPING_AWARD_HOME_PAGE = "home"; public static final String MAPPING_AWARD_CONTACTS_PAGE = "contacts"; public static final String MAPPING_AWARD_TIME_AND_MONEY_PAGE = "timeAndMoney"; public static final String MAPPING_AWARD_PAYMENT_REPORTS_AND_TERMS_PAGE = "paymentReportsAndTerms"; public static final String MAPPING_AWARD_SPECIAL_REVIEW_PAGE = "specialReview"; public static final String MAPPING_AWARD_CUSTOM_DATA_PAGE = "customData"; public static final String MAPPING_AWARD_QUESTIONS_PAGE = "questions"; public static final String MAPPING_AWARD_PERMISSIONS_PAGE = "permissions"; public static final String MAPPING_AWARD_NOTES_AND_ATTACHMENTS_PAGE = "notesAndAttachments"; public static final String MAPPING_AWARD_ACTIONS_PAGE = "awardActions"; public static final Integer COST_SHARE_COMMENT_TYPE_CODE = 9; public static final Integer FANDA_RATE_COMMENT_TYPE_CODE = 8; public static final Integer PREAWARD_SPONSOR_AUTHORIZATION_COMMENT_TYPE_CODE = 18; public static final Integer PREAWARD_INSTITUTIONAL_AUTHORIZATION_COMMENT_TYPE_CODE = 19; public static final Integer BENEFITS_RATES_COMMENT_TYPE_CODE = 20; public static final Integer MIN_FISCAL_YEAR = 1900; public static final Integer MAX_FISCAL_YEAR = 2499; public static final String PARAMETER_MODULE_AWARD = "KC-AWARD"; public static final String SPECIAL_REVIEW_NUMBER = "SPECIAL_REVIEW_NUMBER"; public static final String LEFT_SQUARE_BRACKET = "["; public static final String RIGHT_SQUARE_BRACKET = "]"; public static final String REPORT_CLASSES_KEY_FOR_INITIALIZE_OBJECTS = "reportClasses"; public static final String NEW_AWARD_REPORT_TERMS_LIST_KEY_FOR_INITIALIZE_OBJECTS = "newAwardReportTermList"; public static final String NEW_AWARD_REPORT_TERM_RECIPIENTS_LIST_KEY_FOR_INITIALIZE_OBJECTS = "newAwardReportTermRecipientsList"; public static final String REPORT_CLASS_FOR_PAYMENTS_AND_INVOICES_PANEL = "reportClassForPaymentsAndInvoicesPanel"; // IRB public static final String PARTICIPANTS_PROPERTY_KEY = "participantsHelper.newProtocolParticipant"; public static final String DEFAULT_PROTOCOL_ORGANIZATION_TYPE_CODE = "1"; public static final String DEFAULT_PROTOCOL_ORGANIZATION_ID = "000001"; public static final String DEFAULT_PROTOCOL_STATUS_CODE = "100"; public static final String PROPERTY_PROTOCOL_STATUS = "protocolStatus"; public static final String PARAMETER_PROTOCOL_PERSON_TRAINING_SECTION = "protocolPersonTrainingSectionRequired"; public static final Integer PROTOCOL_RISK_LEVEL_COMMENT_LENGTH = 40; public static final String ACTIVE_STATUS_LITERAL = "Active"; public static final String INACTIVE_STATUS_LITERAL = "Inactive"; public static final String CONFIRM_DELETE_PROTOCOL_USER_KEY = "confirmDeleteProtocolUser"; public static final String VIEW_ONLY = "viewOnly"; // Committee public static final String COMMITTEE_PROPERTY_KEY = "committee"; public static final String CONFIRM_DELETE_PERMISSIONS_USER_KEY = "confirmDeletePermissionsUser"; }
src/main/java/org/kuali/kra/infrastructure/Constants.java
/* * Copyright 2006-2008 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kra.infrastructure; public interface Constants { public static final String KRA_SESSION_KEY = "kra.session"; public static final String APP_CONTEXT_KEY = "app.context.name"; public static final String DATASOURCE = "kraDataSource"; public static final String DATA_DICTIONARY_SERVICE_NAME = "dataDictionaryService"; public static final String BUSINESS_OBJECT_DICTIONARY_SERVICE_NAME = "businessObjectDictionaryService"; public static final String DATE_TIME_SERVICE_NAME = "dateTimeService"; public static final String BUSINESS_OBJECT_DAO_NAME = "businessObjectDao"; public static final String HTML_FORM_ACTION = "htmlFormAction"; public static final String TEXT_AREA_FIELD_NAME = "textAreaFieldName"; public static final String TEXT_AREA_FIELD_LABEL = "textAreaFieldLabel"; public static final String TEXT_AREA_FIELD_ANCHOR = "textAreaFieldAnchor"; public static final Integer APPROVAL_STATUS = 2; public static final String MAINTENANCE_NEW_ACTION = "New"; public static final String KEY_PERSON_ROLE = "KP"; public static final String PRINCIPAL_INVESTIGATOR_ROLE = "PI"; public static final String CO_INVESTIGATOR_ROLE = "COI"; public static final String MULTIPLE_VALUE = "multipleValues"; public static final String KEYWORD_PANEL_DISPLAY = "proposaldevelopment.displayKeywordPanel"; public static final String MAPPING_BASIC = "basic"; public static final String MAPPING_ERROR = "error"; public static final String MAPPING_PROPOSAL_ACTIONS = "actions"; public static final String NEW_PROPOSAL_PERSON_PROPERTY_NAME = "newProposalPerson"; public static final String NEW_PERSON_LOOKUP_FLAG = "newPersonLookupFlag"; public static final String MAPPING_CLOSE_PAGE = "closePage"; public static final String MAPPING_NARRATIVE_ATTACHMENT_RIGHTS_PAGE = "attachmentRights"; public static final String MAPPING_INSTITUTE_ATTACHMENT_RIGHTS_PAGE = "instituteAttachmentRights"; public static final String CREDIT_SPLIT_ENABLED_RULE_NAME = "proposaldevelopment.creditsplit.enabled"; public static final String CREDIT_SPLIT_ENABLED_FLAG = "creditSplitEnabledFlag"; public static final String NARRATIVE_MODULE_NUMBER = "proposalDevelopment.narrative.moduleNumber"; public static final String NARRATIVE_MODULE_SEQUENCE_NUMBER = "proposalDevelopment.narrative.moduleSequenceNumber"; public static final String PROP_PERSON_BIO_NUMBER = "proposalDevelopment.proposalPersonBiography.biographyNumber"; public static final String PROPOSAL_LOCATION_SEQUENCE_NUMBER = "proposalDevelopment.proposalLocation.locationSequenceNumber"; public static final String PROPOSAL_SPECIALREVIEW_NUMBER = "proposalDevelopment.proposalSpecialReview.specialReviewNumber"; public static final String PROPOSAL_PERSON_DEGREE_SEQUENCE_NUMBER = "proposalDevelopment.proposalPerson.degree.degreeSequenceNumber"; public static final String PROPOSAL_PERSON_NUMBER = "proposalDevelopment.proposalPerson.proposalPersonNumber"; public static final String PROPOSAL_NARRATIVE_TYPE_GROUP = "proposalNarrativeTypeGroup"; public static final String INSTITUTE_NARRATIVE_TYPE_GROUP = "instituteNarrativeTypeGroup"; public static final String INSTITUTIONAL_ATTACHMENT_TYPE_NAME = "Institutional Attachment"; public static final String PERSONNEL_ATTACHMENT_TYPE_NAME = "Personnel Attachment"; public static final String PROPOSAL_ATTACHMENT_TYPE_NAME = "Proposal Attachment"; public static final String NEW_NARRATIVE_USER_RIGHTS_PROPERTY_KEY = "newNarrativeUserRight"; public static final String PROPOSAL_PERSON_ROLE_PARAMETER_PREFIX = "proposaldevelopment.personrole."; public static final String NIH_SPONSOR_ACRONYM = "NIH"; public static final String NIH_SPONSOR_CODE = "000340"; public static final String SPONSOR_LEVEL_HIERARCHY = "sponsorLevelHierarchy"; public static final String SPONSOR_HIERARCHY_NAME = "sponsorGroupHierarchyName"; public static final String PARAMETER_MODULE_PROTOCOL = "KC-PROTOCOL"; public static final String PARAMETER_MODULE_PROTOCOL_REFERENCEID1 = "irb.protocol.referenceID1"; public static final String PARAMETER_MODULE_PROTOCOL_REFERENCEID2 = "irb.protocol.referenceID2"; public static final String PARAMETER_MODULE_PROPOSAL_DEVELOPMENT = "KRA-PD"; public static final String PARAMETER_COMPONENT_DOCUMENT = "D"; public static final String INSTITUTE_NARRATIVE_TYPE_GROUP_CODE = "O"; public static final String NARRATIVE_MODULE_STATUS_COMPLETE = "C"; public static final String ABSTRACTS_PROPERTY_KEY = "newProposalAbstract"; public static final String SPONSOR_PROPOSAL_NUMBER_PROPERTY_KEY = "sponsorProposalNumber"; public static final String DEADLINE_DATE_KEY = "document.deadlineDate"; public static final String PROJECT_TITLE_KEY = "document.title"; public static final String SPONSOR_PROPOSAL_NUMBER_LABEL = "Sponsor Proposal ID"; public static final String AUDIT_ERRORS = "Validation Errors"; public static final String AUDIT_WARNINGS = "Warnings"; public static final String GRANTSGOV_ERRORS= "Grants.Gov Errors"; public static final String PROPOSAL_PAGE = "proposal"; public static final String CUSTOM_ATTRIBUTES_PAGE = "customData"; public static final String QUESTIONS_PAGE = "questions"; public static final String PERMISSIONS_PAGE = "permissions"; public static final String PROPOSAL_ACTIONS_PAGE = "actions"; public static final String ATTACHMENTS_PAGE = "abstractsAttachments"; public static final String SPONSOR_PROGRAM_INFORMATION_PANEL_ANCHOR = "SponsorProgramInformation"; public static final String SPONSOR_PROGRAM_INFORMATION_PANEL_NAME = "Sponsor & Program Information"; public static final String REQUIRED_FIELDS_PANEL_ANCHOR = "RequiredFieldsforSavingDocument"; public static final String REQUIRED_FIELDS_PANEL_NAME = "Required Fields for Saving Document "; public static final String BUDGET_EXPENSES_PAGE = "budgetExpenses"; public static final String BUDGET_EXPENSES_OVERVIEW_PANEL_ANCHOR = "BudgetOvervieV"; public static final String BUDGET_EXPENSES_OVERVIEW_PANEL_NAME = "Budget Overview (Period "; // Proposal Document Property Constants public static final String PROPOSAL_NUMBER = "proposalNumber"; public static final String BUDGET_VERSION_PANEL_NAME = "Budget Versions"; public static final String BUDGET_VERSION_OVERVIEWS = "budgetVersionOverviews"; // Budget Document Property Constants public static final String BUDGET_VERSION_NUMBER = "budgetVersionNumber"; // Key Personnel Mojo public static final String KEY_PERSONNEL_PAGE = "keyPersonnel"; public static final String PROPOSAL_PERSON_INVESTIGATOR = "investigator"; public static final String KEY_PERSONNEL_PANEL_ANCHOR = "KeyPersonnel"; public static final String KEY_PERSONNEL_PANEL_NAME = "Key Personnel Information"; public static final String PERSON_EDITABLE_FIELD_NAME_PROPERTY_KEY = "fieldName"; public static final String INVESTIGATOR_CREDIT_TYPE_CODE_PROPERTY_KEY = "invCreditTypeCode"; public static final String EMPTY_STRING = ""; public static final String PROPOSAL_PERSON_KEY = "document.proposalPerson*"; public static final String PRINCIPAL_INVESTIGATOR_KEY = "newProposalPerson*"; public static final String CREDIT_SPLIT_KEY = "document.creditSplit"; /* set values for ynq */ public static final Integer ANSWER_YES_NO = 2; public static final Integer ANSWER_YES_NO_NA = 3; public static final String QUESTION_TYPE_PROPOSAL = "P"; public static final String QUESTION_TYPE_INDIVIDUAL = "I"; // Investigator - Certification questions public static final String YNQ_EXPLANATION_REQUIRED = "Explanation required: if answer = "; public static final String YNQ_REVIEW_DATE_REQUIRED = "Date required: if answer = "; public static final String STATUS_ACTIVE = "A"; public static final String ANSWER_NA = "X"; public static final String DEFAULT_DATE_FORMAT_PATTERN = "MM/dd/yyyy"; public static final String PARAMETER_MODULE_BUDGET = "KRA-B"; // Budget Versions Constants public static final String BUDGET_STATUS_COMPLETE_CODE = "budgetStatusCompleteCode"; public static final String BUDGET_STATUS_INCOMPLETE_CODE = "budgetStatusIncompleteCode"; public static final String PROPOSAL_BUDGET_VERSION_NUMBER = "proposalDevelopment.budget.versionNumber"; public static final String BUDGET_DEFAULT_OVERHEAD_RATE_CODE = "defaultOverheadRateClassCode"; public static final String BUDGET_DEFAULT_OVERHEAD_RATE_TYPE_CODE = "defaultOverheadRateTypeCode"; public static final String BUDGET_DEFAULT_UNDERRECOVERY_RATE_CODE = "defaultUnderrecoveryRateClassCode"; public static final String BUDGET_DEFAULT_MODULAR_FLAG = "defaultModularFlag"; // Budget Distribution And Income public static final String BUDGET_CURRENT_FISCAL_YEAR = "budgetCurrentFiscalYear"; public static final String BUDGET_COST_SHARING_APPLICABILITY_FLAG = "budgetCostSharingApplicabilityFlag"; public static final String BUDGET_UNRECOVERED_F_AND_A_APPLICABILITY_FLAG = "budgetUnrecoveredFandAApplicabilityFlag"; // Budget Personnel public static final String BUDGET_PERSON_DEFAULT_JOB_CODE = "budgetPersonDefaultJobCode"; public static final String BUDGET_PERSON_DEFAULT_APPOINTMENT_TYPE = "budgetPersonDefaultAppointmentType"; public static final String BUDGET_PERSON_DEFAULT_PERIOD_TYPE = "budgetPersonDefaultPeriodType"; public static final String BUDGET_PERSON_DEFAULT_CALCULATION_BASE = "budgetPersonDefaultCalculationBase"; public static final String BUDGET_PERSON_DEFAULT_EFFECTIVE_DATE = "budgetPersonDefaultEffectiveDate"; public static final String PERSON_SEQUENCE_NUMBER = "personSequenceNumber"; public static final String BUDGET_PERSONNEL_PAGE = "personnel"; public static final String JOB_CODE = "jobCode"; // KIM Authorization Namespace for KRA public static final String KRA_NAMESPACE = "KRA"; // Key Permissions Info public static final String CONFIRM_DELETE_PROPOSAL_USER_KEY = "confirmDeleteProposalUser"; public static final String PERMISSION_PROPOSAL_USERS_PROPERTY_KEY = "newProposalUser"; public static final String EDIT_ROLES_PROPERTY_KEY = "proposalUserEditRole"; public static final String PERMISSIONS_EDIT_ROLES_PROPERTY_KEY = "permissionsUserEditRole"; public static final String MAPPING_PERMISSIONS_ROLE_RIGHTS_PAGE = "permissionsRoleRights"; public static final String MAPPING_PERMISSIONS_EDIT_ROLES_PAGE = "permissionsEditRoles"; public static final String MAPPING_PERMISSIONS_CLOSE_EDIT_ROLES_PAGE = "permissionsCloseEditRoles"; // Permission constants public static final String PERMISSION_USERS_PROPERTY_KEY = "newPermissionsUser"; // Task Authorization public static final String TASK_AUTHORIZATION = "taskAuthorization"; //Budget Rates public static final String ON_CAMUS_FLAG = "N"; public static final String OFF_CAMUS_FLAG = "F"; public static final String DEFALUT_CAMUS_FLAG = "D"; //Budget Expenses public static final String BUDGET_LINEITEM_NUMBER = "budget.budgetLineItem.lineItemNumber"; public static final String BUDGET_EXPENSE_LOOKUP_MESSAGE1 = "budget.expense.lookup.message1"; public static final String BUDGET_EXPENSE_LOOKUP_MESSAGE2 = "budget.expense.lookup.message2"; public static final String PERCENT_EFFORT_FIELD = "Percent Effort"; public static final String PERCENT_CHARGED_FIELD = "Percent Charged"; //Grants.gov public static final String S2S_SUBMISSIONTYPE_CODE_KEY="document.s2sOpportunity.s2sSubmissionTypeCode"; public static final String GRANTS_GOV_PANEL_ANCHOR = "Opportunity"; public static final String GRANTS_GOV_OPPORTUNITY_PANEL = "GrantsGov"; public static final String OPPORTUNITY_ID_KEY="document.programAnnouncementNumber"; public static final String OPPORTUNITY_TITLE_KEY="document.programAnnouncementTitle"; public static final String CFDA_NUMBER_KEY="document.cfdaNumber"; public static final String GRANTS_GOV_PAGE = "grantsGov"; public static final String ORIGINAL_PROPOSAL_ID_KEY = "document.sponsorProposalNumber"; public static final String CFDA_NUMBER = "cfdaNumber"; public static final String OPPORTUNITY_ID= "opportunityId"; public static final String NO_FIELD= "noField"; public static final String GRANTS_GOV_LINK="message.grantsgov.link"; public static final String GRANTS_GOV_GENERIC_ERROR_KEY= "error.grantsgov.schemavalidation.generic.errorkey"; public static final String GRANTS_GOV_SUBMISSION_SUCCESSFUL_MESSAGE = "message.grantsGov.submission.successful"; // custom attribute public static final String CUSTOM_ATTRIBUTE_ID = "customAttributeId"; public static final String DOCUMENT_NEWMAINTAINABLEOBJECT_ACTIVE = "document.newMaintainableObject.active"; public static final String DOCUMENT_NEWMAINTAINABLEOBJECT_LOOKUPRETURN = "document.newMaintainableObject.lookupReturn"; public static final String LOOKUP_RETURN_FIELDS = "lookupReturnFields"; public static final String LOOKUP_CLASS_NAME = "lookupClassName"; public static final String MAPPING_PERSONNEL_BUDGET = "personnelBudget"; public static final String MAPPING_EXPENSES_BUDGET = "expenses"; public static final String BUDGET_PERSON_LINE_NUMBER = "budget.budgetPersonnelDetails.personNumber"; public static final String BUDGET_PERSON_LINE_SEQUENCE_NUMBER = "budget.budgetPersonnelDetails.sequenceNumber"; public static final String DATA_TYPE_STRING = "String - Any Character"; public static final String DATA_TYPE_NUMBER = "Number - [0-9]"; public static final String DATA_TYPE_DATE = "Date - [xx/xx/xxxx]"; // Change Password public static final String CHANGE_PASSWORD_PROPERTY_KEY = "changePassword"; public static final String TRUE_FLAG = "Y"; public static final String FALSE_FLAG = "N"; public static final String PROPOSAL_SPECIAL_REVIEW_KEY = "document.proposalSpecialReview*"; public static final String SPECIAL_REVIEW_PAGE = "specialReview"; public static final String SPECIAL_REVIEW_PANEL_ANCHOR = "SpecialReview"; public static final String SPECIAL_REVIEW_PANEL_NAME = "Special Review Information"; public static final String BUDGET_PERIOD_PANEL_NAME = "Budget Period And Totals Information"; public static final String BUDGET_RATE_PANEL_NAME = "Budget Rate"; public static final String BUDGET_PERIOD_PAGE = "summary"; public static final String BUDGET_RATE_PAGE = "budgetRate"; public static final String BUDGET_VERSIONS_PAGE = "budgetVersions"; public static final String PD_BUDGET_VERSIONS_PAGE = "budgetVersions"; public static final String BUDGET_PERIOD_PANEL_ANCHOR = "BudgetPeriodsAmpTotals"; public static final String BUDGET_RATE_PANEL_ANCHOR = "BudgetProposalRate"; public static final String BUDGET_VERSIONS_PANEL_ANCHOR = "BudgetVersions"; public static final String BUDGET_PERIOD_KEY = "document.budgetPeriod*"; // Copy proposal public static final String COPY_PROPOSAL_PROPERTY_KEY = "copyProposal"; public static final String MAPPING_COPY_PROPOSAL_PAGE = "copyProposal"; public static final String HEADER_TAB = "headerTab"; public static final String ON_OFF_CAMPUS_FLAG = "onOffCampusFlag"; // Budget Rates public static final int APPLICABLE_RATE_PRECISION = 3; public static final int APPLICABLE_RATE_SCALE = 2; public static final String APPLICABLE_RATE_LIMIT = "999.99"; public static final String APPLICABLE_RATE_DECIMAL_CHAR = "."; // Modular Budget public static final String PARAMETER_FNA_COST_ELEMENTS = "consortiumFnaCostElements"; public static final String PARAMETER_FNA_RATE_CLASS_TYPE = "fnaRateClassTypeCode"; public static final String PROPOSALDATA_OVERRIDE_PROPERTY_KEY = "newProposalChangedData"; public static final String PROPOSALDATA_CHANGED_VAL_KEY = "newProposalChangedData.changedValue"; public static final String PROPOSALDATA_DISPLAY_VAL_KEY = "newProposalChangedData.displayValue"; public static final String PROPOSALDATA_CURRENT_DISPLAY_KEY = "newProposalChangedData.oldDisplayValue"; public static final String PROPOSALDATA_COMMENTS_KEY = "newProposalChangedData.comments"; public static final String BUDGET_SALARY_REPORT = "ProposalBudget/Salaries"; public static final String PERSONNEL_BUDGET_PANEL_NAME = "Personnel Budget"; public static final String INITIAL_UNIT_HIERARCHY_LOAD_DEPTH = "initialUnitLoadDepth"; public static final String NUMBER_PER_SPONSOR_HIERARCHY_GROUP = "numberPerSponsorHierarchyGroup"; public static final String PROPOSAL_EDITABLECOLUMN_DATATYPE = "document.newMaintainableObject.dataType"; public static final String PROPOSAL_EDITABLECOLUMN_DATALENGTH = "document.newMaintainableObject.dataLength"; public static final String PROPOSAL_EDITABLECOLUMN_LOOKUPRETURN = "document.newMaintainableObject.lookupReturn"; public static final String PDF_REPORT_CONTENT_TYPE = "application/pdf"; public static final String PDF_FILE_EXTENSION = ".pdf"; public static final String GENERIC_SPONSOR_CODE = "GENERIC_SPONSOR_CODE"; public static final String CUSTOM_ERROR = "error.custom"; public static final String SUBAWARD_FILE_REQUIERED = "newSubAward.subAwardFile.required"; public static final String SUBAWARD_FILE = "newSubAward.subAwardFile"; public static final String SUBAWARD_FILE_NOT_POPULATED = "newSubAward.subAwardFile.notExtracted"; public static final String SUBAWARD_ORG_NAME = "newSubAward.organizationName"; public static final String SUBAWARD_ORG_NAME_REQUIERED = "newSubAward.organizationName.required"; // sponsor hierarchy public static final String HIERARCHY_NAME = "hierarchyName"; public static final String SPONSOR_CODE = "sponsorCode"; public static final String SPONSOR_HIERARCHY_SEPARATOR_C1C = ";1;"; public static final String SPONSOR_HIERARCHY_SEPARATOR_P1P = "#1#"; //Award public static final String MAPPING_AWARD_BASIC = "basic"; public static final String MAPPING_AWARD_HOME_PAGE = "home"; public static final String MAPPING_AWARD_CONTACTS_PAGE = "contacts"; public static final String MAPPING_AWARD_TIME_AND_MONEY_PAGE = "timeAndMoney"; public static final String MAPPING_AWARD_PAYMENT_REPORTS_AND_TERMS_PAGE = "paymentReportsAndTerms"; public static final String MAPPING_AWARD_SPECIAL_REVIEW_PAGE = "specialReview"; public static final String MAPPING_AWARD_CUSTOM_DATA_PAGE = "customData"; public static final String MAPPING_AWARD_QUESTIONS_PAGE = "questions"; public static final String MAPPING_AWARD_PERMISSIONS_PAGE = "permissions"; public static final String MAPPING_AWARD_NOTES_AND_ATTACHMENTS_PAGE = "notesAndAttachments"; public static final String MAPPING_AWARD_ACTIONS_PAGE = "awardActions"; public static final Integer COST_SHARE_COMMENT_TYPE_CODE = 9; public static final Integer FANDA_RATE_COMMENT_TYPE_CODE = 8; public static final Integer PREAWARD_SPONSOR_AUTHORIZATION_COMMENT_TYPE_CODE = 18; public static final Integer PREAWARD_INSTITUTIONAL_AUTHORIZATION_COMMENT_TYPE_CODE = 19; public static final Integer BENEFITS_RATES_COMMENT_TYPE_CODE = 20; public static final Integer MIN_FISCAL_YEAR = 1900; public static final Integer MAX_FISCAL_YEAR = 2499; public static final String PARAMETER_MODULE_AWARD = "KC-AWARD"; public static final String SPECIAL_REVIEW_NUMBER = "SPECIAL_REVIEW_NUMBER"; public static final String LEFT_SQUARE_BRACKET = "["; public static final String RIGHT_SQUARE_BRACKET = "]"; public static final String REPORT_CLASSES_KEY_FOR_INITIALIZE_OBJECTS = "reportClasses"; public static final String NEW_AWARD_REPORT_TERMS_LIST_KEY_FOR_INITIALIZE_OBJECTS = "newAwardReportTermList"; public static final String NEW_AWARD_REPORT_TERM_RECIPIENTS_LIST_KEY_FOR_INITIALIZE_OBJECTS = "newAwardReportTermRecipientsList"; public static final String REPORT_CLASS_FOR_PAYMENTS_AND_INVOICES_PANEL = "reportClassForPaymentsAndInvoicesPanel"; // IRB public static final String PARTICIPANTS_PROPERTY_KEY = "newProtocolParticipant"; public static final String DEFAULT_PROTOCOL_ORGANIZATION_TYPE_CODE = "1"; public static final String DEFAULT_PROTOCOL_ORGANIZATION_ID = "000001"; public static final String DEFAULT_PROTOCOL_STATUS_CODE = "100"; public static final String PROPERTY_PROTOCOL_STATUS = "protocolStatus"; public static final String PARAMETER_PROTOCOL_PERSON_TRAINING_SECTION = "protocolPersonTrainingSectionRequired"; public static final Integer PROTOCOL_RISK_LEVEL_COMMENT_LENGTH = 40; public static final String ACTIVE_STATUS_LITERAL = "Active"; public static final String INACTIVE_STATUS_LITERAL = "Inactive"; public static final String CONFIRM_DELETE_PROTOCOL_USER_KEY = "confirmDeleteProtocolUser"; public static final String VIEW_ONLY = "viewOnly"; // Committee public static final String COMMITTEE_PROPERTY_KEY = "committee"; public static final String CONFIRM_DELETE_PERMISSIONS_USER_KEY = "confirmDeletePermissionsUser"; }
KCIRB-18 Updated error prefixes
src/main/java/org/kuali/kra/infrastructure/Constants.java
KCIRB-18 Updated error prefixes
Java
lgpl-2.1
823b212ec3e778da4bf5486b39432eac1351ea32
0
ACS-Community/ACS,jbarriosc/ACSUFRO,ACS-Community/ACS,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,csrg-utfsm/acscb,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,ACS-Community/ACS,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,csrg-utfsm/acscb,csrg-utfsm/acscb,ACS-Community/ACS,csrg-utfsm/acscb,csrg-utfsm/acscb,ACS-Community/ACS,csrg-utfsm/acscb,csrg-utfsm/acscb,ACS-Community/ACS,ACS-Community/ACS,jbarriosc/ACSUFRO,csrg-utfsm/acscb,ACS-Community/ACS
package cern.laser.business.pojo; import java.util.Collection; import java.util.Iterator; import org.apache.log4j.Logger; import cern.laser.business.LaserRuntimeException; import cern.laser.business.dao.AlarmDAO; import cern.laser.business.data.Alarm; import cern.laser.business.data.AlarmChange; import cern.laser.business.data.Status; import cern.laser.util.LogTimeStamp; public class AlarmCacheServerImpl { private static final Logger LOGGER = Logger.getLogger(AlarmCacheServerImpl.class.getName()); private AlarmDAO alarmDAO; private AlarmPublisherImpl alarmPublisher; private MailAndSmsServerImpl mailAndSmsServer; // // -- CONSTRUCTORS ------------------------------------------------ // // // -- PUBLIC METHODS ---------------------------------------------- // public void setAlarmDAO(AlarmDAO alarmDAO) { this.alarmDAO = alarmDAO; } public void setAlarmPublisher(AlarmPublisherImpl alarmPublisher) { this.alarmPublisher = alarmPublisher; } public void setMailAndSmsServer(MailAndSmsServerImpl mailAndSmsServer) { this.mailAndSmsServer = mailAndSmsServer; } public Alarm load(String alarmId) { return alarmDAO.findAlarm(alarmId); } public void store(Collection updated) { try { LOGGER.info("storing " + updated.size() + " alarm(s)..."); if (LOGGER.isDebugEnabled()) LogTimeStamp.logMsg("storing " + updated.size() + " alarm(s)...", true); Iterator iterator = updated.iterator(); while (iterator.hasNext()) { Alarm alarm = (Alarm) iterator.next(); Status status = alarm.getStatus(); // if (status.getStatusId() == null || status.getStatusId().equals("")) { // if (LOGGER.isDebugEnabled()) LOGGER.debug("saving status ..."); // status.setStatusId(alarm.getAlarmId()); // alarmDAO.saveStatus(status); // } else { // if (LOGGER.isDebugEnabled()) LOGGER.debug("updating status ..."); alarmDAO.updateStatus(status); // } } LOGGER.info("stored"); if (LOGGER.isDebugEnabled()) LogTimeStamp.logMsg("stored"); } catch (Exception e) { LOGGER.error("unable to store alarm(s)", e); throw new LaserRuntimeException("unable to store alarm(s)", e); } } public void publish(Collection alarmChanges) { System.out.println("*** AlarmCacheServerImpl.Publishing "+alarmChanges.size()+" alarms"); try { LOGGER.info("publishing " + alarmChanges.size() + " alarm(s)..."); if (LOGGER.isDebugEnabled()) LogTimeStamp.logMsg("publishing " + alarmChanges.size() + " alarm(s)...", true); alarmPublisher.publish(alarmChanges); LOGGER.info("published"); if (LOGGER.isDebugEnabled()) LogTimeStamp.logMsg("published"); } catch (Exception e) { LOGGER.error("unable to publish alarm(s)", e); throw new LaserRuntimeException("unable to publish alarm(s)", e); } } public void notify(Collection alarmChanges) { try { Iterator iterator = alarmChanges.iterator(); while (iterator.hasNext()) { AlarmChange alarm_change = (AlarmChange) iterator.next(); Alarm current_alarm = alarm_change.getCurrent(); if (!current_alarm.getStatus().getActive().equals(alarm_change.getPrevious().getStatus().getActive())) { if (current_alarm.getPiquetGSM() != null) { sendSMS(current_alarm); } if (current_alarm.getPiquetEmail() != null) { sendEmail(current_alarm); } } } } catch (Exception e) { LOGGER.error("unable to notify alarm(s)", e); throw new LaserRuntimeException("unable to notify alarm(s)", e); } } // // -- PROTECTED METHODS ------------------------------------------- // // // -- PRIVATE METHODS --------------------------------------------- // private void sendEmail(Alarm currentAlarm) { try { LOGGER.info("notifying piquet email : " + currentAlarm.getPiquetEmail()); if (LOGGER.isDebugEnabled()) LogTimeStamp.logMsg("notifying piquet email : " + currentAlarm.getPiquetEmail(), true); String subject="Alarm server notification: "+currentAlarm.getAlarmId(); if (currentAlarm.getStatus().getActive()) { subject=subject+" ACTIVE"; } else { subject=subject+" TERMINATE"; } mailAndSmsServer.sendEmail(currentAlarm.getPiquetEmail(), subject, currentAlarm.toString()); LOGGER.info("notified"); if (LOGGER.isDebugEnabled()) LogTimeStamp.logMsg("notified piquet email"); } catch (Exception e) { LOGGER.error("unable to notify " + currentAlarm.getPiquetEmail() + " : " + currentAlarm.toString(), e); } } private void sendSMS(Alarm currentAlarm) { StringBuffer gsm_message = new StringBuffer(); gsm_message.append(currentAlarm.getStatus().getSourceTimestamp()); gsm_message.append(" => ("); gsm_message.append(currentAlarm.getSystemName()); gsm_message.append(")("); gsm_message.append(currentAlarm.getIdentifier()); gsm_message.append(")("); gsm_message.append(currentAlarm.getProblemDescription()); gsm_message.append(") IS "); gsm_message.append(currentAlarm.getStatus().getActive().booleanValue() ? "ACTIVE" : "TERMINATE"); String number = "16" + currentAlarm.getPiquetGSM(); try { LOGGER.info("notifying piquet GSM : " + number); if (LOGGER.isDebugEnabled()) LogTimeStamp.logMsg("notifying piquet GSM : " + number, true); mailAndSmsServer.sendSMS(number, gsm_message.toString()); LOGGER.info("notified"); if (LOGGER.isDebugEnabled()) LogTimeStamp.logMsg("notified piquet GSM"); } catch (Exception e) { LOGGER.error("unable to notify " + number + " : " + gsm_message.toString(), e); } } }
LGPL/CommonSoftware/ACSLaser/laser-core/src/cern/laser/business/pojo/AlarmCacheServerImpl.java
package cern.laser.business.pojo; import java.util.Collection; import java.util.Iterator; import org.apache.log4j.Logger; import cern.laser.business.LaserRuntimeException; import cern.laser.business.dao.AlarmDAO; import cern.laser.business.data.Alarm; import cern.laser.business.data.AlarmChange; import cern.laser.business.data.Status; import cern.laser.util.LogTimeStamp; public class AlarmCacheServerImpl { private static final Logger LOGGER = Logger.getLogger(AlarmCacheServerImpl.class.getName()); private AlarmDAO alarmDAO; private AlarmPublisherImpl alarmPublisher; private MailAndSmsServerImpl mailAndSmsServer; // // -- CONSTRUCTORS ------------------------------------------------ // // // -- PUBLIC METHODS ---------------------------------------------- // public void setAlarmDAO(AlarmDAO alarmDAO) { this.alarmDAO = alarmDAO; } public void setAlarmPublisher(AlarmPublisherImpl alarmPublisher) { this.alarmPublisher = alarmPublisher; } public void setMailAndSmsServer(MailAndSmsServerImpl mailAndSmsServer) { this.mailAndSmsServer = mailAndSmsServer; } public Alarm load(String alarmId) { return alarmDAO.findAlarm(alarmId); } public void store(Collection updated) { try { LOGGER.info("storing " + updated.size() + " alarm(s)..."); if (LOGGER.isDebugEnabled()) LogTimeStamp.logMsg("storing " + updated.size() + " alarm(s)...", true); Iterator iterator = updated.iterator(); while (iterator.hasNext()) { Alarm alarm = (Alarm) iterator.next(); Status status = alarm.getStatus(); // if (status.getStatusId() == null || status.getStatusId().equals("")) { // if (LOGGER.isDebugEnabled()) LOGGER.debug("saving status ..."); // status.setStatusId(alarm.getAlarmId()); // alarmDAO.saveStatus(status); // } else { // if (LOGGER.isDebugEnabled()) LOGGER.debug("updating status ..."); alarmDAO.updateStatus(status); // } } LOGGER.info("stored"); if (LOGGER.isDebugEnabled()) LogTimeStamp.logMsg("stored"); } catch (Exception e) { LOGGER.error("unable to store alarm(s)", e); throw new LaserRuntimeException("unable to store alarm(s)", e); } } public void publish(Collection alarmChanges) { System.out.println("*** AlarmCacheServerImpl.Publishing "+alarmChanges.size()+" alarms"); try { LOGGER.info("publishing " + alarmChanges.size() + " alarm(s)..."); if (LOGGER.isDebugEnabled()) LogTimeStamp.logMsg("publishing " + alarmChanges.size() + " alarm(s)...", true); alarmPublisher.publish(alarmChanges); LOGGER.info("published"); if (LOGGER.isDebugEnabled()) LogTimeStamp.logMsg("published"); } catch (Exception e) { LOGGER.error("unable to publish alarm(s)", e); throw new LaserRuntimeException("unable to publish alarm(s)", e); } } public void notify(Collection alarmChanges) { try { Iterator iterator = alarmChanges.iterator(); while (iterator.hasNext()) { AlarmChange alarm_change = (AlarmChange) iterator.next(); Alarm current_alarm = alarm_change.getCurrent(); if (!current_alarm.getStatus().getActive().equals(alarm_change.getPrevious().getStatus().getActive())) { if (current_alarm.getPiquetGSM() != null) { sendSMS(current_alarm); } if (current_alarm.getPiquetEmail() != null) { sendEmail(current_alarm); } } } } catch (Exception e) { LOGGER.error("unable to notify alarm(s)", e); throw new LaserRuntimeException("unable to notify alarm(s)", e); } } // // -- PROTECTED METHODS ------------------------------------------- // // // -- PRIVATE METHODS --------------------------------------------- // private void sendEmail(Alarm currentAlarm) { try { LOGGER.info("notifying piquet email : " + currentAlarm.getPiquetEmail()); if (LOGGER.isDebugEnabled()) LogTimeStamp.logMsg("notifying piquet email : " + currentAlarm.getPiquetEmail(), true); mailAndSmsServer.sendEmail(currentAlarm.getPiquetEmail(), "LASER NOTIFICATION", currentAlarm.toString()); LOGGER.info("notified"); if (LOGGER.isDebugEnabled()) LogTimeStamp.logMsg("notified piquet email"); } catch (Exception e) { LOGGER.error("unable to notify " + currentAlarm.getPiquetEmail() + " : " + currentAlarm.toString(), e); } } private void sendSMS(Alarm currentAlarm) { StringBuffer gsm_message = new StringBuffer(); gsm_message.append(currentAlarm.getStatus().getSourceTimestamp()); gsm_message.append(" => ("); gsm_message.append(currentAlarm.getSystemName()); gsm_message.append(")("); gsm_message.append(currentAlarm.getIdentifier()); gsm_message.append(")("); gsm_message.append(currentAlarm.getProblemDescription()); gsm_message.append(") IS "); gsm_message.append(currentAlarm.getStatus().getActive().booleanValue() ? "ACTIVE" : "TERMINATE"); String number = "16" + currentAlarm.getPiquetGSM(); try { LOGGER.info("notifying piquet GSM : " + number); if (LOGGER.isDebugEnabled()) LogTimeStamp.logMsg("notifying piquet GSM : " + number, true); mailAndSmsServer.sendSMS(number, gsm_message.toString()); LOGGER.info("notified"); if (LOGGER.isDebugEnabled()) LogTimeStamp.logMsg("notified piquet GSM"); } catch (Exception e) { LOGGER.error("unable to notify " + number + " : " + gsm_message.toString(), e); } } }
Better subject for emails git-svn-id: afcf11d89342f630bd950d18a70234a9e277d909@163098 523d945c-050c-4681-91ec-863ad3bb968a
LGPL/CommonSoftware/ACSLaser/laser-core/src/cern/laser/business/pojo/AlarmCacheServerImpl.java
Better subject for emails
Java
lgpl-2.1
56acc214c863a917925ad03937258b4d97656e14
0
integrated/jfreechart
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * DefaultPlotEditor.java * ---------------------- * (C) Copyright 2005-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Andrzej Porebski; * Arnaud Lelievre; * Daniel Gredler; * * Changes: * -------- * 24-Nov-2005 : Version 1, based on PlotPropertyEditPanel.java (DG); * 18-Dec-2008 : Use ResourceBundleWrapper - see patch 1607918 by * Jess Thrysoee (DG); * */ package org.jfree.chart.editor; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusListener; import java.awt.event.FocusEvent; import java.util.ResourceBundle; import java.text.MessageFormat; import java.text.DecimalFormat; import javax.swing.*; import javax.swing.event.DocumentListener; import javax.swing.event.DocumentEvent; import org.jfree.chart.axis.Axis; import org.jfree.chart.plot.*; import org.jfree.chart.util.ResourceBundleWrapper; import org.jfree.chart.JFreeChart; import org.jfree.chart.labels.StandardPieSectionLabelGenerator; import org.jfree.chart.labels.StandardCategoryItemLabelGenerator; import org.jfree.chart.labels.StandardXYItemLabelGenerator; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.chart.renderer.category.CategoryItemRenderer; import org.jfree.chart.renderer.xy.XYBarRenderer; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.ui.RectangleInsets; import org.jfree.util.Rotation; import org.jfree.chart.editor.components.*; import org.jfree.chart.editor.themes.PlotTheme; import org.jfree.chart.editor.themes.ChartBorder; import org.jfree.chart.editor.themes.AxisTheme; /** * A panel for editing the properties of a {@link Plot}. */ public class DefaultPlotEditor extends BaseEditor implements ActionListener { private final static int PIE = -1, CATEGORY = -2, XY = -3; /** Orientation constants. */ private final static String[] orientationNames = {"Vertical", "Horizontal"}; private final static int ORIENTATION_VERTICAL = 0; private final static int ORIENTATION_HORIZONTAL = 1; protected PlotTheme theme; /** The panel to adjust the properties of the plot's background */ private BackgroundEditingPanel backgroundPanel; /** * A panel used to display/edit the properties of the domain axis (if any). */ private DefaultAxisEditor domainAxisPropertyPanel; /** * A panel used to display/edit the properties of the range axis (if any). */ private DefaultAxisEditor rangeAxisPropertyPanel; /** * The orientation for the plot (for <tt>CategoryPlot</tt>s and * <tt>XYPlot</tt>s). */ private PlotOrientation plotOrientation; /** * The orientation combo box (for <tt>CategoryPlot</tt>s and * <tt>XYPlot</tt>s). */ private JComboBox orientationCombo; private JCheckBox shadowsVisible; private InsetPanel axisOffset; private LineEditorPanel domainPanel, rangePanel; private BorderPanel plotBorder; private InsetPanel insetPanel; private JSpinner startAngle; private JCheckBox circularPlot; private RotationComboBox pieDirection; // label controls private JPanel labelPanel = null; private JCheckBox labelsVisible; private FontControl labelFont; private PaintControl labelPaint, labelBackgroundPaint, labelOutlinePaint, labelShadowPaint; private JCheckBox labelLinkVisible; private LinkStyleComboBox labelLinkStyle; private StrokeControl labelOutlineStroke; private InsetPanel labelPadding; private JTextField labelFormat; private NumberFormatDisplay numberFormatDisplay, percentFormatDisplay; /** The resourceBundle for the localization. */ protected static ResourceBundle localizationResources = ResourceBundleWrapper.getBundle( "org.jfree.chart.editor.LocalizationBundle"); /** * Standard constructor - constructs a panel for editing the properties of * the specified plot. * <P> * In designing the panel, we need to be aware that subclasses of Plot will * need to implement subclasses of PlotPropertyEditPanel - so we need to * leave one or two 'slots' where the subclasses can extend the user * interface. * * @param theme The theme that will be edited. * @param chart the chart, which should be changed. * @param plot the plot, which should be changed. * @param immediateUpdate Whether changes to GUI controls should immediately be applied. */ public DefaultPlotEditor(PlotTheme theme, JFreeChart chart, Plot plot, boolean immediateUpdate) { super(chart, immediateUpdate); this.theme = theme; this.backgroundPanel = new BackgroundEditingPanel(theme); this.plotOrientation = theme.getOrientation(); domainPanel = new LineEditorPanel(localizationResources.getString("Domain_Axis"), theme.isDomainGridlineVisible(), theme.getDomainGridlinePaint(), theme.getDomainGridlineStroke()); rangePanel = new LineEditorPanel(localizationResources.getString("Range_Axis"), theme.isRangeGridlinesVisible(), theme.getRangeGridlinePaint(), theme.getRangeGridlineStroke()); setLayout(new BorderLayout()); // create a panel for the settings... JPanel panel = new JPanel(new BorderLayout()); JPanel general = new JPanel(new BorderLayout()); JPanel interior = new JPanel(new GridBagLayout()); GridBagConstraints c = getNewConstraints(); interior.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5)); if (plot instanceof CategoryPlot || plot instanceof XYPlot) { startNewRow(c); boolean isVertical = this.plotOrientation.equals(PlotOrientation.VERTICAL); int index = isVertical ? ORIENTATION_VERTICAL : ORIENTATION_HORIZONTAL; interior.add( new JLabel(localizationResources.getString("Orientation")), c ); c.gridx++; c.gridwidth = 2; c.anchor = GridBagConstraints.WEST; c.fill = GridBagConstraints.NONE; this.orientationCombo = new JComboBox(orientationNames); this.orientationCombo.setSelectedIndex(index); this.orientationCombo.setActionCommand("Orientation"); this.orientationCombo.addActionListener(updateHandler); this.orientationCombo.addActionListener(this); interior.add(this.orientationCombo,c); startNewRow(c); RectangleInsets offsets = theme.getAxisOffset(); this.axisOffset = new InsetPanel(localizationResources.getString("Axis-Offset"), offsets); this.axisOffset.addChangeListener(updateHandler); c.gridwidth = 3; c.weightx = 1; interior.add(this.axisOffset, c); } if(hasPossibleShadows(plot)) { insertShadowsCheckBox(interior, c, theme.isShadowsVisible()); } startNewRow(c); c.gridwidth = 3; c.weightx = 1; insetPanel = new InsetPanel(localizationResources.getString("Insets"), theme.getInsets()); insetPanel.addChangeListener(updateHandler); interior.add(insetPanel, c); startNewRow(c); c.gridwidth = 3; c.weightx = 1; ChartBorder border = theme.getBorder(); plotBorder = new BorderPanel(localizationResources.getString("Border"), border.isVisible(), border.getStroke(), border.getPaint()); plotBorder.addChangeListener(updateHandler); interior.add(plotBorder, c); startNewRow(c); backgroundPanel.setBorder(BorderFactory.createTitledBorder( localizationResources.getString("Background") )); backgroundPanel.addChangeListener(updateHandler); c.gridwidth = 3; c.weightx = 1; interior.add(backgroundPanel,c); if(plot instanceof PiePlot) { JPanel piePanel = getPiePanel(); startNewRow(c); c.gridwidth = 3; c.weightx = 1; interior.add(piePanel, c); labelPanel = getLabelPanel(PIE); enableDisableLabelControls(); } general.add(interior, BorderLayout.NORTH); JPanel appearance = new JPanel(new BorderLayout()); appearance.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); appearance.add(general, BorderLayout.NORTH); JTabbedPane tabs = new JTabbedPane(); tabs.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5)); tabs.add(localizationResources.getString("Appearance"), new JScrollPane(appearance)); Axis domainAxis = null; if (plot instanceof CategoryPlot) { domainAxis = ((CategoryPlot) plot).getDomainAxis(); } else if (plot instanceof XYPlot) { domainAxis = ((XYPlot) plot).getDomainAxis(); } AxisTheme dAxisTheme = theme.getDomainAxisTheme(); AxisTheme rAxisTheme = theme.getRangeAxisTheme(); this.domainAxisPropertyPanel = DefaultAxisEditor.getInstance(dAxisTheme, chart, domainAxis, immediateUpdate); if (this.domainAxisPropertyPanel != null) { this.domainAxisPropertyPanel.setBorder( BorderFactory.createEmptyBorder(2, 2, 2, 2) ); tabs.add( localizationResources.getString("Domain_Axis"), new JScrollPane(this.domainAxisPropertyPanel) ); } Axis rangeAxis = null; if (plot instanceof CategoryPlot) { rangeAxis = ((CategoryPlot) plot).getRangeAxis(); labelPanel = getLabelPanel(CATEGORY); } else if (plot instanceof XYPlot) { rangeAxis = ((XYPlot) plot).getRangeAxis(); labelPanel = getLabelPanel(XY); } this.rangeAxisPropertyPanel = DefaultAxisEditor.getInstance(rAxisTheme, chart, rangeAxis, immediateUpdate); if (this.rangeAxisPropertyPanel != null) { this.rangeAxisPropertyPanel.setBorder( BorderFactory.createEmptyBorder(2, 2, 2, 2) ); tabs.add( localizationResources.getString("Range_Axis"), new JScrollPane(this.rangeAxisPropertyPanel) ); } if (plot instanceof CategoryPlot || plot instanceof XYPlot) { tabs.add(localizationResources.getString("Grid_Lines"), new JScrollPane(getGridlinesPanel())); } addCustomTabs(tabs); if(labelPanel != null) { tabs.add(localizationResources.getString("Labels"), new JScrollPane(labelPanel)); } panel.add(tabs); add(panel); } protected JPanel getLabelPanel(int plotType) { JPanel retVal = new JPanel(new GridBagLayout()); GridBagConstraints c = getNewConstraints(); labelsVisible = new JCheckBox(localizationResources.getString("Visible"), theme.isLabelsVisible()); labelsVisible.addActionListener(updateHandler); labelsVisible.addActionListener(this); labelFormat = new JTextField(theme.getLabelFormat()); DocHandler handler = new DocHandler(); labelFormat.getDocument().addDocumentListener(handler); labelFormat.addFocusListener(handler); String tip; switch(plotType) { case CATEGORY: tip = localizationResources.getString("Format_tip_cat"); break; case XY: tip = localizationResources.getString("Format_tip_xy"); break; case PIE: default: tip = localizationResources.getString("Format_tip_pie"); break; } labelFormat.setToolTipText(tip); numberFormatDisplay = buildNumberFormatDisplay(theme.getNumberFormatString()); numberFormatDisplay.addChangeListener(updateHandler); percentFormatDisplay = buildNumberFormatDisplay(theme.getPercentFormatString()); percentFormatDisplay.addChangeListener(updateHandler); labelFont = new FontControl(theme.getLabelFont()); labelFont.addChangeListener(updateHandler); labelPaint = new PaintControl(theme.getLabelPaint(), false); labelPaint.addChangeListener(updateHandler); labelBackgroundPaint = new PaintControl(theme.getLabelBackgroundPaint(), true); labelBackgroundPaint.addChangeListener(updateHandler); labelShadowPaint = new PaintControl(theme.getLabelShadowPaint(), true); labelShadowPaint.addChangeListener(updateHandler); labelOutlinePaint = new PaintControl(theme.getLabelOutlinePaint(), true); labelOutlinePaint.addChangeListener(updateHandler); labelOutlineStroke = new StrokeControl(theme.getLabelOutlineStroke()); labelOutlineStroke.addChangeListener(updateHandler); labelPadding = new InsetPanel(localizationResources.getString("Padding"), theme.getLabelPadding()); labelPadding.addChangeListener(updateHandler); labelLinkVisible = new JCheckBox(localizationResources.getString("Links_Visible"), theme.isLabelLinksVisible()); labelLinkVisible.addActionListener(updateHandler); labelLinkVisible.addActionListener(this); labelLinkStyle = new LinkStyleComboBox(); labelLinkStyle.setSelectedObject(theme.getLabelLinkStyle()); labelLinkStyle.addActionListener(updateHandler); c.gridwidth = 2; c.anchor = GridBagConstraints.WEST; retVal.add(labelsVisible, c); startNewRow(c); retVal.add(new JLabel(localizationResources.getString("Format")), c); c.gridx++; c.weightx = 1; retVal.add(labelFormat, c); startNewRow(c); retVal.add(new JLabel(localizationResources.getString("Number_Format")), c); c.gridx++; c.weightx = 1; retVal.add(numberFormatDisplay, c); startNewRow(c); retVal.add(new JLabel(localizationResources.getString("Percent_Format")), c); c.gridx++; c.weightx = 1; retVal.add(percentFormatDisplay, c); startNewRow(c); retVal.add(new JLabel(localizationResources.getString("Font")), c); c.gridx++; c.weightx = 1; retVal.add(labelFont, c); startNewRow(c); retVal.add(new JLabel(localizationResources.getString("Paint")), c); c.gridx++; c.weightx = 1; retVal.add(labelPaint, c); if (plotType == PIE) { startNewRow(c); retVal.add(new JLabel(localizationResources.getString("Background_paint")), c); c.gridx++; c.weightx = 1; retVal.add(labelBackgroundPaint, c); startNewRow(c); retVal.add(new JLabel(localizationResources.getString("Shadow_paint")), c); c.gridx++; c.weightx = 1; retVal.add(labelShadowPaint, c); startNewRow(c); retVal.add(new JLabel(localizationResources.getString("Outline_Paint")), c); c.gridx++; c.weightx = 1; retVal.add(labelOutlinePaint, c); startNewRow(c); retVal.add(new JLabel(localizationResources.getString("Outline_stroke")), c); c.gridx++; c.weightx = 1; retVal.add(labelOutlineStroke, c); startNewRow(c); c.gridwidth = 2; c.anchor = GridBagConstraints.WEST; retVal.add(labelLinkVisible, c); startNewRow(c); retVal.add(new JLabel(localizationResources.getString("Link_Style")), c); c.gridx++; c.weightx = 1; retVal.add(labelLinkStyle, c); startNewRow(c); c.gridwidth = 2; c.weightx = 1; retVal.add(labelPadding, c); } startNewRow(c); c.fill = GridBagConstraints.VERTICAL; c.weighty = 1; retVal.add(new JPanel(), c); return retVal; } protected NumberFormatDisplay buildNumberFormatDisplay(String formatStr) { return new NumberFormatDisplay(formatStr); } protected JPanel getGridlinesPanel() { JPanel retVal = new JPanel(new GridBagLayout()); domainPanel.addChangeListener(updateHandler); rangePanel.addChangeListener(updateHandler); GridBagConstraints c = getNewConstraints(); c.weightx = 1; retVal.add(domainPanel, c); startNewRow(c); c.weightx = 1; retVal.add(rangePanel, c); startNewRow(c); c.fill = GridBagConstraints.BOTH; c.weighty = 1; retVal.add(new JPanel(), c); return retVal; } private JPanel getPiePanel() { JPanel retVal = new JPanel(new GridBagLayout()); retVal.setBorder(BorderFactory.createTitledBorder(localizationResources.getString("Pie"))); GridBagConstraints c = getNewConstraints(); circularPlot = new JCheckBox(localizationResources.getString("Circular"), theme.isCircularPie()); circularPlot.addActionListener(updateHandler); pieDirection = new RotationComboBox(); pieDirection.setSelectedObject(theme.getPieDirection()); pieDirection.addActionListener(updateHandler); startAngle = new JSpinner(new SpinnerNumberModel(theme.getStartAngle(), 0, 360, 1)); startAngle.addChangeListener(updateHandler); c.gridwidth = 2; c.anchor = GridBagConstraints.WEST; retVal.add(circularPlot, c); startNewRow(c); retVal.add(new JLabel(localizationResources.getString("Pie_Direction")), c); c.gridx++; c.weightx = 1; retVal.add(pieDirection, c); startNewRow(c); retVal.add(new JLabel(localizationResources.getString("Start_Position_Degs")), c); c.gridx++; c.weightx = 1; retVal.add(startAngle, c); return retVal; } private boolean hasPossibleShadows(Plot plot) { if(plot instanceof PiePlot) { return true; } else if (plot instanceof CategoryPlot) { CategoryPlot cPlot = (CategoryPlot) plot; for(int i=0; i < cPlot.getRendererCount(); i++) { if(cPlot.getRenderer(i) instanceof BarRenderer) { return true; } } } else if (plot instanceof XYPlot) { XYPlot xyPlot = (XYPlot) plot; for(int i=0; i < xyPlot.getRendererCount(); i++) { if(xyPlot.getRenderer(i) instanceof XYBarRenderer) { return true; } } } return false; } private void insertShadowsCheckBox(JPanel interior, GridBagConstraints c, boolean shadowVisible) { startNewRow(c); c.gridwidth = 2; c.anchor = GridBagConstraints.WEST; shadowsVisible = new JCheckBox(localizationResources.getString("Shadows_Visible")); shadowsVisible.setSelected(shadowVisible); shadowsVisible.addActionListener(updateHandler); interior.add(shadowsVisible, c); } /** * Returns the current outline stroke. * * @return The current outline stroke. */ public Stroke getOutlineStroke() { return this.plotBorder.getBorderStroke(); } /** * Returns the current outline paint. * * @return The current outline paint. */ public Paint getOutlinePaint() { return this.plotBorder.getBorderPaint(); } /** * Returns a reference to the panel for editing the properties of the * domain axis. * * @return A reference to a panel. */ public DefaultAxisEditor getDomainAxisPropertyEditPanel() { return this.domainAxisPropertyPanel; } /** * Returns a reference to the panel for editing the properties of the * range axis. * * @return A reference to a panel. */ public DefaultAxisEditor getRangeAxisPropertyEditPanel() { return this.rangeAxisPropertyPanel; } public RectangleInsets getAxisOffset() { return axisOffset.getSelectedInsets(); } /** * Handles user actions generated within the panel. * @param event the event */ public void actionPerformed(ActionEvent event) { String command = event.getActionCommand(); if (command.equals("Orientation")) { attemptOrientationSelection(); } else if (event.getSource() == labelsVisible) { enableDisableLabelControls(); } } private void enableDisableLabelControls() { boolean b = labelsVisible.isSelected(); boolean l = labelLinkVisible.isSelected(); labelFont.setEnabled(b); labelPaint.setEnabled(b); labelBackgroundPaint.setEnabled(b); labelShadowPaint.setEnabled(b); labelOutlinePaint.setEnabled(b); labelOutlineStroke.setEnabled(b); labelPadding.setEnabled(b); labelFormat.setEnabled(b); numberFormatDisplay.setEnabled(b); percentFormatDisplay.setEnabled(b); labelLinkVisible.setEnabled(b); labelLinkStyle.setEnabled(b&&l); } /** * Allow the user to modify the plot orientation if this is an editor for a * <tt>CategoryPlot</tt> or a <tt>XYPlot</tt>. */ private void attemptOrientationSelection() { int index = this.orientationCombo.getSelectedIndex(); if (index == ORIENTATION_VERTICAL) { this.plotOrientation = PlotOrientation.VERTICAL; } else { this.plotOrientation = PlotOrientation.HORIZONTAL; } } /** * Updates the plot properties to match the properties defined on the panel. * * @param chart The chart. */ public void updateChart(JFreeChart chart) { Plot plot = chart.getPlot(); // set the plot properties... boolean pBorderVisible = plotBorder.isBorderVisible(); theme.setBorder(pBorderVisible, getOutlinePaint(), (BasicStroke) getOutlineStroke()); plot.setOutlineVisible(pBorderVisible); plot.setOutlinePaint(getOutlinePaint()); plot.setOutlineStroke(getOutlineStroke()); RectangleInsets plotInsets = insetPanel.getSelectedInsets(); theme.setInsets(plotInsets); plot.setInsets(plotInsets); plot.setBackgroundPaint(backgroundPanel.getBackgroundPaint()); theme.setPlotBackgroundPaint(backgroundPanel.getBackgroundPaint()); if(plot instanceof CategoryPlot) { CategoryPlot cPlot = (CategoryPlot) plot; RectangleInsets offset = axisOffset.getSelectedInsets(); cPlot.setAxisOffset(offset); theme.setAxisOffset(offset); boolean domVis = domainPanel.isLineVisible(); cPlot.setDomainGridlinesVisible(domVis); theme.setDomainGridlineVisible(domVis); boolean ranVis = rangePanel.isLineVisible(); cPlot.setRangeGridlinesVisible(ranVis); theme.setRangeGridlinesVisible(ranVis); Paint domPaint = domainPanel.getLinePaint(); BasicStroke domStroke = domainPanel.getLineStroke(); cPlot.setDomainGridlinePaint(domPaint); theme.setDomainGridlinePaint(domPaint); cPlot.setDomainGridlineStroke(domStroke); theme.setDomainGridlineStroke(domStroke); Paint ranPaint = rangePanel.getLinePaint(); BasicStroke ranStroke = rangePanel.getLineStroke(); cPlot.setRangeGridlinePaint(ranPaint); theme.setRangeGridlinePaint(ranPaint); cPlot.setRangeGridlineStroke(ranStroke); theme.setRangeGridlineStroke(ranStroke); CategoryItemRenderer renderer = cPlot.getRenderer(); boolean labelsVis = labelsVisible.isSelected(); renderer.setBaseItemLabelsVisible(labelsVis); theme.setLabelsVisible(labelsVis); Font labelFont = this.labelFont.getChosenFont(); renderer.setBaseItemLabelFont(labelFont); theme.setLabelFont(labelFont); Paint labelPaint = this.labelPaint.getChosenPaint(); renderer.setBaseItemLabelPaint(labelPaint); theme.setLabelPaint(labelPaint); String formatText = labelFormat.getText(); theme.setLabelFormat(formatText); String numFormatString = numberFormatDisplay.getFormatString(); String perFormatString = percentFormatDisplay.getFormatString(); theme.setNumberFormatString(numFormatString); theme.setPercentFormatString(perFormatString); DecimalFormat numF = new DecimalFormat(numFormatString); DecimalFormat perF = new DecimalFormat(perFormatString); StandardCategoryItemLabelGenerator sLabelGen = new StandardCategoryItemLabelGenerator( formatText, numF, perF ); renderer.setBaseItemLabelGenerator(sLabelGen); } else if (plot instanceof XYPlot) { XYPlot xyPlot = (XYPlot) plot; RectangleInsets offset = axisOffset.getSelectedInsets(); xyPlot.setAxisOffset(offset); theme.setAxisOffset(offset); boolean domVis = domainPanel.isLineVisible(); xyPlot.setDomainGridlinesVisible(domVis); theme.setDomainGridlineVisible(domVis); boolean ranVis = rangePanel.isLineVisible(); xyPlot.setRangeGridlinesVisible(ranVis); theme.setRangeGridlinesVisible(ranVis); Paint domPaint = domainPanel.getLinePaint(); BasicStroke domStroke = domainPanel.getLineStroke(); xyPlot.setDomainGridlinePaint(domPaint); theme.setDomainGridlinePaint(domPaint); xyPlot.setDomainGridlineStroke(domStroke); theme.setDomainGridlineStroke(domStroke); Paint ranPaint = rangePanel.getLinePaint(); BasicStroke ranStroke = rangePanel.getLineStroke(); xyPlot.setRangeGridlinePaint(ranPaint); theme.setRangeGridlinePaint(ranPaint); xyPlot.setRangeGridlineStroke(ranStroke); theme.setRangeGridlineStroke(ranStroke); XYItemRenderer renderer = xyPlot.getRenderer(); boolean labelsVis = labelsVisible.isSelected(); renderer.setBaseItemLabelsVisible(labelsVis); theme.setLabelsVisible(labelsVis); Font labelFont = this.labelFont.getChosenFont(); renderer.setBaseItemLabelFont(labelFont); theme.setLabelFont(labelFont); Paint labelPaint = this.labelPaint.getChosenPaint(); renderer.setBaseItemLabelPaint(labelPaint); theme.setLabelPaint(labelPaint); String formatText = labelFormat.getText(); theme.setLabelFormat(formatText); String numFormatString = numberFormatDisplay.getFormatString(); String perFormatString = percentFormatDisplay.getFormatString(); theme.setNumberFormatString(numFormatString); theme.setPercentFormatString(perFormatString); // 2 copies for thread safety. DecimalFormat numF = new DecimalFormat(numFormatString); DecimalFormat numF2 = new DecimalFormat(numFormatString); StandardXYItemLabelGenerator sLabelGen = new StandardXYItemLabelGenerator( formatText, numF, numF2 ); renderer.setBaseItemLabelGenerator(sLabelGen); } else if (plot instanceof PiePlot) { PiePlot piePlot = (PiePlot) plot; boolean circular = circularPlot.isSelected(); theme.setCircularPie(circular); piePlot.setCircular(circular); double angle = ((Number)startAngle.getValue()).doubleValue(); theme.setStartAngle(angle); piePlot.setStartAngle(angle); Rotation direction = (Rotation)pieDirection.getSelectedObject(); theme.setPieDirection(direction); piePlot.setDirection(direction); boolean visible = labelsVisible.isSelected(); theme.setLabelsVisible(visible); String formatText = labelFormat.getText(); theme.setLabelFormat(formatText); String numFormatString = numberFormatDisplay.getFormatString(); String perFormatString = percentFormatDisplay.getFormatString(); theme.setNumberFormatString(numFormatString); theme.setPercentFormatString(perFormatString); if(visible) { DecimalFormat numF = new DecimalFormat(numFormatString); DecimalFormat perF = new DecimalFormat(perFormatString); StandardPieSectionLabelGenerator sLabelGen = new StandardPieSectionLabelGenerator( formatText, numF, perF ); piePlot.setLabelGenerator(sLabelGen); } else { piePlot.setLabelGenerator(null); } if(visible) { Font font = labelFont.getChosenFont(); theme.setLabelFont(font); piePlot.setLabelFont(font); Paint paint = labelPaint.getChosenPaint(); theme.setLabelPaint(paint); piePlot.setLabelLinkPaint(paint); paint = labelBackgroundPaint.getChosenPaint(); theme.setLabelBackgroundPaint(paint); piePlot.setLabelBackgroundPaint(paint); paint = labelOutlinePaint.getChosenPaint(); theme.setLabelOutlinePaint(paint); piePlot.setLabelOutlinePaint(paint); BasicStroke stroke = labelOutlineStroke.getChosenStroke(); theme.setLabelOutlineStroke(stroke); piePlot.setLabelOutlineStroke(stroke); RectangleInsets padding = labelPadding.getSelectedInsets(); theme.setLabelPadding(padding); piePlot.setLabelPadding(padding); Paint shadowPaint = labelShadowPaint.getChosenPaint(); theme.setLabelShadowPaint(shadowPaint); piePlot.setLabelShadowPaint(shadowPaint); boolean linkVis = labelLinkVisible.isSelected(); theme.setLabelLinksVisible(linkVis); piePlot.setLabelLinksVisible(linkVis); if(linkVis) { PieLabelLinkStyle style = (PieLabelLinkStyle) labelLinkStyle.getSelectedObject(); theme.setLabelLinkStyle(style); piePlot.setLabelLinkStyle(style); } } } if(this.shadowsVisible != null) { boolean shadowsVisible = this.shadowsVisible.isSelected(); theme.setShadowsVisible(shadowsVisible); if(plot instanceof PiePlot) { PiePlot pPlot = (PiePlot) plot; Paint shadow = shadowsVisible ? Color.LIGHT_GRAY : null; pPlot.setShadowPaint(shadow); } else if (plot instanceof CategoryPlot) { CategoryPlot cPlot = (CategoryPlot) plot; for(int i = 0; i < cPlot.getRendererCount(); i++) { if(cPlot.getRenderer(i) instanceof BarRenderer) { ((BarRenderer)cPlot.getRenderer(i)).setShadowVisible(shadowsVisible); } } } else if (plot instanceof XYPlot) { XYPlot xyPlot = (XYPlot) plot; for(int i = 0; i < xyPlot.getRendererCount(); i++) { if(xyPlot.getRenderer(i) instanceof XYBarRenderer) { ((XYBarRenderer)xyPlot.getRenderer(i)).setShadowVisible(shadowsVisible); } } } } // then the axis properties... if (this.domainAxisPropertyPanel != null) { Axis domainAxis = null; if (plot instanceof CategoryPlot) { CategoryPlot p = (CategoryPlot) plot; domainAxis = p.getDomainAxis(); } else if (plot instanceof XYPlot) { XYPlot p = (XYPlot) plot; domainAxis = p.getDomainAxis(); } if (domainAxis != null) { this.domainAxisPropertyPanel.updateChart(chart); } } if (this.rangeAxisPropertyPanel != null) { Axis rangeAxis = null; if (plot instanceof CategoryPlot) { CategoryPlot p = (CategoryPlot) plot; rangeAxis = p.getRangeAxis(); } else if (plot instanceof XYPlot) { XYPlot p = (XYPlot) plot; rangeAxis = p.getRangeAxis(); } if (rangeAxis != null) { this.rangeAxisPropertyPanel.updateChart(chart); } } if (this.plotOrientation != null) { if (plot instanceof CategoryPlot) { CategoryPlot p = (CategoryPlot) plot; p.setOrientation(this.plotOrientation); } else if (plot instanceof XYPlot) { XYPlot p = (XYPlot) plot; p.setOrientation(this.plotOrientation); } theme.setOrientation(this.plotOrientation); } applyCustomEditors(chart); } private boolean formatValid() { String format = labelFormat.getText(); try { new MessageFormat(format); return true; } catch (IllegalArgumentException e) { return false; } } public void setLiveUpdates(boolean val) { super.setLiveUpdates(val); if(domainAxisPropertyPanel != null) { domainAxisPropertyPanel.setLiveUpdates(val); } if(rangeAxisPropertyPanel != null) { rangeAxisPropertyPanel.setLiveUpdates(val); } } public void setChart(JFreeChart chart) { super.setChart(chart); if(domainAxisPropertyPanel != null) { domainAxisPropertyPanel.setChart(chart); } if(rangeAxisPropertyPanel != null) { rangeAxisPropertyPanel.setChart(chart); } } private class DocHandler implements DocumentListener, FocusListener { String lastGoodFormat = labelFormat.getText(); public void changedUpdate(DocumentEvent e) { if(formatValid()) { labelFormat.setBackground(Color.WHITE); labelFormat.setForeground(Color.BLACK); lastGoodFormat = labelFormat.getText(); updateHandler.changedUpdate(e); } else { labelFormat.setBackground(Color.RED); labelFormat.setForeground(Color.WHITE); } } public void insertUpdate(DocumentEvent e) { if(formatValid()) { labelFormat.setBackground(Color.WHITE); labelFormat.setForeground(Color.BLACK); lastGoodFormat = labelFormat.getText(); updateHandler.removeUpdate(e); } else { labelFormat.setBackground(Color.RED); labelFormat.setForeground(Color.WHITE); } } public void removeUpdate(DocumentEvent e) { if(formatValid()) { labelFormat.setBackground(Color.WHITE); labelFormat.setForeground(Color.BLACK); lastGoodFormat = labelFormat.getText(); updateHandler.removeUpdate(e); } else { labelFormat.setBackground(Color.RED); labelFormat.setForeground(Color.WHITE); } } public void focusGained(FocusEvent e) { // do nothing. } public void focusLost(FocusEvent e) { if(!formatValid()) { labelFormat.setText(lastGoodFormat); } } } }
source/org/jfree/chart/editor/DefaultPlotEditor.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * DefaultPlotEditor.java * ---------------------- * (C) Copyright 2005-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Andrzej Porebski; * Arnaud Lelievre; * Daniel Gredler; * * Changes: * -------- * 24-Nov-2005 : Version 1, based on PlotPropertyEditPanel.java (DG); * 18-Dec-2008 : Use ResourceBundleWrapper - see patch 1607918 by * Jess Thrysoee (DG); * */ package org.jfree.chart.editor; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusListener; import java.awt.event.FocusEvent; import java.util.ResourceBundle; import java.text.MessageFormat; import java.text.DecimalFormat; import javax.swing.*; import javax.swing.event.DocumentListener; import javax.swing.event.DocumentEvent; import org.jfree.chart.axis.Axis; import org.jfree.chart.plot.*; import org.jfree.chart.util.ResourceBundleWrapper; import org.jfree.chart.JFreeChart; import org.jfree.chart.labels.StandardPieSectionLabelGenerator; import org.jfree.chart.labels.StandardCategoryItemLabelGenerator; import org.jfree.chart.labels.StandardXYItemLabelGenerator; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.chart.renderer.category.CategoryItemRenderer; import org.jfree.chart.renderer.xy.XYBarRenderer; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.ui.RectangleInsets; import org.jfree.util.Rotation; import org.jfree.chart.editor.components.*; import org.jfree.chart.editor.themes.PlotTheme; import org.jfree.chart.editor.themes.ChartBorder; import org.jfree.chart.editor.themes.AxisTheme; /** * A panel for editing the properties of a {@link Plot}. */ public class DefaultPlotEditor extends BaseEditor implements ActionListener { private final static int PIE = -1, CATEGORY = -2, XY = -3; /** Orientation constants. */ private final static String[] orientationNames = {"Vertical", "Horizontal"}; private final static int ORIENTATION_VERTICAL = 0; private final static int ORIENTATION_HORIZONTAL = 1; protected PlotTheme theme; /** The panel to adjust the properties of the plot's background */ private BackgroundEditingPanel backgroundPanel; /** * A panel used to display/edit the properties of the domain axis (if any). */ private DefaultAxisEditor domainAxisPropertyPanel; /** * A panel used to display/edit the properties of the range axis (if any). */ private DefaultAxisEditor rangeAxisPropertyPanel; /** * The orientation for the plot (for <tt>CategoryPlot</tt>s and * <tt>XYPlot</tt>s). */ private PlotOrientation plotOrientation; /** * The orientation combo box (for <tt>CategoryPlot</tt>s and * <tt>XYPlot</tt>s). */ private JComboBox orientationCombo; private JCheckBox shadowsVisible; private InsetPanel axisOffset; private LineEditorPanel domainPanel, rangePanel; private BorderPanel plotBorder; private InsetPanel insetPanel; private JSpinner startAngle; private JCheckBox circularPlot; private RotationComboBox pieDirection; // label controls private JPanel labelPanel = null; private JCheckBox labelsVisible; private FontControl labelFont; private PaintControl labelPaint, labelBackgroundPaint, labelOutlinePaint, labelShadowPaint; private JCheckBox labelLinkVisible; private LinkStyleComboBox labelLinkStyle; private StrokeControl labelOutlineStroke; private InsetPanel labelPadding; private JTextField labelFormat; private NumberFormatDisplay numberFormatDisplay, percentFormatDisplay; /** The resourceBundle for the localization. */ protected static ResourceBundle localizationResources = ResourceBundleWrapper.getBundle( "org.jfree.chart.editor.LocalizationBundle"); /** * Standard constructor - constructs a panel for editing the properties of * the specified plot. * <P> * In designing the panel, we need to be aware that subclasses of Plot will * need to implement subclasses of PlotPropertyEditPanel - so we need to * leave one or two 'slots' where the subclasses can extend the user * interface. * * @param theme The theme that will be edited. * @param chart the chart, which should be changed. * @param plot the plot, which should be changed. * @param immediateUpdate Whether changes to GUI controls should immediately be applied. */ public DefaultPlotEditor(PlotTheme theme, JFreeChart chart, Plot plot, boolean immediateUpdate) { super(chart, immediateUpdate); this.theme = theme; this.backgroundPanel = new BackgroundEditingPanel(theme); this.plotOrientation = theme.getOrientation(); domainPanel = new LineEditorPanel(localizationResources.getString("Domain_Axis"), theme.isDomainGridlineVisible(), theme.getDomainGridlinePaint(), theme.getDomainGridlineStroke()); rangePanel = new LineEditorPanel(localizationResources.getString("Range_Axis"), theme.isRangeGridlinesVisible(), theme.getRangeGridlinePaint(), theme.getRangeGridlineStroke()); setLayout(new BorderLayout()); // create a panel for the settings... JPanel panel = new JPanel(new BorderLayout()); JPanel general = new JPanel(new BorderLayout()); JPanel interior = new JPanel(new GridBagLayout()); GridBagConstraints c = getNewConstraints(); interior.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5)); if (plot instanceof CategoryPlot || plot instanceof XYPlot) { startNewRow(c); boolean isVertical = this.plotOrientation.equals(PlotOrientation.VERTICAL); int index = isVertical ? ORIENTATION_VERTICAL : ORIENTATION_HORIZONTAL; interior.add( new JLabel(localizationResources.getString("Orientation")), c ); c.gridx++; c.gridwidth = 2; c.anchor = GridBagConstraints.WEST; c.fill = GridBagConstraints.NONE; this.orientationCombo = new JComboBox(orientationNames); this.orientationCombo.setSelectedIndex(index); this.orientationCombo.setActionCommand("Orientation"); this.orientationCombo.addActionListener(updateHandler); this.orientationCombo.addActionListener(this); interior.add(this.orientationCombo,c); startNewRow(c); RectangleInsets offsets = theme.getAxisOffset(); this.axisOffset = new InsetPanel(localizationResources.getString("Axis-Offset"), offsets); this.axisOffset.addChangeListener(updateHandler); c.gridwidth = 3; c.weightx = 1; interior.add(this.axisOffset, c); } if(hasPossibleShadows(plot)) { insertShadowsCheckBox(interior, c, theme.isShadowsVisible()); } startNewRow(c); c.gridwidth = 3; c.weightx = 1; insetPanel = new InsetPanel(localizationResources.getString("Insets"), theme.getInsets()); insetPanel.addChangeListener(updateHandler); interior.add(insetPanel, c); startNewRow(c); c.gridwidth = 3; c.weightx = 1; ChartBorder border = theme.getBorder(); plotBorder = new BorderPanel(localizationResources.getString("Border"), border.isVisible(), border.getStroke(), border.getPaint()); plotBorder.addChangeListener(updateHandler); interior.add(plotBorder, c); startNewRow(c); backgroundPanel.setBorder(BorderFactory.createTitledBorder( localizationResources.getString("Background") )); backgroundPanel.addChangeListener(updateHandler); c.gridwidth = 3; c.weightx = 1; interior.add(backgroundPanel,c); if(plot instanceof PiePlot) { JPanel piePanel = getPiePanel(); startNewRow(c); c.gridwidth = 3; c.weightx = 1; interior.add(piePanel, c); labelPanel = getLabelPanel(PIE); enableDisableLabelControls(); } general.add(interior, BorderLayout.NORTH); JPanel appearance = new JPanel(new BorderLayout()); appearance.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); appearance.add(general, BorderLayout.NORTH); JTabbedPane tabs = new JTabbedPane(); tabs.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5)); tabs.add(localizationResources.getString("Appearance"), new JScrollPane(appearance)); Axis domainAxis = null; if (plot instanceof CategoryPlot) { domainAxis = ((CategoryPlot) plot).getDomainAxis(); } else if (plot instanceof XYPlot) { domainAxis = ((XYPlot) plot).getDomainAxis(); } AxisTheme dAxisTheme = theme.getDomainAxisTheme(); AxisTheme rAxisTheme = theme.getRangeAxisTheme(); this.domainAxisPropertyPanel = DefaultAxisEditor.getInstance(dAxisTheme, chart, domainAxis, immediateUpdate); if (this.domainAxisPropertyPanel != null) { this.domainAxisPropertyPanel.setBorder( BorderFactory.createEmptyBorder(2, 2, 2, 2) ); tabs.add( localizationResources.getString("Domain_Axis"), new JScrollPane(this.domainAxisPropertyPanel) ); } Axis rangeAxis = null; if (plot instanceof CategoryPlot) { rangeAxis = ((CategoryPlot) plot).getRangeAxis(); labelPanel = getLabelPanel(CATEGORY); } else if (plot instanceof XYPlot) { rangeAxis = ((XYPlot) plot).getRangeAxis(); labelPanel = getLabelPanel(XY); } this.rangeAxisPropertyPanel = DefaultAxisEditor.getInstance(rAxisTheme, chart, rangeAxis, immediateUpdate); if (this.rangeAxisPropertyPanel != null) { this.rangeAxisPropertyPanel.setBorder( BorderFactory.createEmptyBorder(2, 2, 2, 2) ); tabs.add( localizationResources.getString("Range_Axis"), new JScrollPane(this.rangeAxisPropertyPanel) ); } if (plot instanceof CategoryPlot || plot instanceof XYPlot) { tabs.add(localizationResources.getString("Grid_Lines"), new JScrollPane(getGridlinesPanel())); } addCustomTabs(tabs); if(labelPanel != null) { tabs.add(localizationResources.getString("Labels"), new JScrollPane(labelPanel)); } panel.add(tabs); add(panel); } protected JPanel getLabelPanel(int plotType) { JPanel retVal = new JPanel(new GridBagLayout()); GridBagConstraints c = getNewConstraints(); labelsVisible = new JCheckBox(localizationResources.getString("Visible"), theme.isLabelsVisible()); labelsVisible.addActionListener(updateHandler); labelsVisible.addActionListener(this); labelFormat = new JTextField(theme.getLabelFormat()); DocHandler handler = new DocHandler(); labelFormat.getDocument().addDocumentListener(handler); labelFormat.addFocusListener(handler); String tip; switch(plotType) { case CATEGORY: tip = localizationResources.getString("Format_tip_cat"); break; case XY: tip = localizationResources.getString("Format_tip_xy"); break; case PIE: default: tip = localizationResources.getString("Format_tip_pie"); break; } labelFormat.setToolTipText(tip); numberFormatDisplay = buildNumberFormatDisplay(theme.getNumberFormatString()); numberFormatDisplay.addChangeListener(updateHandler); percentFormatDisplay = buildNumberFormatDisplay(theme.getPercentFormatString()); percentFormatDisplay.addChangeListener(updateHandler); labelFont = new FontControl(theme.getLabelFont()); labelFont.addChangeListener(updateHandler); labelPaint = new PaintControl(theme.getLabelPaint(), false); labelPaint.addChangeListener(updateHandler); labelBackgroundPaint = new PaintControl(theme.getLabelBackgroundPaint(), true); labelBackgroundPaint.addChangeListener(updateHandler); labelShadowPaint = new PaintControl(theme.getLabelShadowPaint(), true); labelShadowPaint.addChangeListener(updateHandler); labelOutlinePaint = new PaintControl(theme.getLabelOutlinePaint(), true); labelOutlinePaint.addChangeListener(updateHandler); labelOutlineStroke = new StrokeControl(theme.getLabelOutlineStroke()); labelOutlineStroke.addChangeListener(updateHandler); labelPadding = new InsetPanel(localizationResources.getString("Padding"), theme.getLabelPadding()); labelPadding.addChangeListener(updateHandler); labelLinkVisible = new JCheckBox(localizationResources.getString("Links_Visible"), theme.isLabelLinksVisible()); labelLinkVisible.addActionListener(updateHandler); labelLinkVisible.addActionListener(this); labelLinkStyle = new LinkStyleComboBox(); labelLinkStyle.setSelectedObject(theme.getLabelLinkStyle()); labelLinkStyle.addActionListener(updateHandler); c.gridwidth = 2; c.anchor = GridBagConstraints.WEST; retVal.add(labelsVisible, c); startNewRow(c); retVal.add(new JLabel(localizationResources.getString("Format")), c); c.gridx++; c.weightx = 1; retVal.add(labelFormat, c); startNewRow(c); retVal.add(new JLabel(localizationResources.getString("Number_Format")), c); c.gridx++; c.weightx = 1; retVal.add(numberFormatDisplay, c); startNewRow(c); retVal.add(new JLabel(localizationResources.getString("Percent_Format")), c); c.gridx++; c.weightx = 1; retVal.add(percentFormatDisplay, c); startNewRow(c); retVal.add(new JLabel(localizationResources.getString("Font")), c); c.gridx++; c.weightx = 1; retVal.add(labelFont, c); startNewRow(c); retVal.add(new JLabel(localizationResources.getString("Paint")), c); c.gridx++; c.weightx = 1; retVal.add(labelPaint, c); if (plotType == PIE) { startNewRow(c); retVal.add(new JLabel(localizationResources.getString("Background_paint")), c); c.gridx++; c.weightx = 1; retVal.add(labelBackgroundPaint, c); startNewRow(c); retVal.add(new JLabel(localizationResources.getString("Shadow_paint")), c); c.gridx++; c.weightx = 1; retVal.add(labelShadowPaint, c); startNewRow(c); retVal.add(new JLabel(localizationResources.getString("Outline_Paint")), c); c.gridx++; c.weightx = 1; retVal.add(labelOutlinePaint, c); startNewRow(c); retVal.add(new JLabel(localizationResources.getString("Outline_stroke")), c); c.gridx++; c.weightx = 1; retVal.add(labelOutlineStroke, c); startNewRow(c); c.gridwidth = 2; c.anchor = GridBagConstraints.WEST; retVal.add(labelLinkVisible, c); startNewRow(c); retVal.add(new JLabel(localizationResources.getString("Link_Style")), c); c.gridx++; c.weightx = 1; retVal.add(labelLinkStyle, c); startNewRow(c); c.gridwidth = 2; c.weightx = 1; retVal.add(labelPadding, c); } startNewRow(c); c.fill = GridBagConstraints.VERTICAL; c.weighty = 1; retVal.add(new JPanel(), c); return retVal; } protected NumberFormatDisplay buildNumberFormatDisplay(String formatStr) { return new NumberFormatDisplay(formatStr); } protected JPanel getGridlinesPanel() { JPanel retVal = new JPanel(new GridBagLayout()); domainPanel.addChangeListener(updateHandler); rangePanel.addChangeListener(updateHandler); GridBagConstraints c = getNewConstraints(); c.weightx = 1; retVal.add(domainPanel, c); startNewRow(c); c.weightx = 1; retVal.add(rangePanel, c); startNewRow(c); c.fill = GridBagConstraints.BOTH; c.weighty = 1; retVal.add(new JPanel(), c); return retVal; } private JPanel getPiePanel() { JPanel retVal = new JPanel(new GridBagLayout()); retVal.setBorder(BorderFactory.createTitledBorder(localizationResources.getString("Pie"))); GridBagConstraints c = getNewConstraints(); circularPlot = new JCheckBox(localizationResources.getString("Circular"), theme.isCircularPie()); circularPlot.addActionListener(updateHandler); pieDirection = new RotationComboBox(); pieDirection.setSelectedObject(theme.getPieDirection()); pieDirection.addActionListener(updateHandler); startAngle = new JSpinner(new SpinnerNumberModel(theme.getStartAngle(), 0, 360, 1)); startAngle.addChangeListener(updateHandler); c.gridwidth = 2; c.anchor = GridBagConstraints.WEST; retVal.add(circularPlot, c); startNewRow(c); retVal.add(new JLabel(localizationResources.getString("Pie_Direction")), c); c.gridx++; c.weightx = 1; retVal.add(pieDirection, c); startNewRow(c); retVal.add(new JLabel(localizationResources.getString("Start_Position_Degs")), c); c.gridx++; c.weightx = 1; retVal.add(startAngle, c); return retVal; } private boolean hasPossibleShadows(Plot plot) { if(plot instanceof PiePlot) { return true; } else if (plot instanceof CategoryPlot) { CategoryPlot cPlot = (CategoryPlot) plot; for(int i=0; i < cPlot.getRendererCount(); i++) { if(cPlot.getRenderer(i) instanceof BarRenderer) { return true; } } } else if (plot instanceof XYPlot) { XYPlot xyPlot = (XYPlot) plot; for(int i=0; i < xyPlot.getRendererCount(); i++) { if(xyPlot.getRenderer(i) instanceof XYBarRenderer) { return true; } } } return false; } private void insertShadowsCheckBox(JPanel interior, GridBagConstraints c, boolean shadowVisible) { startNewRow(c); c.gridwidth = 2; c.anchor = GridBagConstraints.WEST; shadowsVisible = new JCheckBox(localizationResources.getString("Shadows_Visible")); shadowsVisible.setSelected(shadowVisible); shadowsVisible.addActionListener(updateHandler); interior.add(shadowsVisible, c); } /** * Returns the current outline stroke. * * @return The current outline stroke. */ public Stroke getOutlineStroke() { return this.plotBorder.getBorderStroke(); } /** * Returns the current outline paint. * * @return The current outline paint. */ public Paint getOutlinePaint() { return this.plotBorder.getBorderPaint(); } /** * Returns a reference to the panel for editing the properties of the * domain axis. * * @return A reference to a panel. */ public DefaultAxisEditor getDomainAxisPropertyEditPanel() { return this.domainAxisPropertyPanel; } /** * Returns a reference to the panel for editing the properties of the * range axis. * * @return A reference to a panel. */ public DefaultAxisEditor getRangeAxisPropertyEditPanel() { return this.rangeAxisPropertyPanel; } public RectangleInsets getAxisOffset() { return axisOffset.getSelectedInsets(); } /** * Handles user actions generated within the panel. * @param event the event */ public void actionPerformed(ActionEvent event) { String command = event.getActionCommand(); if (command.equals("Orientation")) { attemptOrientationSelection(); } else if (event.getSource() == labelsVisible) { enableDisableLabelControls(); } } private void enableDisableLabelControls() { boolean b = labelsVisible.isSelected(); boolean l = labelLinkVisible.isSelected(); labelFont.setEnabled(b); labelPaint.setEnabled(b); labelBackgroundPaint.setEnabled(b); labelShadowPaint.setEnabled(b); labelOutlinePaint.setEnabled(b); labelOutlineStroke.setEnabled(b); labelPadding.setEnabled(b); labelFormat.setEnabled(b); numberFormatDisplay.setEnabled(b); percentFormatDisplay.setEnabled(b); labelLinkVisible.setEnabled(b); labelLinkStyle.setEnabled(b&&l); } /** * Allow the user to modify the plot orientation if this is an editor for a * <tt>CategoryPlot</tt> or a <tt>XYPlot</tt>. */ private void attemptOrientationSelection() { int index = this.orientationCombo.getSelectedIndex(); if (index == ORIENTATION_VERTICAL) { this.plotOrientation = PlotOrientation.VERTICAL; } else { this.plotOrientation = PlotOrientation.HORIZONTAL; } } /** * Updates the plot properties to match the properties defined on the panel. * * @param chart The chart. */ public void updateChart(JFreeChart chart) { Plot plot = chart.getPlot(); // set the plot properties... boolean pBorderVisible = plotBorder.isBorderVisible(); theme.setBorder(pBorderVisible, getOutlinePaint(), (BasicStroke) getOutlineStroke()); plot.setOutlineVisible(pBorderVisible); plot.setOutlinePaint(getOutlinePaint()); plot.setOutlineStroke(getOutlineStroke()); RectangleInsets plotInsets = insetPanel.getSelectedInsets(); theme.setInsets(plotInsets); plot.setInsets(plotInsets); plot.setBackgroundPaint(backgroundPanel.getBackgroundPaint()); theme.setPlotBackgroundPaint(backgroundPanel.getBackgroundPaint()); if(plot instanceof CategoryPlot) { CategoryPlot cPlot = (CategoryPlot) plot; RectangleInsets offset = axisOffset.getSelectedInsets(); cPlot.setAxisOffset(offset); theme.setAxisOffset(offset); boolean domVis = domainPanel.isLineVisible(); cPlot.setDomainGridlinesVisible(domVis); theme.setDomainGridlineVisible(domVis); boolean ranVis = rangePanel.isLineVisible(); cPlot.setRangeGridlinesVisible(ranVis); theme.setRangeGridlinesVisible(ranVis); Paint domPaint = domainPanel.getLinePaint(); BasicStroke domStroke = domainPanel.getLineStroke(); cPlot.setDomainGridlinePaint(domPaint); theme.setDomainGridlinePaint(domPaint); cPlot.setDomainGridlineStroke(domStroke); theme.setDomainGridlineStroke(domStroke); Paint ranPaint = rangePanel.getLinePaint(); BasicStroke ranStroke = rangePanel.getLineStroke(); cPlot.setRangeGridlinePaint(ranPaint); theme.setRangeGridlinePaint(ranPaint); cPlot.setRangeGridlineStroke(ranStroke); theme.setRangeGridlineStroke(ranStroke); CategoryItemRenderer renderer = cPlot.getRenderer(); boolean labelsVis = labelsVisible.isSelected(); renderer.setBaseItemLabelsVisible(labelsVis); theme.setLabelsVisible(labelsVis); Font labelFont = this.labelFont.getChosenFont(); renderer.setBaseItemLabelFont(labelFont); theme.setLabelFont(labelFont); Paint labelPaint = this.labelPaint.getChosenPaint(); renderer.setBaseItemLabelPaint(labelPaint); theme.setLabelPaint(labelPaint); String formatText = labelFormat.getText(); theme.setLabelFormat(formatText); String numFormatString = numberFormatDisplay.getFormatString(); String perFormatString = percentFormatDisplay.getFormatString(); theme.setNumberFormatString(numFormatString); theme.setPercentFormatString(perFormatString); DecimalFormat numF = new DecimalFormat(numFormatString); DecimalFormat perF = new DecimalFormat(perFormatString); StandardCategoryItemLabelGenerator sLabelGen = new StandardCategoryItemLabelGenerator( formatText, numF, perF ); renderer.setBaseItemLabelGenerator(sLabelGen); } else if (plot instanceof XYPlot) { XYPlot xyPlot = (XYPlot) plot; RectangleInsets offset = axisOffset.getSelectedInsets(); xyPlot.setAxisOffset(offset); theme.setAxisOffset(offset); boolean domVis = domainPanel.isLineVisible(); xyPlot.setDomainGridlinesVisible(domVis); theme.setDomainGridlineVisible(domVis); boolean ranVis = rangePanel.isLineVisible(); xyPlot.setRangeGridlinesVisible(ranVis); theme.setRangeGridlinesVisible(ranVis); Paint domPaint = domainPanel.getLinePaint(); BasicStroke domStroke = domainPanel.getLineStroke(); xyPlot.setDomainGridlinePaint(domPaint); theme.setDomainGridlinePaint(domPaint); xyPlot.setDomainGridlineStroke(domStroke); theme.setDomainGridlineStroke(domStroke); Paint ranPaint = rangePanel.getLinePaint(); BasicStroke ranStroke = rangePanel.getLineStroke(); xyPlot.setRangeGridlinePaint(ranPaint); theme.setRangeGridlinePaint(ranPaint); xyPlot.setRangeGridlineStroke(ranStroke); theme.setRangeGridlineStroke(ranStroke); XYItemRenderer renderer = xyPlot.getRenderer(); boolean labelsVis = labelsVisible.isSelected(); renderer.setBaseItemLabelsVisible(labelsVis); theme.setLabelsVisible(labelsVis); Font labelFont = this.labelFont.getChosenFont(); renderer.setBaseItemLabelFont(labelFont); theme.setLabelFont(labelFont); Paint labelPaint = this.labelPaint.getChosenPaint(); renderer.setBaseItemLabelPaint(labelPaint); theme.setLabelPaint(labelPaint); String formatText = labelFormat.getText(); theme.setLabelFormat(formatText); String numFormatString = numberFormatDisplay.getFormatString(); String perFormatString = percentFormatDisplay.getFormatString(); theme.setNumberFormatString(numFormatString); theme.setPercentFormatString(perFormatString); // 2 copies for thread safety. DecimalFormat numF = new DecimalFormat(numFormatString); DecimalFormat numF2 = new DecimalFormat(numFormatString); StandardXYItemLabelGenerator sLabelGen = new StandardXYItemLabelGenerator( formatText, numF, numF2 ); renderer.setBaseItemLabelGenerator(sLabelGen); } else if (plot instanceof PiePlot) { PiePlot piePlot = (PiePlot) plot; boolean circular = circularPlot.isSelected(); theme.setCircularPie(circular); piePlot.setCircular(circular); double angle = ((Number)startAngle.getValue()).doubleValue(); theme.setStartAngle(angle); piePlot.setStartAngle(angle); Rotation direction = (Rotation)pieDirection.getSelectedObject(); theme.setPieDirection(direction); piePlot.setDirection(direction); boolean visible = labelsVisible.isSelected(); theme.setLabelsVisible(visible); String formatText = labelFormat.getText(); theme.setLabelFormat(formatText); String numFormatString = numberFormatDisplay.getFormatString(); String perFormatString = percentFormatDisplay.getFormatString(); theme.setNumberFormatString(numFormatString); theme.setPercentFormatString(perFormatString); if(visible) { DecimalFormat numF = new DecimalFormat(numFormatString); DecimalFormat perF = new DecimalFormat(perFormatString); StandardPieSectionLabelGenerator sLabelGen = new StandardPieSectionLabelGenerator( formatText, numF, perF ); piePlot.setLabelGenerator(sLabelGen); } else { piePlot.setLabelGenerator(null); } if(visible) { Font font = labelFont.getChosenFont(); theme.setLabelFont(font); piePlot.setLabelFont(font); Paint paint = labelPaint.getChosenPaint(); theme.setLabelPaint(paint); piePlot.setLabelLinkPaint(paint); paint = labelBackgroundPaint.getChosenPaint(); theme.setLabelBackgroundPaint(paint); piePlot.setLabelBackgroundPaint(paint); paint = labelOutlinePaint.getChosenPaint(); theme.setLabelOutlinePaint(paint); piePlot.setLabelOutlinePaint(paint); BasicStroke stroke = labelOutlineStroke.getChosenStroke(); theme.setLabelOutlineStroke(stroke); piePlot.setLabelOutlineStroke(stroke); RectangleInsets padding = labelPadding.getSelectedInsets(); theme.setLabelPadding(padding); piePlot.setLabelPadding(padding); Paint shadowPaint = labelShadowPaint.getChosenPaint(); theme.setLabelShadowPaint(shadowPaint); piePlot.setLabelShadowPaint(shadowPaint); boolean linkVis = labelLinkVisible.isSelected(); theme.setLabelLinksVisible(linkVis); piePlot.setLabelLinksVisible(linkVis); if(linkVis) { PieLabelLinkStyle style = (PieLabelLinkStyle) labelLinkStyle.getSelectedObject(); theme.setLabelLinkStyle(style); piePlot.setLabelLinkStyle(style); } } } if(this.shadowsVisible != null) { boolean shadowsVisible = this.shadowsVisible.isSelected(); theme.setShadowsVisible(shadowsVisible); if(plot instanceof PiePlot) { PiePlot pPlot = (PiePlot) plot; Paint shadow = shadowsVisible ? Color.LIGHT_GRAY : null; pPlot.setShadowPaint(shadow); } else if (plot instanceof CategoryPlot) { CategoryPlot cPlot = (CategoryPlot) plot; for(int i = 0; i < cPlot.getRendererCount(); i++) { if(cPlot.getRenderer(i) instanceof BarRenderer) { ((BarRenderer)cPlot.getRenderer(i)).setShadowVisible(shadowsVisible); } } } else if (plot instanceof XYPlot) { XYPlot xyPlot = (XYPlot) plot; for(int i = 0; i < xyPlot.getRendererCount(); i++) { if(xyPlot.getRenderer(i) instanceof XYBarRenderer) { ((XYBarRenderer)xyPlot.getRenderer(i)).setShadowVisible(shadowsVisible); } } } } // then the axis properties... if (this.domainAxisPropertyPanel != null) { Axis domainAxis = null; if (plot instanceof CategoryPlot) { CategoryPlot p = (CategoryPlot) plot; domainAxis = p.getDomainAxis(); } else if (plot instanceof XYPlot) { XYPlot p = (XYPlot) plot; domainAxis = p.getDomainAxis(); } if (domainAxis != null) { this.domainAxisPropertyPanel.updateChart(chart); } } if (this.rangeAxisPropertyPanel != null) { Axis rangeAxis = null; if (plot instanceof CategoryPlot) { CategoryPlot p = (CategoryPlot) plot; rangeAxis = p.getRangeAxis(); } else if (plot instanceof XYPlot) { XYPlot p = (XYPlot) plot; rangeAxis = p.getRangeAxis(); } if (rangeAxis != null) { this.rangeAxisPropertyPanel.updateChart(chart); } } if (this.plotOrientation != null) { if (plot instanceof CategoryPlot) { CategoryPlot p = (CategoryPlot) plot; p.setOrientation(this.plotOrientation); } else if (plot instanceof XYPlot) { XYPlot p = (XYPlot) plot; p.setOrientation(this.plotOrientation); } theme.setOrientation(this.plotOrientation); } applyCustomEditors(chart); } private boolean formatValid() { String format = labelFormat.getText(); try { new MessageFormat(format); return true; } catch (IllegalArgumentException e) { return false; } } public void setLiveUpdates(boolean val) { super.setLiveUpdates(val); if(domainAxisPropertyPanel != null) { domainAxisPropertyPanel.setLiveUpdates(val); } if(rangeAxisPropertyPanel != null) { rangeAxisPropertyPanel.setLiveUpdates(val); } } public void setChart(JFreeChart chart) { super.setChart(chart); domainAxisPropertyPanel.setChart(chart); rangeAxisPropertyPanel.setChart(chart); } private class DocHandler implements DocumentListener, FocusListener { String lastGoodFormat = labelFormat.getText(); public void changedUpdate(DocumentEvent e) { if(formatValid()) { labelFormat.setBackground(Color.WHITE); labelFormat.setForeground(Color.BLACK); lastGoodFormat = labelFormat.getText(); updateHandler.changedUpdate(e); } else { labelFormat.setBackground(Color.RED); labelFormat.setForeground(Color.WHITE); } } public void insertUpdate(DocumentEvent e) { if(formatValid()) { labelFormat.setBackground(Color.WHITE); labelFormat.setForeground(Color.BLACK); lastGoodFormat = labelFormat.getText(); updateHandler.removeUpdate(e); } else { labelFormat.setBackground(Color.RED); labelFormat.setForeground(Color.WHITE); } } public void removeUpdate(DocumentEvent e) { if(formatValid()) { labelFormat.setBackground(Color.WHITE); labelFormat.setForeground(Color.BLACK); lastGoodFormat = labelFormat.getText(); updateHandler.removeUpdate(e); } else { labelFormat.setBackground(Color.RED); labelFormat.setForeground(Color.WHITE); } } public void focusGained(FocusEvent e) { // do nothing. } public void focusLost(FocusEvent e) { if(!formatValid()) { labelFormat.setText(lastGoodFormat); } } } }
Fix for an NPE in some circumstances.
source/org/jfree/chart/editor/DefaultPlotEditor.java
Fix for an NPE in some circumstances.
Java
lgpl-2.1
00901c7b4fb49423c43d2ce35b8980d8b2bbd1e2
0
ggiudetti/opencms-core,gallardo/opencms-core,MenZil/opencms-core,victos/opencms-core,MenZil/opencms-core,victos/opencms-core,sbonoc/opencms-core,it-tavis/opencms-core,serrapos/opencms-core,serrapos/opencms-core,serrapos/opencms-core,it-tavis/opencms-core,serrapos/opencms-core,alkacon/opencms-core,mediaworx/opencms-core,mediaworx/opencms-core,alkacon/opencms-core,MenZil/opencms-core,victos/opencms-core,gallardo/opencms-core,sbonoc/opencms-core,mediaworx/opencms-core,sbonoc/opencms-core,alkacon/opencms-core,it-tavis/opencms-core,alkacon/opencms-core,MenZil/opencms-core,victos/opencms-core,ggiudetti/opencms-core,serrapos/opencms-core,ggiudetti/opencms-core,it-tavis/opencms-core,ggiudetti/opencms-core,gallardo/opencms-core,mediaworx/opencms-core,sbonoc/opencms-core,gallardo/opencms-core,serrapos/opencms-core,serrapos/opencms-core
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software GmbH, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.setup.comptest; import org.opencms.setup.CmsSetupBean; /** * Tests the servlet container.<p> * * @since 6.1.8 */ public class CmsSetupTestServletContainer implements I_CmsSetupTest { /** The test name. */ public static final String TEST_NAME = "Servlet Container"; /** * @see org.opencms.setup.comptest.I_CmsSetupTest#execute(org.opencms.setup.CmsSetupBean) */ public CmsSetupTestResult execute(CmsSetupBean setupBean) { CmsSetupTestResult testResult = new CmsSetupTestResult(this); String[][] supportedContainers = { {"Apache Tomcat/4.1", null}, {"Apache Tomcat/5", null}, {"Apache Tomcat/6", null}, {"Apache Tomcat/7", null}, {"WebLogic Server 9", null}, { "Resin/3", "Please be sure that during the Setup Wizard, the web application auto-redeployment feature is deactivated. One way to achieve this, is to set the '<code>dependency-check-interval</code>' option in your <code>resin.conf</code> configuration file to <code>-1</code> or something big like <code>2000s</code>."}, { "IBM WebSphere Application Server/6", "The only limitation found so far, is that when using the <code>sendRedirect</code> method you have always to use an absolute path."}, {"Sun GlassFish Enterprise Server v2.1", null}, { "GlassFish/v3", "GlassFish/v3 is not a stable release and subject to major changes. Please prefer a stable release."}, {"JBoss Web/2.1.3.GA", null}}; String[][] unsupportedContainers = { {"Tomcat Web Server/3", "Tomcat 3.x is no longer supported. Please use at least Tomcat 4.1 instead."}, {"Apache Tomcat/4.0", "Tomcat 4.0.x is no longer supported. Please use at least Tomcat 4.1 instead."}, {"Resin/2", "The OpenCms JSP integration does not work with Resin 2.x. Please use Resin 3 instead."}, { "IBM WebSphere Application Server/5", "OpenCms has problems with the way Websphere handles the <code>sendRedirect</code> method. Please use at least WebSphere 6 instead."}}; String servletContainer = setupBean.getServletConfig().getServletContext().getServerInfo(); testResult.setResult(servletContainer); int supportedServletContainer = hasSupportedServletContainer(servletContainer, supportedContainers); int unsupportedServletContainer = unsupportedServletContainer(servletContainer, unsupportedContainers); if (unsupportedServletContainer > -1) { testResult.setRed(); testResult.setInfo(unsupportedContainers[unsupportedServletContainer][1]); testResult.setHelp("This servlet container does not work with OpenCms. Even though OpenCms is fully standards compliant, " + "the standard leaves some 'grey' (i.e. undefined) areas. " + "Please consider using another, supported servlet container."); } else if (supportedServletContainer < 0) { testResult.setYellow(); testResult.setHelp("This servlet container has not been tested with OpenCms. Please consider using another, supported servlet container."); } else if (supportedContainers[supportedServletContainer][1] != null) { // set additional info for supported servlet containers testResult.setInfo(supportedContainers[supportedServletContainer][1]); } else { testResult.setGreen(); } return testResult; } /** * @see org.opencms.setup.comptest.I_CmsSetupTest#getName() */ public String getName() { return TEST_NAME; } /** * Checks if the used servlet container is part of the servlet containers OpenCms supports.<p> * * @param thisContainer The servlet container in use * @param supportedContainers All known servlet containers OpenCms supports * * @return true if this container is supported, false if it was not found in the list */ private int hasSupportedServletContainer(String thisContainer, String[][] supportedContainers) { for (int i = 0; i < supportedContainers.length; i++) { if (thisContainer.indexOf(supportedContainers[i][0]) >= 0) { return i; } } return -1; } /** * Checks if the used servlet container is part of the servlet containers OpenCms * does NOT support.<p> * * @param thisContainer the servlet container in use * @param unsupportedContainers all known servlet containers OpenCms does NOT support * * @return the container id or -1 if the container is not supported */ private int unsupportedServletContainer(String thisContainer, String[][] unsupportedContainers) { for (int i = 0; i < unsupportedContainers.length; i++) { if (thisContainer.indexOf(unsupportedContainers[i][0]) >= 0) { return i; } } return -1; } }
src-setup/org/opencms/setup/comptest/CmsSetupTestServletContainer.java
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software GmbH, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.setup.comptest; import org.opencms.setup.CmsSetupBean; /** * Tests the servlet container.<p> * * @since 6.1.8 */ public class CmsSetupTestServletContainer implements I_CmsSetupTest { /** The test name. */ public static final String TEST_NAME = "Servlet Container"; /** * @see org.opencms.setup.comptest.I_CmsSetupTest#execute(org.opencms.setup.CmsSetupBean) */ public CmsSetupTestResult execute(CmsSetupBean setupBean) { CmsSetupTestResult testResult = new CmsSetupTestResult(this); String[][] supportedContainers = { {"Apache Tomcat/4.1", null}, {"Apache Tomcat/5", null}, {"Apache Tomcat/6", null}, {"WebLogic Server 9", null}, { "Resin/3", "Please be sure that during the Setup Wizard, the web application auto-redeployment feature is deactivated. One way to achieve this, is to set the '<code>dependency-check-interval</code>' option in your <code>resin.conf</code> configuration file to <code>-1</code> or something big like <code>2000s</code>."}, { "IBM WebSphere Application Server/6", "The only limitation found so far, is that when using the <code>sendRedirect</code> method you have always to use an absolute path."}, {"Sun GlassFish Enterprise Server v2.1", null}, { "GlassFish/v3", "GlassFish/v3 is not a stable release and subject to major changes. Please prefer a stable release."}, {"JBoss Web/2.1.3.GA", null} }; String[][] unsupportedContainers = { {"Tomcat Web Server/3", "Tomcat 3.x is no longer supported. Please use at least Tomcat 4.1 instead."}, {"Apache Tomcat/4.0", "Tomcat 4.0.x is no longer supported. Please use at least Tomcat 4.1 instead."}, {"Resin/2", "The OpenCms JSP integration does not work with Resin 2.x. Please use Resin 3 instead."}, { "IBM WebSphere Application Server/5", "OpenCms has problems with the way Websphere handles the <code>sendRedirect</code> method. Please use at least WebSphere 6 instead."}}; String servletContainer = setupBean.getServletConfig().getServletContext().getServerInfo(); testResult.setResult(servletContainer); int supportedServletContainer = hasSupportedServletContainer(servletContainer, supportedContainers); int unsupportedServletContainer = unsupportedServletContainer(servletContainer, unsupportedContainers); if (unsupportedServletContainer > -1) { testResult.setRed(); testResult.setInfo(unsupportedContainers[unsupportedServletContainer][1]); testResult.setHelp("This servlet container does not work with OpenCms. Even though OpenCms is fully standards compliant, " + "the standard leaves some 'grey' (i.e. undefined) areas. " + "Please consider using another, supported servlet container."); } else if (supportedServletContainer < 0) { testResult.setYellow(); testResult.setHelp("This servlet container has not been tested with OpenCms. Please consider using another, supported servlet container."); } else if (supportedContainers[supportedServletContainer][1] != null) { // set additional info for supported servlet containers testResult.setInfo(supportedContainers[supportedServletContainer][1]); } else { testResult.setGreen(); } return testResult; } /** * @see org.opencms.setup.comptest.I_CmsSetupTest#getName() */ public String getName() { return TEST_NAME; } /** * Checks if the used servlet container is part of the servlet containers OpenCms supports.<p> * * @param thisContainer The servlet container in use * @param supportedContainers All known servlet containers OpenCms supports * * @return true if this container is supported, false if it was not found in the list */ private int hasSupportedServletContainer(String thisContainer, String[][] supportedContainers) { for (int i = 0; i < supportedContainers.length; i++) { if (thisContainer.indexOf(supportedContainers[i][0]) >= 0) { return i; } } return -1; } /** * Checks if the used servlet container is part of the servlet containers OpenCms * does NOT support.<p> * * @param thisContainer the servlet container in use * @param unsupportedContainers all known servlet containers OpenCms does NOT support * * @return the container id or -1 if the container is not supported */ private int unsupportedServletContainer(String thisContainer, String[][] unsupportedContainers) { for (int i = 0; i < unsupportedContainers.length; i++) { if (thisContainer.indexOf(unsupportedContainers[i][0]) >= 0) { return i; } } return -1; } }
Added Tomcat 7 to supported servlet container list.
src-setup/org/opencms/setup/comptest/CmsSetupTestServletContainer.java
Added Tomcat 7 to supported servlet container list.
Java
apache-2.0
798ec29915362e0231ea6bffd623e8a69db26d2b
0
Waniusza/Losowosc
package com.dam; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; import javax.swing.JPanel; import javax.swing.Timer; class los extends JPanel implements ActionListener { private static long MOD = (Long.MAX_VALUE/2); private final int DELAY = 150; private Timer timer; public los() { initTimer(); } private void initTimer() { timer = new Timer(DELAY, this); timer.start(); } public Timer getTimer() { return timer; } private void doDrawing(Graphics g) { Generator generator = new Generator(MOD); int[] statsX = new int[10]; int[] statsY = new int[10]; Graphics2D g2d = (Graphics2D) g; g2d.setPaint(Color.red); for (int i=0 ; i<1000 ; i++) { long[] coordinates = generator.getCoordinates(); int w = 500; //width int h = 500; //height Random r = new Random(); float x = (float) coordinates[0] / MOD; float y = (float) coordinates[1] / MOD; statsX[(int)(x*10)]++; statsY[(int)(y*10)]++; System.out.println("Wygenerowa�em punkt : (" + x + " | " + y + ")"); int xx = Math.round(x) % w; int yy = Math.round(y) % h; g2d.drawLine(xx, yy, xx, yy); //RYSOWANIE /* for (int j = 0; j < 1000; j++) { int xx = Math.round(x) % w; int yy = Math.round(y) % h; g2d.drawLine(xx, yy, xx, yy); } */ } } @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } @Override public void actionPerformed(ActionEvent e) { } }
Losowosc/src/com/dam/los.java
package com.dam; import java.util.Arrays; import java.util.List; /** * * @author waniusza && damian */ public class los { private static long MOD = (Long.MAX_VALUE/2); /** * @param args the command line arguments */ public static void main(String[] args) { /* * zainicjalizowanie tabeli OXY s */ Generator generator = new Generator(MOD); int[] statsX = new int[10]; int[] statsY = new int[10]; for (int i=0 ; i<1000 ; i++) { long[] coordinates = generator.getCoordinates(); float x = (float) coordinates[0] / MOD; float y = (float) coordinates[1] / MOD; statsX[(int)(x*10)]++; statsY[(int)(y*10)]++; System.out.println("Wygenerowałem punkt : (" + x + " | " + y + ")"); /* * wypełnienie punktu (x|y) kolorem */ } System.out.println("Statystyka podpowiada: "); System.out.println("Równość rozproszenie na osi X : " + Arrays.toString(statsX)); System.out.println("Równość rozproszenie na osi Y : " + Arrays.toString(statsY)); } }
-Dodanie okna menu głównego wraz z polami i buttonem. -Wyświetlanie okna rysowania punktów.
Losowosc/src/com/dam/los.java
-Dodanie okna menu głównego wraz z polami i buttonem. -Wyświetlanie okna rysowania punktów.
Java
apache-2.0
17deb2cd7345acb188b10ebb4e23c5bc962be587
0
metatron-app/metatron-discovery,metatron-app/metatron-discovery,metatron-app/metatron-discovery,metatron-app/metatron-discovery,metatron-app/metatron-discovery,metatron-app/metatron-discovery,metatron-app/metatron-discovery
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.metatron.discovery.domain.workspace; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.querydsl.core.BooleanBuilder; import com.querydsl.core.types.Predicate; import com.querydsl.core.types.dsl.BooleanExpression; import com.querydsl.jpa.JPAExpressions; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import app.metatron.discovery.common.MatrixResponse; import app.metatron.discovery.common.exception.BadRequestException; import app.metatron.discovery.common.exception.ResourceNotFoundException; import app.metatron.discovery.domain.CollectionPatch; import app.metatron.discovery.domain.activities.ActivityStreamService; import app.metatron.discovery.domain.dataconnection.DataConnection; import app.metatron.discovery.domain.dataconnection.DataConnectionPredicate; import app.metatron.discovery.domain.dataconnection.DataConnectionRepository; import app.metatron.discovery.domain.datasource.DataSourceRepository; import app.metatron.discovery.domain.datasource.QDataSource; import app.metatron.discovery.domain.user.CachedUserService; import app.metatron.discovery.domain.user.DirectoryProfile; import app.metatron.discovery.domain.user.User; import app.metatron.discovery.domain.user.group.Group; import app.metatron.discovery.domain.user.group.GroupRepository; import app.metatron.discovery.domain.user.group.GroupService; import app.metatron.discovery.domain.user.role.Role; import app.metatron.discovery.domain.user.role.RoleRepository; import app.metatron.discovery.domain.user.role.RoleService; import app.metatron.discovery.domain.user.role.RoleSet; import app.metatron.discovery.domain.user.role.RoleSetRepository; import app.metatron.discovery.domain.user.role.RoleSetService; import app.metatron.discovery.domain.workbook.configurations.format.TimeFieldFormat; import app.metatron.discovery.util.AuthUtils; import app.metatron.discovery.util.EnumUtils; import static app.metatron.discovery.domain.workspace.Workspace.PublicType.SHARED; import static app.metatron.discovery.domain.workspace.WorkspacePermissions.PERM_WORKSPACE_EDIT_WORKBENCH; import static app.metatron.discovery.domain.workspace.WorkspacePermissions.PERM_WORKSPACE_MANAGE_WORKBENCH; /** * Created by kyungtaak on 2017. 7. 23.. */ @Component @Transactional(readOnly = true) public class WorkspaceService { private static Logger LOGGER = LoggerFactory.getLogger(WorkspaceService.class); @Autowired ActivityStreamService activityStreamService; @Autowired GroupService groupService; @Autowired GroupRepository groupRepository; @Autowired RoleService roleService; @Autowired RoleSetService roleSetService; @Autowired CachedUserService cachedUserService; @Autowired DataSourceRepository dataSourceRepository; @Autowired WorkspaceRepository workspaceRepository; @Autowired WorkspaceMemberRepository workspaceMemberRepository; @Autowired WorkspaceFavoriteRepository workspaceFavoriteRepository; @Autowired RoleSetRepository roleSetRepository; @Autowired RoleRepository roleRepository; @Autowired DataConnectionRepository connectionRepository; @Transactional public Workspace createWorkspaceByUserCreation(User user, boolean ifExistThrowException) { // 워크스페이스 생성(등록된 워크스페이스가 없을 경우 생성) Workspace checkedWorkspace = workspaceRepository.findPrivateWorkspaceByOwnerId(user.getUsername()); if(checkedWorkspace != null) { if (ifExistThrowException ) { throw new RuntimeException("Workspace already exist."); } else { return checkedWorkspace; } } Workspace createWorkspace = new Workspace(); createWorkspace.setPublicType(Workspace.PublicType.PRIVATE); createWorkspace.setName(user.getFullName() + " Workspace"); createWorkspace.setOwnerId(user.getUsername()); if(StringUtils.isNotEmpty(user.getWorkspaceType()) && Workspace.workspaceTypes.contains(user.getWorkspaceType())) { createWorkspace.setType(user.getWorkspaceType()); } else { createWorkspace.setType(Workspace.workspaceTypes.get(0)); // "DEFAULT" 셋팅 } return workspaceRepository.saveAndFlush(createWorkspace); } /** * Workspace 접근 시간 지정 */ @Transactional public void updateLastAccessedTime(String workspaceId) { workspaceRepository.updateLastAccessedTime(workspaceId); } /** * 사용자 삭제시 Workspace 처리 */ @Transactional public void disableWorkspaceAndMember(String username, Map<String, String> delegateePair) { // Workspace Owner 인 경우 처리, 위임자 정보가 없는 경우, 전체 Inactive 시킴 if(MapUtils.isEmpty(delegateePair)) { workspaceRepository.updateInactiveWorkspaceAndChangeKnownOwnerId(username, Workspace.PublicType.PRIVATE, Workspace.PublicType.SHARED); } else { // 개인 워크스페이스만 비활성화 시킵니다 workspaceRepository.updateInactiveWorkspaceOfOwner(username, Workspace.PublicType.PRIVATE); // TODO: delegateePair 를 통해 위임합니다 } // Workspace Member 로 포함된 경우 삭제 workspaceMemberRepository.deleteByMemberIds(Lists.newArrayList(username)); // Workspace Favorite 삭제 workspaceFavoriteRepository.deleteByUsername(username); } /** * 사용자 삭제시 Workspace 삭제 */ @Transactional public void deleteWorkspaceAndMember(String username) { // PRIVATE workspace 삭제 Workspace workspace = workspaceRepository.findPrivateWorkspaceByOwnerId(username); if(workspace == null) { LOGGER.warn("Fail to find private workspace : {}", username); } else { workspaceRepository.delete(workspace); } // Workspace Member 로 포함된 경우 삭제 workspaceMemberRepository.deleteByMemberIds(Lists.newArrayList(username)); // Workspace Favorite 삭제 workspaceFavoriteRepository.deleteByUsername(username); } public Integer countAvailableWorkspaces(String workspaceId) { BooleanBuilder builder = new BooleanBuilder(); QDataSource dataSource = QDataSource.dataSource; // 전체 공개 Sub-Query BooleanExpression published = dataSource.id .in(JPAExpressions.select(dataSource.id) .from(dataSource) .where(dataSource.published.eq(true))); // Workspace 내 포함된 Datasource 조회 Sub-Query BooleanExpression workspaceContains = dataSource.id .in(JPAExpressions.select(dataSource.id) .from(dataSource) .innerJoin(dataSource.workspaces) .where(dataSource.workspaces.any().id.eq(workspaceId))); builder = builder.andAnyOf(workspaceContains, published); long count = dataSourceRepository.count(builder); return (int) count; } /** * * @param workbookId * @param workspaceId * @return */ public boolean checkWorkBookCopyToWorkspace(String workbookId, String workspaceId) { List<String> dataSourceIdInWorkbook = dataSourceRepository.findIdsByWorkbookInNotPublic(workbookId); List<String> dataSourceIdInWorkspace = dataSourceRepository.findIdsByWorkspaceIn(workspaceId); return CollectionUtils.containsAll(dataSourceIdInWorkspace, dataSourceIdInWorkbook); } @Transactional public void updateMembers(Workspace workspace, List<CollectionPatch> patches) { // RoleSet 이 없는 경우 기본 RoleSet 지정 if (CollectionUtils.isEmpty(workspace.getRoleSets())) { workspace.addRoleSet(roleSetService.getDefaultRoleSet()); } Map<String, Role> roleMap = workspace.getRoleMap(); Map<String, WorkspaceMember> memberMap = workspace.getMemberIdMap(); for (CollectionPatch patch : patches) { String memberId = patch.getValue("memberId"); switch (patch.getOp()) { case ADD: case REPLACE: if (!validateCollectionPatchForMember(patch, roleMap)) { continue; } if (memberMap.containsKey(memberId)) { memberMap.get(memberId).setRole(patch.getValue("role")); LOGGER.debug("Replaced member in workspace({}) : {}, {}", workspace.getId(), memberId, patch.getValue("role")); } else { workspace.getMembers().add(new WorkspaceMember(patch, workspace, this.cachedUserService)); LOGGER.debug("Added member in workspace({}) : {}, {}", workspace.getId(), memberId, patch.getValue("role")); } break; case REMOVE: if (memberMap.containsKey(memberId)) { workspace.getMembers().remove(memberMap.get(memberId)); LOGGER.debug("Deleted member in workspace({}) : {}", workspace.getId(), memberId); // 즐겨찾기가 등록되어 있는 경우 삭제 workspaceFavoriteRepository.deleteByUsernameAndWorkspaceId(memberId, workspace.getId()); } break; default: break; } } workspaceRepository.save(workspace); } private boolean validateCollectionPatchForMember(CollectionPatch patch, Map<String, Role> roleMap) { // Required 'MemberId' property String memberId = patch.getValue("memberId"); if (StringUtils.isEmpty(memberId)) { LOGGER.debug("memberId required."); return false; } // Checking valid member type. WorkspaceMember.MemberType memberType = null; if (patch.getValue("memberType") != null) { memberType = EnumUtils.getUpperCaseEnum(WorkspaceMember.MemberType.class, patch.getValue("memberType")); if (memberType == null) { LOGGER.debug("Invalid memberType(user/group)."); return false; } DirectoryProfile profile = cachedUserService.findProfileByMemberType(memberId, memberType); if (profile == null) { LOGGER.debug("Unknown member {}({}).", memberId, memberType); return false; } } // Required 'role' property, checking valid role name. String roleName = patch.getValue("role"); if (StringUtils.isNotEmpty(roleName)) { if (!roleMap.containsKey(roleName)) { LOGGER.debug("Unknown role name {}.", roleName); return false; } } return true; } /** * 워크스페이스 내에서 접속한 Member 및 Member가 포함된 Group 의 역할을 전달 (for Projection) */ public List<WorkspaceMember> myRoles(String workspaceId, String ownerId) { String currentUser = AuthUtils.getAuthUserName(); if (currentUser.equals(ownerId)) { return null; } // Workspace 내 멤버 여부 확인하고 Role 명 가져오기 List<String> joinedIds = groupService.getJoinedGroups(currentUser).stream() .map(Group::getName) .collect(Collectors.toList()); joinedIds.add(currentUser); List<WorkspaceMember> members = workspaceMemberRepository.findByWorkspaceIdAndMemberIds(workspaceId, joinedIds); return members; } /** * Workspace Permission 목록 가져오기 (for Projection) * * @return Permission 목록 */ public Set<String> getPermissions(Workspace workspace) { String currentUser = AuthUtils.getAuthUserName(); // Owner 는 모든 권한을 가짐 if (currentUser.equals(workspace.getOwnerId())) { //Users have workbench permissions if there are connections available. Predicate searchPredicated = DataConnectionPredicate .searchListForWorkspace(null, null, null, workspace.getId()); ArrayList<DataConnection> connections = Lists.newArrayList(connectionRepository.findAll(searchPredicated)); if(connections.isEmpty()){ Set<String> allPermissions = WorkspacePermissions.allPermissions(); allPermissions.remove(PERM_WORKSPACE_EDIT_WORKBENCH); allPermissions.remove(PERM_WORKSPACE_MANAGE_WORKBENCH); return allPermissions; } else { return WorkspacePermissions.allPermissions(); } } // Workspace 내 멤버 여부 확인하고 Role 명 가져오기 List<String> joinedIds = groupService.getJoinedGroups(currentUser).stream() .map(Group::getId) .collect(Collectors.toList()); joinedIds.add(currentUser); List<String> roleNames = workspaceMemberRepository.findRoleNameByMemberIdsAndWorkspaceId(joinedIds, workspace.getId()); // 멤버가 아닌 경우 빈값 노출 if (CollectionUtils.isEmpty(roleNames)) { return Sets.newHashSet(); } if (CollectionUtils.isEmpty(workspace.getRoleSets())) { workspace.addRoleSet(roleSetService.getDefaultRoleSet()); } return roleSetRepository.getPermissionsByRoleSetAndRoleName(workspace.getRoleSets(), roleNames); } /** * Workspace 내 RoleSet 추가 * * @return Permission 목록 */ @Transactional public void addRoleSet(Workspace workspace, String roleSetName) { RoleSet addRoleSet = roleSetRepository.findByName(roleSetName); if (addRoleSet == null) { throw new ResourceNotFoundException(roleSetName); } List<RoleSet> roleSets = workspace.getRoleSets(); if (roleSets.contains(addRoleSet)) { throw new IllegalArgumentException("Already added roleset."); } // RoleSet 추가 roleSets.add(addRoleSet); workspaceRepository.save(workspace); } /** * Workspace 내 RoleSet 변경 * * @return Permission 목록 */ @Transactional public void changeRoleSet(Workspace workspace, String from, String to, String defaultRoleName, Map<String, String> mapper) { RoleSet fromRoleSet = null; RoleSet defaultRoleSet = roleSetService.getDefaultRoleSet(); // RoleSet 이 없는 경우 fromRoleSet 이 Default rolset 인지 확인 List<RoleSet> roleSets = workspace.getRoleSets(); if (CollectionUtils.isEmpty(roleSets)) { if (defaultRoleSet.getName().equals(from)) { fromRoleSet = defaultRoleSet; } else { throw new BadRequestException("Invalid fromRoleSet name."); } } else { fromRoleSet = roleSets.stream() .filter(roleSet -> from.equals(roleSet.getName())) .findFirst() .orElseThrow(() -> new BadRequestException("fromRoleSet(" + from + ") not found in lined workspace")); } RoleSet toRoleSet = roleSetRepository.findByName(to); if (fromRoleSet == null) { throw new BadRequestException("toRoleSet(" + to + ") not found."); } workspace.removeRoleSet(fromRoleSet); workspace.addRoleSet(toRoleSet); workspaceRepository.saveAndFlush(workspace); /* Mapper 처리 부분 */ // mapper 를 통한 workspace member role 업데이트 Role toDefaultRole = getDefaultRole(defaultRoleName, Lists.newArrayList(toRoleSet)); if (MapUtils.isEmpty(mapper)) { // mapper 정보가 없는 경우 default role로 변경 for (Role role : fromRoleSet.getRoles()) { workspaceMemberRepository.updateMemberRoleInWorkspace(workspace, role.getName(), toDefaultRole.getName()); } } else { List<String> fromRoleNames = fromRoleSet.getRoleNames(); List<String> toRoleNames = toRoleSet.getRoleNames(); String toDefaultRoleName = toDefaultRole.getName(); for (String fromRoleName : mapper.keySet()) { if (!fromRoleNames.contains(fromRoleName)) { continue; } // toRoleName 이 존재하지 않으면 기본 RoleName 으로 변경 String toRoleName = mapper.get(fromRoleName); if (!toRoleNames.contains(toRoleName)) { toRoleName = toDefaultRoleName; } workspaceMemberRepository.updateMemberRoleInWorkspace(workspace, fromRoleName, toRoleName); fromRoleNames.remove(fromRoleName); } if (!fromRoleNames.isEmpty()) { // 포함되지 않은 from RoleSet 의 member role 을 to RoleSet 기본 Role Name 으로 일괄 변경 workspaceMemberRepository.updateMultiMemberRoleInWorkspace(workspace, fromRoleSet.getRoleNames(), toDefaultRoleName); } } } /** * Workspace 내 RoleSet 삭제 * * @return Permission 목록 */ @Transactional public void deleteRoleSet(Workspace workspace, String roleSetName, String defaultRoleName) { RoleSet deleteRoleSet = roleSetRepository.findByName(roleSetName); if (deleteRoleSet == null) { throw new ResourceNotFoundException(roleSetName); } List<RoleSet> roleSets = workspace.getRoleSets(); if (roleSets.contains(deleteRoleSet)) { roleSets.remove(deleteRoleSet); } else { throw new IllegalArgumentException("Already added roleset."); } // 삭제하고 RoleSet이 하나도 없는 경우 지정 if (roleSets.size() == 0) { roleSets.add(roleSetService.getDefaultRoleSet()); } workspaceRepository.saveAndFlush(workspace); // Default Role 을 통해 삭제할 RoleSet내 지정된 Workspace Member Role 업데이트 Role defaultRole = getDefaultRole(defaultRoleName, roleSets); List<String> targetRoleNames = deleteRoleSet.getRoles().stream() .map(role -> role.getName()) .collect(Collectors.toList()); workspaceMemberRepository.updateMultiMemberRoleInWorkspace(workspace, targetRoleNames, defaultRole.getName()); } private Role getDefaultRole(String defaultRoleName, List<RoleSet> roleSets) { final List<Role> roles = Lists.newArrayList(); roleSets.forEach(roleSet -> { roles.addAll(roleSet.getRoles()); }); Role defaultRole = roles.stream() .filter(r -> r.equals(defaultRoleName)) .findFirst().orElse(null); if (defaultRole == null) { defaultRole = roles.stream() .filter(r -> r.getDefaultRole()) .findFirst().orElseThrow(() -> new IllegalArgumentException("default role not found")); } return defaultRole; } public Map<String, Object> getStatistics(Workspace workspace, TimeFieldFormat.TimeUnit timeUnit, DateTime from, DateTime to, boolean accumulated) { Map<String, Long> countBookByType = workspaceRepository.countByBookType(workspace); Double avgDashboardByWorkBook = workspaceRepository.avgDashBoardByWorkBook(workspace); Long countFavoriteWorkspace = workspaceFavoriteRepository.countDistinctByWorkspaceId(workspace.getId()); // 접속 이력 통계 구하기 Map<String, Long> viewCountByTime = activityStreamService .getWorkspaceViewByDateTime(workspace.getId(), timeUnit, from, to); // 누적 옵션 추가 List<Long> viewCountValues; if(accumulated) { viewCountValues = Lists.newArrayList(); Long tempValue = 0L; for (Long viewCountValue : viewCountByTime.values()) { tempValue += viewCountValue; viewCountValues.add(tempValue); } } else { viewCountValues = Lists.newArrayList(viewCountByTime.values()); } MatrixResponse<String, Long> matrix = new MatrixResponse<>(Lists.newArrayList(viewCountByTime.keySet()), Lists.newArrayList(new MatrixResponse.Column("Count", viewCountValues))); Map<String, Object> statMap = Maps.newLinkedHashMap(); statMap.put("countBookByType", countBookByType); statMap.put("avgDashboardByWorkBook", avgDashboardByWorkBook); statMap.put("countFavoriteWorkspace", countFavoriteWorkspace); statMap.put("viewCountByTime", matrix); return statMap; } public Page<Workspace> getPublicWorkspaces(Boolean onlyFavorite, Boolean myWorkspace, Boolean published, String nameContains, Pageable pageable){ String username = AuthUtils.getAuthUserName(); Predicate publicWorkspacePredicate = getPublicWorkspacePredicate(onlyFavorite, myWorkspace, published, nameContains); // 결과 질의 Page<Workspace> publicWorkspaces = workspaceRepository.findAll(publicWorkspacePredicate, pageable); // Favorite 여부 처리 if (onlyFavorite) { publicWorkspaces.forEach(publicWorkspace -> publicWorkspace.setFavorite(true)); } else { Set<String> favoriteWorkspaceIds = workspaceFavoriteRepository.findWorkspaceIdByUsername(username); for (Workspace publicWorkspace : publicWorkspaces) { if (favoriteWorkspaceIds.contains(publicWorkspace.getId())) { publicWorkspace.setFavorite(true); } else { publicWorkspace.setFavorite(false); } } } return publicWorkspaces; } public List<Workspace> getPublicWorkspaces(Boolean onlyFavorite, Boolean myWorkspace, Boolean published, String nameContains){ String username = AuthUtils.getAuthUserName(); Predicate publicWorkspacePredicate = getPublicWorkspacePredicate(onlyFavorite, myWorkspace, published, nameContains); // 결과 질의 List<Workspace> publicWorkspaces = (List) workspaceRepository.findAll(publicWorkspacePredicate); // Favorite 여부 처리 if (onlyFavorite) { publicWorkspaces.forEach(publicWorkspace -> publicWorkspace.setFavorite(true)); } else { Set<String> favoriteWorkspaceIds = workspaceFavoriteRepository.findWorkspaceIdByUsername(username); for (Workspace publicWorkspace : publicWorkspaces) { if (favoriteWorkspaceIds.contains(publicWorkspace.getId())) { publicWorkspace.setFavorite(true); } else { publicWorkspace.setFavorite(false); } } } return publicWorkspaces; } public Map<String, Long> countOfBookByType(Workspace workspace) { Map<String, Long> countOfBook = workspaceRepository.countByBookType(workspace); Map<String, Long> result = Maps.newHashMap(); result.put("folder", countOfBook.get("folder") == null ? 0L : countOfBook.get("folder")); result.put("workBook", countOfBook.get("workbook") == null ? 0L : countOfBook.get("workbook")); result.put("workBench", countOfBook.get("workbench") == null ? 0L : countOfBook.get("workbench")); result.put("notebook", countOfBook.get("notebook") == null ? 0L : countOfBook.get("notebook")); return result; } public Map<String, Long> countByMemberType(Workspace workspace, boolean includePublished) { Map<WorkspaceMember.MemberType, Long> countOfMember = Maps.newHashMap(); if (Workspace.PublicType.SHARED.equals(workspace.getPublicType()) && (includePublished || !workspace.getPublished())) { countOfMember = workspaceRepository.countByMemberType(workspace); } Map<String, Long> result = Maps.newHashMap(); result.put("group", countOfMember.get(WorkspaceMember.MemberType.GROUP) == null ? 0L : countOfMember.get(WorkspaceMember.MemberType.GROUP)); result.put("user", countOfMember.get(WorkspaceMember.MemberType.USER) == null ? 0L : countOfMember.get(WorkspaceMember.MemberType.USER)); return result; } private Predicate getPublicWorkspacePredicate(Boolean onlyFavorite, Boolean myWorkspace, Boolean published, String nameContains){ String username = AuthUtils.getAuthUserName(); List<String> targets = Lists.newArrayList(username); targets.addAll(groupRepository.findGroupIdsByMemberId(username)); BooleanBuilder builder = new BooleanBuilder(); QWorkspace workspace = QWorkspace.workspace; QWorkspaceFavorite workspaceFavorite = QWorkspaceFavorite.workspaceFavorite; builder.and(workspace.publicType.eq(SHARED)); Predicate pOwnerEq = null; if(myWorkspace != null) { pOwnerEq = myWorkspace ? workspace.ownerId.eq(username) : workspace.ownerId.ne(username); } Predicate pPublished = null; if(published != null) { pPublished = published ? builder.and(workspace.published.isTrue()) : builder.andAnyOf(workspace.published.isNull(), workspace.published.isFalse()); } BooleanExpression memberIn = workspace.id .in(JPAExpressions.select(workspace.id) .from(workspace) .innerJoin(workspace.members) .where(workspace.members.any().memberId.in(targets))); if (myWorkspace != null) { if(published == null) { if(myWorkspace) { builder.and(pOwnerEq); } else { builder.andAnyOf(memberIn, workspace.published.isTrue()); } } else { builder.and(pOwnerEq); builder.and(pPublished); if(!myWorkspace) { builder.and(memberIn); } } } else { if (published == null) { builder.andAnyOf(memberIn, workspace.ownerId.eq(username), workspace.published.isTrue()); } else { builder.and(pPublished); } } if (onlyFavorite) { BooleanExpression favorite = workspace.id .in(JPAExpressions.select(workspace.id) .from(workspace, workspaceFavorite) .where(workspace.id.eq(workspaceFavorite.workspaceId).and(workspaceFavorite.username.eq(username)))); builder.and(favorite); if (myWorkspace != null) { builder.and(pOwnerEq); } if (published != null) { builder.and(pPublished); } } if (StringUtils.isNotEmpty(nameContains)) { builder = builder.and(workspace.name.containsIgnoreCase(nameContains)); } return builder; } }
discovery-server/src/main/java/app/metatron/discovery/domain/workspace/WorkspaceService.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.metatron.discovery.domain.workspace; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.querydsl.core.BooleanBuilder; import com.querydsl.core.types.Predicate; import com.querydsl.core.types.dsl.BooleanExpression; import com.querydsl.jpa.JPAExpressions; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import app.metatron.discovery.common.MatrixResponse; import app.metatron.discovery.common.exception.BadRequestException; import app.metatron.discovery.common.exception.ResourceNotFoundException; import app.metatron.discovery.domain.CollectionPatch; import app.metatron.discovery.domain.activities.ActivityStreamService; import app.metatron.discovery.domain.datasource.DataSourceRepository; import app.metatron.discovery.domain.datasource.QDataSource; import app.metatron.discovery.domain.user.CachedUserService; import app.metatron.discovery.domain.user.DirectoryProfile; import app.metatron.discovery.domain.user.User; import app.metatron.discovery.domain.user.group.Group; import app.metatron.discovery.domain.user.group.GroupRepository; import app.metatron.discovery.domain.user.group.GroupService; import app.metatron.discovery.domain.user.role.Role; import app.metatron.discovery.domain.user.role.RoleRepository; import app.metatron.discovery.domain.user.role.RoleService; import app.metatron.discovery.domain.user.role.RoleSet; import app.metatron.discovery.domain.user.role.RoleSetRepository; import app.metatron.discovery.domain.user.role.RoleSetService; import app.metatron.discovery.domain.workbook.configurations.format.TimeFieldFormat; import app.metatron.discovery.util.AuthUtils; import app.metatron.discovery.util.EnumUtils; import static app.metatron.discovery.domain.workspace.Workspace.PublicType.SHARED; /** * Created by kyungtaak on 2017. 7. 23.. */ @Component @Transactional(readOnly = true) public class WorkspaceService { private static Logger LOGGER = LoggerFactory.getLogger(WorkspaceService.class); @Autowired ActivityStreamService activityStreamService; @Autowired GroupService groupService; @Autowired GroupRepository groupRepository; @Autowired RoleService roleService; @Autowired RoleSetService roleSetService; @Autowired CachedUserService cachedUserService; @Autowired DataSourceRepository dataSourceRepository; @Autowired WorkspaceRepository workspaceRepository; @Autowired WorkspaceMemberRepository workspaceMemberRepository; @Autowired WorkspaceFavoriteRepository workspaceFavoriteRepository; @Autowired RoleSetRepository roleSetRepository; @Autowired RoleRepository roleRepository; @Transactional public Workspace createWorkspaceByUserCreation(User user, boolean ifExistThrowException) { // 워크스페이스 생성(등록된 워크스페이스가 없을 경우 생성) Workspace checkedWorkspace = workspaceRepository.findPrivateWorkspaceByOwnerId(user.getUsername()); if(checkedWorkspace != null) { if (ifExistThrowException ) { throw new RuntimeException("Workspace already exist."); } else { return checkedWorkspace; } } Workspace createWorkspace = new Workspace(); createWorkspace.setPublicType(Workspace.PublicType.PRIVATE); createWorkspace.setName(user.getFullName() + " Workspace"); createWorkspace.setOwnerId(user.getUsername()); if(StringUtils.isNotEmpty(user.getWorkspaceType()) && Workspace.workspaceTypes.contains(user.getWorkspaceType())) { createWorkspace.setType(user.getWorkspaceType()); } else { createWorkspace.setType(Workspace.workspaceTypes.get(0)); // "DEFAULT" 셋팅 } return workspaceRepository.saveAndFlush(createWorkspace); } /** * Workspace 접근 시간 지정 */ @Transactional public void updateLastAccessedTime(String workspaceId) { workspaceRepository.updateLastAccessedTime(workspaceId); } /** * 사용자 삭제시 Workspace 처리 */ @Transactional public void disableWorkspaceAndMember(String username, Map<String, String> delegateePair) { // Workspace Owner 인 경우 처리, 위임자 정보가 없는 경우, 전체 Inactive 시킴 if(MapUtils.isEmpty(delegateePair)) { workspaceRepository.updateInactiveWorkspaceAndChangeKnownOwnerId(username, Workspace.PublicType.PRIVATE, Workspace.PublicType.SHARED); } else { // 개인 워크스페이스만 비활성화 시킵니다 workspaceRepository.updateInactiveWorkspaceOfOwner(username, Workspace.PublicType.PRIVATE); // TODO: delegateePair 를 통해 위임합니다 } // Workspace Member 로 포함된 경우 삭제 workspaceMemberRepository.deleteByMemberIds(Lists.newArrayList(username)); // Workspace Favorite 삭제 workspaceFavoriteRepository.deleteByUsername(username); } /** * 사용자 삭제시 Workspace 삭제 */ @Transactional public void deleteWorkspaceAndMember(String username) { // PRIVATE workspace 삭제 Workspace workspace = workspaceRepository.findPrivateWorkspaceByOwnerId(username); if(workspace == null) { LOGGER.warn("Fail to find private workspace : {}", username); } else { workspaceRepository.delete(workspace); } // Workspace Member 로 포함된 경우 삭제 workspaceMemberRepository.deleteByMemberIds(Lists.newArrayList(username)); // Workspace Favorite 삭제 workspaceFavoriteRepository.deleteByUsername(username); } public Integer countAvailableWorkspaces(String workspaceId) { BooleanBuilder builder = new BooleanBuilder(); QDataSource dataSource = QDataSource.dataSource; // 전체 공개 Sub-Query BooleanExpression published = dataSource.id .in(JPAExpressions.select(dataSource.id) .from(dataSource) .where(dataSource.published.eq(true))); // Workspace 내 포함된 Datasource 조회 Sub-Query BooleanExpression workspaceContains = dataSource.id .in(JPAExpressions.select(dataSource.id) .from(dataSource) .innerJoin(dataSource.workspaces) .where(dataSource.workspaces.any().id.eq(workspaceId))); builder = builder.andAnyOf(workspaceContains, published); long count = dataSourceRepository.count(builder); return (int) count; } /** * * @param workbookId * @param workspaceId * @return */ public boolean checkWorkBookCopyToWorkspace(String workbookId, String workspaceId) { List<String> dataSourceIdInWorkbook = dataSourceRepository.findIdsByWorkbookInNotPublic(workbookId); List<String> dataSourceIdInWorkspace = dataSourceRepository.findIdsByWorkspaceIn(workspaceId); return CollectionUtils.containsAll(dataSourceIdInWorkspace, dataSourceIdInWorkbook); } @Transactional public void updateMembers(Workspace workspace, List<CollectionPatch> patches) { // RoleSet 이 없는 경우 기본 RoleSet 지정 if (CollectionUtils.isEmpty(workspace.getRoleSets())) { workspace.addRoleSet(roleSetService.getDefaultRoleSet()); } Map<String, Role> roleMap = workspace.getRoleMap(); Map<String, WorkspaceMember> memberMap = workspace.getMemberIdMap(); for (CollectionPatch patch : patches) { String memberId = patch.getValue("memberId"); switch (patch.getOp()) { case ADD: case REPLACE: if (!validateCollectionPatchForMember(patch, roleMap)) { continue; } if (memberMap.containsKey(memberId)) { memberMap.get(memberId).setRole(patch.getValue("role")); LOGGER.debug("Replaced member in workspace({}) : {}, {}", workspace.getId(), memberId, patch.getValue("role")); } else { workspace.getMembers().add(new WorkspaceMember(patch, workspace, this.cachedUserService)); LOGGER.debug("Added member in workspace({}) : {}, {}", workspace.getId(), memberId, patch.getValue("role")); } break; case REMOVE: if (memberMap.containsKey(memberId)) { workspace.getMembers().remove(memberMap.get(memberId)); LOGGER.debug("Deleted member in workspace({}) : {}", workspace.getId(), memberId); // 즐겨찾기가 등록되어 있는 경우 삭제 workspaceFavoriteRepository.deleteByUsernameAndWorkspaceId(memberId, workspace.getId()); } break; default: break; } } workspaceRepository.save(workspace); } private boolean validateCollectionPatchForMember(CollectionPatch patch, Map<String, Role> roleMap) { // Required 'MemberId' property String memberId = patch.getValue("memberId"); if (StringUtils.isEmpty(memberId)) { LOGGER.debug("memberId required."); return false; } // Checking valid member type. WorkspaceMember.MemberType memberType = null; if (patch.getValue("memberType") != null) { memberType = EnumUtils.getUpperCaseEnum(WorkspaceMember.MemberType.class, patch.getValue("memberType")); if (memberType == null) { LOGGER.debug("Invalid memberType(user/group)."); return false; } DirectoryProfile profile = cachedUserService.findProfileByMemberType(memberId, memberType); if (profile == null) { LOGGER.debug("Unknown member {}({}).", memberId, memberType); return false; } } // Required 'role' property, checking valid role name. String roleName = patch.getValue("role"); if (StringUtils.isNotEmpty(roleName)) { if (!roleMap.containsKey(roleName)) { LOGGER.debug("Unknown role name {}.", roleName); return false; } } return true; } /** * 워크스페이스 내에서 접속한 Member 및 Member가 포함된 Group 의 역할을 전달 (for Projection) */ public List<WorkspaceMember> myRoles(String workspaceId, String ownerId) { String currentUser = AuthUtils.getAuthUserName(); if (currentUser.equals(ownerId)) { return null; } // Workspace 내 멤버 여부 확인하고 Role 명 가져오기 List<String> joinedIds = groupService.getJoinedGroups(currentUser).stream() .map(Group::getName) .collect(Collectors.toList()); joinedIds.add(currentUser); List<WorkspaceMember> members = workspaceMemberRepository.findByWorkspaceIdAndMemberIds(workspaceId, joinedIds); return members; } /** * Workspace Permission 목록 가져오기 (for Projection) * * @return Permission 목록 */ public Set<String> getPermissions(Workspace workspace) { String currentUser = AuthUtils.getAuthUserName(); // Owner 는 모든 권한을 가짐 if (currentUser.equals(workspace.getOwnerId())) { return WorkspacePermissions.allPermissions(); } // Workspace 내 멤버 여부 확인하고 Role 명 가져오기 List<String> joinedIds = groupService.getJoinedGroups(currentUser).stream() .map(Group::getId) .collect(Collectors.toList()); joinedIds.add(currentUser); List<String> roleNames = workspaceMemberRepository.findRoleNameByMemberIdsAndWorkspaceId(joinedIds, workspace.getId()); // 멤버가 아닌 경우 빈값 노출 if (CollectionUtils.isEmpty(roleNames)) { return Sets.newHashSet(); } if (CollectionUtils.isEmpty(workspace.getRoleSets())) { workspace.addRoleSet(roleSetService.getDefaultRoleSet()); } return roleSetRepository.getPermissionsByRoleSetAndRoleName(workspace.getRoleSets(), roleNames); } /** * Workspace 내 RoleSet 추가 * * @return Permission 목록 */ @Transactional public void addRoleSet(Workspace workspace, String roleSetName) { RoleSet addRoleSet = roleSetRepository.findByName(roleSetName); if (addRoleSet == null) { throw new ResourceNotFoundException(roleSetName); } List<RoleSet> roleSets = workspace.getRoleSets(); if (roleSets.contains(addRoleSet)) { throw new IllegalArgumentException("Already added roleset."); } // RoleSet 추가 roleSets.add(addRoleSet); workspaceRepository.save(workspace); } /** * Workspace 내 RoleSet 변경 * * @return Permission 목록 */ @Transactional public void changeRoleSet(Workspace workspace, String from, String to, String defaultRoleName, Map<String, String> mapper) { RoleSet fromRoleSet = null; RoleSet defaultRoleSet = roleSetService.getDefaultRoleSet(); // RoleSet 이 없는 경우 fromRoleSet 이 Default rolset 인지 확인 List<RoleSet> roleSets = workspace.getRoleSets(); if (CollectionUtils.isEmpty(roleSets)) { if (defaultRoleSet.getName().equals(from)) { fromRoleSet = defaultRoleSet; } else { throw new BadRequestException("Invalid fromRoleSet name."); } } else { fromRoleSet = roleSets.stream() .filter(roleSet -> from.equals(roleSet.getName())) .findFirst() .orElseThrow(() -> new BadRequestException("fromRoleSet(" + from + ") not found in lined workspace")); } RoleSet toRoleSet = roleSetRepository.findByName(to); if (fromRoleSet == null) { throw new BadRequestException("toRoleSet(" + to + ") not found."); } workspace.removeRoleSet(fromRoleSet); workspace.addRoleSet(toRoleSet); workspaceRepository.saveAndFlush(workspace); /* Mapper 처리 부분 */ // mapper 를 통한 workspace member role 업데이트 Role toDefaultRole = getDefaultRole(defaultRoleName, Lists.newArrayList(toRoleSet)); if (MapUtils.isEmpty(mapper)) { // mapper 정보가 없는 경우 default role로 변경 for (Role role : fromRoleSet.getRoles()) { workspaceMemberRepository.updateMemberRoleInWorkspace(workspace, role.getName(), toDefaultRole.getName()); } } else { List<String> fromRoleNames = fromRoleSet.getRoleNames(); List<String> toRoleNames = toRoleSet.getRoleNames(); String toDefaultRoleName = toDefaultRole.getName(); for (String fromRoleName : mapper.keySet()) { if (!fromRoleNames.contains(fromRoleName)) { continue; } // toRoleName 이 존재하지 않으면 기본 RoleName 으로 변경 String toRoleName = mapper.get(fromRoleName); if (!toRoleNames.contains(toRoleName)) { toRoleName = toDefaultRoleName; } workspaceMemberRepository.updateMemberRoleInWorkspace(workspace, fromRoleName, toRoleName); fromRoleNames.remove(fromRoleName); } if (!fromRoleNames.isEmpty()) { // 포함되지 않은 from RoleSet 의 member role 을 to RoleSet 기본 Role Name 으로 일괄 변경 workspaceMemberRepository.updateMultiMemberRoleInWorkspace(workspace, fromRoleSet.getRoleNames(), toDefaultRoleName); } } } /** * Workspace 내 RoleSet 삭제 * * @return Permission 목록 */ @Transactional public void deleteRoleSet(Workspace workspace, String roleSetName, String defaultRoleName) { RoleSet deleteRoleSet = roleSetRepository.findByName(roleSetName); if (deleteRoleSet == null) { throw new ResourceNotFoundException(roleSetName); } List<RoleSet> roleSets = workspace.getRoleSets(); if (roleSets.contains(deleteRoleSet)) { roleSets.remove(deleteRoleSet); } else { throw new IllegalArgumentException("Already added roleset."); } // 삭제하고 RoleSet이 하나도 없는 경우 지정 if (roleSets.size() == 0) { roleSets.add(roleSetService.getDefaultRoleSet()); } workspaceRepository.saveAndFlush(workspace); // Default Role 을 통해 삭제할 RoleSet내 지정된 Workspace Member Role 업데이트 Role defaultRole = getDefaultRole(defaultRoleName, roleSets); List<String> targetRoleNames = deleteRoleSet.getRoles().stream() .map(role -> role.getName()) .collect(Collectors.toList()); workspaceMemberRepository.updateMultiMemberRoleInWorkspace(workspace, targetRoleNames, defaultRole.getName()); } private Role getDefaultRole(String defaultRoleName, List<RoleSet> roleSets) { final List<Role> roles = Lists.newArrayList(); roleSets.forEach(roleSet -> { roles.addAll(roleSet.getRoles()); }); Role defaultRole = roles.stream() .filter(r -> r.equals(defaultRoleName)) .findFirst().orElse(null); if (defaultRole == null) { defaultRole = roles.stream() .filter(r -> r.getDefaultRole()) .findFirst().orElseThrow(() -> new IllegalArgumentException("default role not found")); } return defaultRole; } public Map<String, Object> getStatistics(Workspace workspace, TimeFieldFormat.TimeUnit timeUnit, DateTime from, DateTime to, boolean accumulated) { Map<String, Long> countBookByType = workspaceRepository.countByBookType(workspace); Double avgDashboardByWorkBook = workspaceRepository.avgDashBoardByWorkBook(workspace); Long countFavoriteWorkspace = workspaceFavoriteRepository.countDistinctByWorkspaceId(workspace.getId()); // 접속 이력 통계 구하기 Map<String, Long> viewCountByTime = activityStreamService .getWorkspaceViewByDateTime(workspace.getId(), timeUnit, from, to); // 누적 옵션 추가 List<Long> viewCountValues; if(accumulated) { viewCountValues = Lists.newArrayList(); Long tempValue = 0L; for (Long viewCountValue : viewCountByTime.values()) { tempValue += viewCountValue; viewCountValues.add(tempValue); } } else { viewCountValues = Lists.newArrayList(viewCountByTime.values()); } MatrixResponse<String, Long> matrix = new MatrixResponse<>(Lists.newArrayList(viewCountByTime.keySet()), Lists.newArrayList(new MatrixResponse.Column("Count", viewCountValues))); Map<String, Object> statMap = Maps.newLinkedHashMap(); statMap.put("countBookByType", countBookByType); statMap.put("avgDashboardByWorkBook", avgDashboardByWorkBook); statMap.put("countFavoriteWorkspace", countFavoriteWorkspace); statMap.put("viewCountByTime", matrix); return statMap; } public Page<Workspace> getPublicWorkspaces(Boolean onlyFavorite, Boolean myWorkspace, Boolean published, String nameContains, Pageable pageable){ String username = AuthUtils.getAuthUserName(); Predicate publicWorkspacePredicate = getPublicWorkspacePredicate(onlyFavorite, myWorkspace, published, nameContains); // 결과 질의 Page<Workspace> publicWorkspaces = workspaceRepository.findAll(publicWorkspacePredicate, pageable); // Favorite 여부 처리 if (onlyFavorite) { publicWorkspaces.forEach(publicWorkspace -> publicWorkspace.setFavorite(true)); } else { Set<String> favoriteWorkspaceIds = workspaceFavoriteRepository.findWorkspaceIdByUsername(username); for (Workspace publicWorkspace : publicWorkspaces) { if (favoriteWorkspaceIds.contains(publicWorkspace.getId())) { publicWorkspace.setFavorite(true); } else { publicWorkspace.setFavorite(false); } } } return publicWorkspaces; } public List<Workspace> getPublicWorkspaces(Boolean onlyFavorite, Boolean myWorkspace, Boolean published, String nameContains){ String username = AuthUtils.getAuthUserName(); Predicate publicWorkspacePredicate = getPublicWorkspacePredicate(onlyFavorite, myWorkspace, published, nameContains); // 결과 질의 List<Workspace> publicWorkspaces = (List) workspaceRepository.findAll(publicWorkspacePredicate); // Favorite 여부 처리 if (onlyFavorite) { publicWorkspaces.forEach(publicWorkspace -> publicWorkspace.setFavorite(true)); } else { Set<String> favoriteWorkspaceIds = workspaceFavoriteRepository.findWorkspaceIdByUsername(username); for (Workspace publicWorkspace : publicWorkspaces) { if (favoriteWorkspaceIds.contains(publicWorkspace.getId())) { publicWorkspace.setFavorite(true); } else { publicWorkspace.setFavorite(false); } } } return publicWorkspaces; } public Map<String, Long> countOfBookByType(Workspace workspace) { Map<String, Long> countOfBook = workspaceRepository.countByBookType(workspace); Map<String, Long> result = Maps.newHashMap(); result.put("folder", countOfBook.get("folder") == null ? 0L : countOfBook.get("folder")); result.put("workBook", countOfBook.get("workbook") == null ? 0L : countOfBook.get("workbook")); result.put("workBench", countOfBook.get("workbench") == null ? 0L : countOfBook.get("workbench")); result.put("notebook", countOfBook.get("notebook") == null ? 0L : countOfBook.get("notebook")); return result; } public Map<String, Long> countByMemberType(Workspace workspace, boolean includePublished) { Map<WorkspaceMember.MemberType, Long> countOfMember = Maps.newHashMap(); if (Workspace.PublicType.SHARED.equals(workspace.getPublicType()) && (includePublished || !workspace.getPublished())) { countOfMember = workspaceRepository.countByMemberType(workspace); } Map<String, Long> result = Maps.newHashMap(); result.put("group", countOfMember.get(WorkspaceMember.MemberType.GROUP) == null ? 0L : countOfMember.get(WorkspaceMember.MemberType.GROUP)); result.put("user", countOfMember.get(WorkspaceMember.MemberType.USER) == null ? 0L : countOfMember.get(WorkspaceMember.MemberType.USER)); return result; } private Predicate getPublicWorkspacePredicate(Boolean onlyFavorite, Boolean myWorkspace, Boolean published, String nameContains){ String username = AuthUtils.getAuthUserName(); List<String> targets = Lists.newArrayList(username); targets.addAll(groupRepository.findGroupIdsByMemberId(username)); BooleanBuilder builder = new BooleanBuilder(); QWorkspace workspace = QWorkspace.workspace; QWorkspaceFavorite workspaceFavorite = QWorkspaceFavorite.workspaceFavorite; builder.and(workspace.publicType.eq(SHARED)); Predicate pOwnerEq = null; if(myWorkspace != null) { pOwnerEq = myWorkspace ? workspace.ownerId.eq(username) : workspace.ownerId.ne(username); } Predicate pPublished = null; if(published != null) { pPublished = published ? builder.and(workspace.published.isTrue()) : builder.andAnyOf(workspace.published.isNull(), workspace.published.isFalse()); } BooleanExpression memberIn = workspace.id .in(JPAExpressions.select(workspace.id) .from(workspace) .innerJoin(workspace.members) .where(workspace.members.any().memberId.in(targets))); if (myWorkspace != null) { if(published == null) { if(myWorkspace) { builder.and(pOwnerEq); } else { builder.andAnyOf(memberIn, workspace.published.isTrue()); } } else { builder.and(pOwnerEq); builder.and(pPublished); if(!myWorkspace) { builder.and(memberIn); } } } else { if (published == null) { builder.andAnyOf(memberIn, workspace.ownerId.eq(username), workspace.published.isTrue()); } else { builder.and(pPublished); } } if (onlyFavorite) { BooleanExpression favorite = workspace.id .in(JPAExpressions.select(workspace.id) .from(workspace, workspaceFavorite) .where(workspace.id.eq(workspaceFavorite.workspaceId).and(workspaceFavorite.username.eq(username)))); builder.and(favorite); if (myWorkspace != null) { builder.and(pOwnerEq); } if (published != null) { builder.and(pPublished); } } if (StringUtils.isNotEmpty(nameContains)) { builder = builder.and(workspace.name.containsIgnoreCase(nameContains)); } return builder; } }
#3420 Users have workbench permissions if there are connections available. (#3439)
discovery-server/src/main/java/app/metatron/discovery/domain/workspace/WorkspaceService.java
#3420 Users have workbench permissions if there are connections available. (#3439)
Java
apache-2.0
6b658fc61c652f04bba0efe28a535e74f295070d
0
anchela/jackrabbit-oak,trekawek/jackrabbit-oak,anchela/jackrabbit-oak,amit-jain/jackrabbit-oak,trekawek/jackrabbit-oak,mreutegg/jackrabbit-oak,mreutegg/jackrabbit-oak,apache/jackrabbit-oak,apache/jackrabbit-oak,mreutegg/jackrabbit-oak,trekawek/jackrabbit-oak,mreutegg/jackrabbit-oak,amit-jain/jackrabbit-oak,amit-jain/jackrabbit-oak,mreutegg/jackrabbit-oak,anchela/jackrabbit-oak,trekawek/jackrabbit-oak,anchela/jackrabbit-oak,amit-jain/jackrabbit-oak,apache/jackrabbit-oak,amit-jain/jackrabbit-oak,apache/jackrabbit-oak,apache/jackrabbit-oak,anchela/jackrabbit-oak,trekawek/jackrabbit-oak
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.jackrabbit.oak.plugins.document.mongo; import com.mongodb.ReadPreference; import org.apache.jackrabbit.oak.plugins.document.*; import org.apache.jackrabbit.oak.plugins.document.mongo.replica.ReplicaSetInfo; import org.apache.jackrabbit.oak.plugins.document.mongo.replica.ReplicaSetInfoMock; import org.apache.jackrabbit.oak.spi.commit.CommitInfo; import org.apache.jackrabbit.oak.spi.commit.EmptyHook; import org.apache.jackrabbit.oak.spi.state.NodeBuilder; import org.apache.jackrabbit.oak.spi.state.NodeStore; import org.apache.jackrabbit.oak.stats.Clock; import org.junit.Before; import org.junit.Test; import static org.apache.jackrabbit.oak.plugins.document.Collection.NODES; import static org.apache.jackrabbit.oak.plugins.document.Collection.SETTINGS; import static org.apache.jackrabbit.oak.plugins.document.mongo.MongoDocumentStore.DocumentReadPreference; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class ReadPreferenceIT extends AbstractMongoConnectionTest { private MongoDocumentStore mongoDS; private DocumentMK mk2; private Clock clock; private ReplicaSetInfoMock replica; private ReplicaSetInfoMock.RevisionBuilder primary; private ReplicaSetInfoMock.RevisionBuilder secondary; @Override public void setUpConnection() throws Exception { clock = new Clock.Virtual(); mongoConnection = connectionFactory.getConnection(); replica = ReplicaSetInfoMock.create(clock); mk = new DocumentMK.Builder() .setClusterId(1) .setMongoDB(mongoConnection.getDB()) .setLeaseCheck(false) .open(); mongoDS = (MongoDocumentStore) mk.getDocumentStore(); mk2 = new DocumentMK.Builder() .setClusterId(2) .setMongoDB(mongoConnection.getDB()) .setLeaseCheck(false) .open(); } @Before public void createReplicaSet() { replica = ReplicaSetInfoMock.create(clock); primary = replica.addInstance(ReplicaSetInfo.MemberState.PRIMARY, "p1"); secondary = replica.addInstance(ReplicaSetInfo.MemberState.SECONDARY, "s1"); mongoDS.setReplicaInfo(replica); } @Test public void testPreferenceConversion() throws Exception{ primary.addRevisions(200); secondary.addRevisions(0); replica.updateRevisions(); clock.waitUntil(500); assertEquals(300, replica.getLag()); //For cacheAge < replicationLag result should be primary assertEquals(DocumentReadPreference.PRIMARY, mongoDS.getReadPreference(0)); assertEquals(DocumentReadPreference.PRIMARY, mongoDS.getReadPreference((int) (replica.getLag() - 100))); //For Integer.MAX_VALUE it should be secondary as caller intends that value is stable assertEquals(DocumentReadPreference.PREFER_SECONDARY, mongoDS.getReadPreference(Integer.MAX_VALUE)); //For all other cases depends on age assertEquals(DocumentReadPreference.PREFER_SECONDARY_IF_OLD_ENOUGH, mongoDS.getReadPreference(-1)); assertEquals(DocumentReadPreference.PREFER_SECONDARY_IF_OLD_ENOUGH, mongoDS.getReadPreference((int) (replica.getLag() + 100))); } @Test public void testMongoReadPreferencesDefault() throws Exception{ assertEquals(ReadPreference.primary(), mongoDS.getMongoReadPreference(NODES,"foo", null, DocumentReadPreference.PRIMARY)); assertEquals(ReadPreference.primaryPreferred(), mongoDS.getMongoReadPreference(NODES,"foo", null, DocumentReadPreference.PREFER_PRIMARY)); //By default Mongo read preference is primary assertEquals(ReadPreference.primary(), mongoDS.getMongoReadPreference(NODES,"foo", null, DocumentReadPreference.PREFER_SECONDARY)); //Change the default and assert again mongoDS.getDBCollection(NODES).getDB().setReadPreference(ReadPreference.secondary()); assertEquals(ReadPreference.secondary(), mongoDS.getMongoReadPreference(NODES,"foo", null, DocumentReadPreference.PREFER_SECONDARY)); //for case where parent age cannot be determined the preference should be primary assertEquals(ReadPreference.primary(), mongoDS.getMongoReadPreference(NODES,"foo", null, DocumentReadPreference.PREFER_SECONDARY_IF_OLD_ENOUGH)); //For collection other than NODES always primary assertEquals(ReadPreference.primary(), mongoDS.getMongoReadPreference(SETTINGS,"foo", null, DocumentReadPreference.PREFER_SECONDARY_IF_OLD_ENOUGH)); } @Test public void testMongoReadPreferences() throws Exception { ReadPreference testPref = ReadPreference.secondary(); mongoDS.getDBCollection(NODES).getDB().setReadPreference(testPref); NodeStore extNodeStore = mk2.getNodeStore(); NodeBuilder b1 = extNodeStore.getRoot().builder(); b1.child("x").child("y").setProperty("xyz", "123"); extNodeStore.merge(b1, EmptyHook.INSTANCE, CommitInfo.EMPTY); // wait until the change is visible NodeStore nodeStore = mk.getNodeStore(); while (true) { if (nodeStore.getRoot().hasChildNode("x")) { break; } else { Thread.sleep(100); } } // the change hasn't been replicated yet, primary must be used assertEquals(ReadPreference.primary(), mongoDS.getMongoReadPreference(NODES, null, "/x/y", DocumentReadPreference.PREFER_SECONDARY_IF_OLD_ENOUGH)); // make the secondary up-to-date DocumentNodeState ns = (DocumentNodeState) nodeStore.getRoot().getChildNode("x").getChildNode("y"); RevisionVector lastSeenRev = ns.getLastRevision().update(new Revision(Revision.getCurrentTimestamp(), 0, 1)); // add revision for the local cluster node primary.set(lastSeenRev); secondary.set(lastSeenRev); replica.updateRevisions(); // change has been replicated by now, it's fine to use secondary assertEquals(testPref, mongoDS.getMongoReadPreference(NODES, null, "/x/y", DocumentReadPreference.PREFER_SECONDARY_IF_OLD_ENOUGH)); } @Test public void testMongoReadPreferencesForLocalChanges() throws Exception { //Change the default ReadPreference testPref = ReadPreference.secondary(); mongoDS.getDBCollection(NODES).getDB().setReadPreference(testPref); NodeStore nodeStore = mk.getNodeStore(); NodeBuilder b1 = nodeStore.getRoot().builder(); b1.child("x").child("y"); nodeStore.merge(b1, EmptyHook.INSTANCE, CommitInfo.EMPTY); mongoDS.invalidateCache(); // the local change hasn't been replicated yet, primary must be used assertEquals(ReadPreference.primary(), mongoDS.getMongoReadPreference(NODES, null, "/x/y", DocumentReadPreference.PREFER_SECONDARY_IF_OLD_ENOUGH)); // make the secondary up-to-date long now = Revision.getCurrentTimestamp(); primary.addRevision(now, 0, 1, false); primary.addRevision(now, 0, 2, false); secondary.addRevision(now, 0, 1, false); secondary.addRevision(now, 0, 2, false); replica.updateRevisions(); // local change has been replicated by now, it's fine to use secondary for (int i = 0; i < 400; i++) { assertEquals(testPref, mongoDS.getMongoReadPreference(NODES, null, "/x/y", DocumentReadPreference.PREFER_SECONDARY_IF_OLD_ENOUGH)); Thread.sleep(5); } } @Test public void testReadWriteMode() throws Exception{ assertEquals(ReadPreference.primary(), mongoDS.getConfiguredReadPreference(NODES)); mongoDS.setReadWriteMode("readPreference=secondary&w=2&safe=true&j=true"); assertEquals(ReadPreference.secondary(), mongoDS.getDBCollection(NODES).getReadPreference()); assertEquals(2, mongoDS.getDBCollection(NODES).getWriteConcern().getW()); assertTrue(mongoDS.getDBCollection(NODES).getWriteConcern().getJ()); assertEquals(ReadPreference.secondary(), mongoDS.getConfiguredReadPreference(NODES)); } }
oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/document/mongo/ReadPreferenceIT.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.jackrabbit.oak.plugins.document.mongo; import com.mongodb.ReadPreference; import org.apache.jackrabbit.oak.plugins.document.*; import org.apache.jackrabbit.oak.plugins.document.mongo.replica.ReplicaSetInfo; import org.apache.jackrabbit.oak.plugins.document.mongo.replica.ReplicaSetInfoMock; import org.apache.jackrabbit.oak.spi.commit.CommitInfo; import org.apache.jackrabbit.oak.spi.commit.EmptyHook; import org.apache.jackrabbit.oak.spi.state.NodeBuilder; import org.apache.jackrabbit.oak.spi.state.NodeStore; import org.apache.jackrabbit.oak.stats.Clock; import org.junit.Before; import org.junit.Test; import static org.apache.jackrabbit.oak.plugins.document.Collection.NODES; import static org.apache.jackrabbit.oak.plugins.document.Collection.SETTINGS; import static org.apache.jackrabbit.oak.plugins.document.mongo.MongoDocumentStore.DocumentReadPreference; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class ReadPreferenceIT extends AbstractMongoConnectionTest { private MongoDocumentStore mongoDS; private DocumentMK mk2; private Clock clock; private ReplicaSetInfoMock replica; private ReplicaSetInfoMock.RevisionBuilder primary; private ReplicaSetInfoMock.RevisionBuilder secondary; @Override public void setUpConnection() throws Exception { clock = new Clock.Virtual(); mongoConnection = connectionFactory.getConnection(); replica = ReplicaSetInfoMock.create(clock); mk = new DocumentMK.Builder() .setClusterId(1) .setMongoDB(mongoConnection.getDB()) .setLeaseCheck(false) .open(); mongoDS = (MongoDocumentStore) mk.getDocumentStore(); mk2 = new DocumentMK.Builder() .setClusterId(2) .setMongoDB(mongoConnection.getDB()) .setLeaseCheck(false) .open(); } @Before public void createReplicaSet() { replica = ReplicaSetInfoMock.create(clock); primary = replica.addInstance(ReplicaSetInfo.MemberState.PRIMARY, "p1"); secondary = replica.addInstance(ReplicaSetInfo.MemberState.SECONDARY, "s1"); mongoDS.setReplicaInfo(replica); } @Test public void testPreferenceConversion() throws Exception{ primary.addRevisions(200); secondary.addRevisions(0); replica.updateRevisions(); clock.waitUntil(500); assertEquals(300, replica.getLag()); //For cacheAge < replicationLag result should be primary assertEquals(DocumentReadPreference.PRIMARY, mongoDS.getReadPreference(0)); assertEquals(DocumentReadPreference.PRIMARY, mongoDS.getReadPreference((int) (replica.getLag() - 100))); //For Integer.MAX_VALUE it should be secondary as caller intends that value is stable assertEquals(DocumentReadPreference.PREFER_SECONDARY, mongoDS.getReadPreference(Integer.MAX_VALUE)); //For all other cases depends on age assertEquals(DocumentReadPreference.PREFER_SECONDARY_IF_OLD_ENOUGH, mongoDS.getReadPreference(-1)); assertEquals(DocumentReadPreference.PREFER_SECONDARY_IF_OLD_ENOUGH, mongoDS.getReadPreference((int) (replica.getLag() + 100))); } @Test public void testMongoReadPreferencesDefault() throws Exception{ assertEquals(ReadPreference.primary(), mongoDS.getMongoReadPreference(NODES,"foo", null, DocumentReadPreference.PRIMARY)); assertEquals(ReadPreference.primaryPreferred(), mongoDS.getMongoReadPreference(NODES,"foo", null, DocumentReadPreference.PREFER_PRIMARY)); //By default Mongo read preference is primary assertEquals(ReadPreference.primary(), mongoDS.getMongoReadPreference(NODES,"foo", null, DocumentReadPreference.PREFER_SECONDARY)); //Change the default and assert again mongoDS.getDBCollection(NODES).getDB().setReadPreference(ReadPreference.secondary()); assertEquals(ReadPreference.secondary(), mongoDS.getMongoReadPreference(NODES,"foo", null, DocumentReadPreference.PREFER_SECONDARY)); //for case where parent age cannot be determined the preference should be primary assertEquals(ReadPreference.primary(), mongoDS.getMongoReadPreference(NODES,"foo", null, DocumentReadPreference.PREFER_SECONDARY_IF_OLD_ENOUGH)); //For collection other than NODES always primary assertEquals(ReadPreference.primary(), mongoDS.getMongoReadPreference(SETTINGS,"foo", null, DocumentReadPreference.PREFER_SECONDARY_IF_OLD_ENOUGH)); } @Test public void testMongoReadPreferences() throws Exception { ReadPreference testPref = ReadPreference.secondary(); mongoDS.getDBCollection(NODES).getDB().setReadPreference(testPref); NodeStore extNodeStore = mk2.getNodeStore(); NodeBuilder b1 = extNodeStore.getRoot().builder(); b1.child("x").child("y").setProperty("xyz", "123"); extNodeStore.merge(b1, EmptyHook.INSTANCE, CommitInfo.EMPTY); // wait until the change is visible NodeStore nodeStore = mk.getNodeStore(); while (true) { if (nodeStore.getRoot().hasChildNode("x")) { break; } else { Thread.sleep(100); } } // the change hasn't been replicated yet, primary must be used assertEquals(ReadPreference.primary(), mongoDS.getMongoReadPreference(NODES, null, "/x/y", DocumentReadPreference.PREFER_SECONDARY_IF_OLD_ENOUGH)); // make the secondary up-to-date DocumentNodeState ns = (DocumentNodeState) nodeStore.getRoot().getChildNode("x").getChildNode("y"); RevisionVector lastSeenRev = ns.getLastRevision().update(new Revision(Revision.getCurrentTimestamp(), 0, 1)); // add revision for the local cluster node primary.set(lastSeenRev); secondary.set(lastSeenRev); replica.updateRevisions(); // change has been replicated by now, it's fine to use secondary assertEquals(testPref, mongoDS.getMongoReadPreference(NODES, null, "/x/y", DocumentReadPreference.PREFER_SECONDARY_IF_OLD_ENOUGH)); } @Test public void testMongoReadPreferencesForLocalChanges() throws Exception { //Change the default ReadPreference testPref = ReadPreference.secondary(); mongoDS.getDBCollection(NODES).getDB().setReadPreference(testPref); NodeStore nodeStore = mk.getNodeStore(); NodeBuilder b1 = nodeStore.getRoot().builder(); b1.child("x").child("y"); nodeStore.merge(b1, EmptyHook.INSTANCE, CommitInfo.EMPTY); mongoDS.invalidateCache(); // the local change hasn't been replicated yet, primary must be used assertEquals(ReadPreference.primary(), mongoDS.getMongoReadPreference(NODES, null, "/x/y", DocumentReadPreference.PREFER_SECONDARY_IF_OLD_ENOUGH)); // make the secondary up-to-date long now = Revision.getCurrentTimestamp(); primary.addRevision(now, 0, 1, false); secondary.addRevision(now, 0, 1, false); replica.updateRevisions(); // local change has been replicated by now, it's fine to use secondary assertEquals(testPref, mongoDS.getMongoReadPreference(NODES, null, "/x/y", DocumentReadPreference.PREFER_SECONDARY_IF_OLD_ENOUGH)); } @Test public void testReadWriteMode() throws Exception{ assertEquals(ReadPreference.primary(), mongoDS.getConfiguredReadPreference(NODES)); mongoDS.setReadWriteMode("readPreference=secondary&w=2&safe=true&j=true"); assertEquals(ReadPreference.secondary(), mongoDS.getDBCollection(NODES).getReadPreference()); assertEquals(2, mongoDS.getDBCollection(NODES).getWriteConcern().getW()); assertTrue(mongoDS.getDBCollection(NODES).getWriteConcern().getJ()); assertEquals(ReadPreference.secondary(), mongoDS.getConfiguredReadPreference(NODES)); } }
OAK-4912: MongoDB: ReadPreferenceIT.testMongoReadPreferencesForLocalChanges() occasionally fails git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1771274 13f79535-47bb-0310-9956-ffa450edef68
oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/document/mongo/ReadPreferenceIT.java
OAK-4912: MongoDB: ReadPreferenceIT.testMongoReadPreferencesForLocalChanges() occasionally fails
Java
apache-2.0
2582244658a29d4605d33ad262272cfdf6170193
0
Luxoft/Twister,ctgriffiths/twister,ctgriffiths/twister,Luxoft/Twister,ctgriffiths/twister,Luxoft/Twister,Luxoft/Twister,Luxoft/Twister,Luxoft/Twister,ctgriffiths/twister,ctgriffiths/twister,Luxoft/Twister,ctgriffiths/twister
import javax.swing.JPanel; import java.awt.Dimension; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import java.awt.Font; import javax.swing.border.TitledBorder; import javax.swing.JTextArea; import java.awt.Dimension; import javax.swing.border.BevelBorder; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.JScrollPane; import java.awt.Color; import javax.swing.JCheckBox; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.swing.JPasswordField; import javax.xml.transform.Result; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.TransformerFactory; import javax.xml.transform.Transformer; import javax.xml.transform.OutputKeys; import javax.xml.transform.dom.DOMSource; import java.io.FileInputStream; import javax.swing.JOptionPane; public class Emails extends JPanel{ public JPanel p1; private JCheckBox check; private JTextField tipname, tport, tuser, tfrom; private JPasswordField tpass; private JTextArea emails, message, subject; private JLabel enable; public Emails(){ setLayout(null); setPreferredSize(new Dimension(450,480)); setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); setBackground(Color.WHITE); TitledBorder border = BorderFactory.createTitledBorder("SMTP server"); border.setTitleFont(new Font("Arial",Font.PLAIN,14)); border.setBorder(BorderFactory.createLineBorder(new Color(150,150,150), 1)); JPanel p1 = new JPanel(); p1.setBackground(Color.WHITE); p1.setBorder(border); p1.setLayout(null); p1.setBounds(80,5,350,68); JLabel ipname = new JLabel("IP/Name: "); ipname.setBounds(60,15,60,20); p1.add(ipname); tipname = new JTextField(); tipname.setBounds(125,15,150,20); p1.add(tipname); JLabel port = new JLabel("Port: "); port.setBounds(60,40,60,20); p1.add(port); tport = new JTextField(); tport.setBounds(125,40,150,20); p1.add(tport); add(p1); border = BorderFactory.createTitledBorder("Authentication"); border.setTitleFont(new Font("Arial",Font.PLAIN,14)); border.setBorder(BorderFactory.createLineBorder(new Color(150,150,150), 1)); JPanel p2 = new JPanel(); p2.setBackground(Color.WHITE); p2.setBorder(border); p2.setLayout(null); p2.setBounds(80,73,350,93); JLabel user = new JLabel("User: "); user.setBounds(60,15,60,20); p2.add(user); tuser = new JTextField(); tuser.setBounds(125,15,150,20); p2.add(tuser); JLabel pass = new JLabel("Password: "); pass.setBounds(60,40,80,20); p2.add(pass); tpass = new JPasswordField(); tpass.setBounds(125,40,150,20); p2.add(tpass); JLabel from = new JLabel("From: "); from.setBounds(60,65,60,20); p2.add(from); tfrom = new JTextField(); tfrom.setBounds(125,65,150,20); p2.add(tfrom); add(p2); border = BorderFactory.createTitledBorder("Email List"); border.setTitleFont(new Font("Arial",Font.PLAIN,14)); border.setBorder(BorderFactory.createLineBorder(new Color(150,150,150), 1)); JPanel p3 = new JPanel(); p3.setBackground(Color.WHITE); p3.setBorder(border); p3.setLayout(null); p3.setBounds(80,170,350,68); emails = new JTextArea(); emails.setLineWrap(true); emails.setWrapStyleWord(true); JScrollPane scroll = new JScrollPane(emails); scroll.setBounds(7,18,336,45); p3.add(scroll); add(p3); border = BorderFactory.createTitledBorder("Subject"); border.setTitleFont(new Font("Arial",Font.PLAIN,14)); border.setBorder(BorderFactory.createLineBorder(new Color(150,150,150), 1)); JPanel p5 = new JPanel(); p5.setBackground(Color.WHITE); p5.setBorder(border); p5.setLayout(null); p5.setBounds(80,240,350,58); subject = new JTextArea(); subject.setLineWrap(true); subject.setWrapStyleWord(true); JScrollPane scroll3 = new JScrollPane(subject); scroll3.setBounds(7,18,336,35); p5.add(scroll3); add(p5); border = BorderFactory.createTitledBorder("Message"); border.setTitleFont(new Font("Arial",Font.PLAIN,14)); border.setBorder(BorderFactory.createLineBorder(new Color(150,150,150), 1)); JPanel p4 = new JPanel(); p4.setBackground(Color.WHITE); p4.setBorder(border); p4.setLayout(null); p4.setBounds(80,300,350,108); message = new JTextArea(); message.setLineWrap(true); message.setWrapStyleWord(true); JScrollPane scroll2 = new JScrollPane(message); scroll2.setBounds(7,18,336,85); p4.add(scroll2); add(p4); enable = new JLabel("Disabled"); enable.setBounds(360,410,60,20); add(enable); check = new JCheckBox(); check.setBounds(412,410,20,20); check.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ev){ if(check.isSelected())enable.setText("Enabled"); else enable.setText("Disabled");}}); add(check); JButton save = new JButton("Save"); save.setBounds(352,435,80,20); save.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ev){ if(tpass.getPassword().length == 0){JOptionPane.showMessageDialog(Emails.this, "Warning, password not set.", "Warning", JOptionPane.WARNING_MESSAGE);} try{ File theone = new File(Repository.temp+Repository.getBar()+"Twister"+Repository.getBar()+"Config"+Repository.getBar()+new File(Repository.REMOTEEMAILCONFIGFILE).getName()); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(theone); doc.getDocumentElement().normalize(); try{ NodeList nodeLst = doc.getElementsByTagName("Enabled"); if(nodeLst.item(0).getChildNodes().getLength()>0)nodeLst.item(0).getChildNodes().item(0).setNodeValue(check.isSelected()+""); else nodeLst.item(0).appendChild(doc.createTextNode(check.isSelected()+"")); nodeLst = doc.getElementsByTagName("SMTPPath"); String SMTPPath = tipname.getText()+":"+tport.getText(); if(nodeLst.item(0).getChildNodes().getLength()>0)nodeLst.item(0).getChildNodes().item(0).setNodeValue(SMTPPath); else nodeLst.item(0).appendChild(doc.createTextNode(SMTPPath)); nodeLst = doc.getElementsByTagName("SMTPUser"); if(nodeLst.item(0).getChildNodes().getLength()>0)nodeLst.item(0).getChildNodes().item(0).setNodeValue(tuser.getText()); else nodeLst.item(0).appendChild(doc.createTextNode(tuser.getText())); if(tpass.getPassword().length != 0 && !(new String(tpass.getPassword()).equals("****"))){ nodeLst = doc.getElementsByTagName("SMTPPwd"); if(nodeLst.item(0).getChildNodes().getLength()>0)nodeLst.item(0).getChildNodes().item(0).setNodeValue(new String(tpass.getPassword())); else nodeLst.item(0).appendChild(doc.createTextNode(new String(tpass.getPassword())));} nodeLst = doc.getElementsByTagName("From"); if(nodeLst.item(0).getChildNodes().getLength()>0)nodeLst.item(0).getChildNodes().item(0).setNodeValue(tfrom.getText()); else nodeLst.item(0).appendChild(doc.createTextNode(tfrom.getText())); nodeLst = doc.getElementsByTagName("To"); if(nodeLst.item(0).getChildNodes().getLength()>0)nodeLst.item(0).getChildNodes().item(0).setNodeValue(emails.getText()); else nodeLst.item(0).appendChild(doc.createTextNode(emails.getText())); nodeLst = doc.getElementsByTagName("Message"); if(nodeLst.item(0).getChildNodes().getLength()>0)nodeLst.item(0).getChildNodes().item(0).setNodeValue(message.getText()); else nodeLst.item(0).appendChild(doc.createTextNode(message.getText())); nodeLst = doc.getElementsByTagName("Subject"); if(nodeLst.item(0).getChildNodes().getLength()>0)nodeLst.item(0).getChildNodes().item(0).setNodeValue(subject.getText()); else nodeLst.item(0).appendChild(doc.createTextNode(subject.getText()));} catch(Exception e){System.out.println(doc.getDocumentURI()+" may not be properly formatted");} Result result = new StreamResult(theone); try{DOMSource source = new DOMSource(doc); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.transform(source, result); try{Repository.c.cd(Repository.REMOTEEMAILCONFIGPATH);} catch(Exception e){System.out.println("could not get "+Repository.REMOTEEMAILCONFIGPATH); e.printStackTrace();} FileInputStream input = new FileInputStream(theone); Repository.c.put(input, theone.getName()); input.close();} catch(Exception e){e.printStackTrace(); System.out.println("Could not save in file : "+Repository.temp+Repository.getBar()+"Twister"+Repository.getBar()+"Config"+Repository.getBar()+Repository.REMOTEEMAILCONFIGFILE+" and send to "+Repository.REMOTEEMAILCONFIGPATH);}} catch(Exception e){e.printStackTrace();}}}); add(save);} public void setIPName(String ipname){ tipname.setText(ipname);} public void setPassword(String password){ tpass.setText(password);} public void setPort(String port){ tport.setText(port);} public void setUser(String user){ tuser.setText(user);} public void setFrom(String from){ tfrom.setText(from);} public void setEmails(String emails){ this.emails.setText(emails);} public void setMessage(String message){ this.message.setText(message);} public void setSubject(String subject){ this.subject.setText(subject);} public void setCheck(boolean check){ this.check.setSelected(check); if(check)enable.setText("Enabled"); else enable.setText("Disabled");}}
src/client/userinterface/java/src/Emails.java
import javax.swing.JPanel; import java.awt.Dimension; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import java.awt.Font; import javax.swing.border.TitledBorder; import javax.swing.JTextArea; import java.awt.Dimension; import javax.swing.border.BevelBorder; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.JScrollPane; import java.awt.Color; import javax.swing.JCheckBox; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.swing.JPasswordField; import javax.xml.transform.Result; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.TransformerFactory; import javax.xml.transform.Transformer; import javax.xml.transform.OutputKeys; import javax.xml.transform.dom.DOMSource; import java.io.FileInputStream; import javax.swing.JOptionPane; public class Emails extends JPanel{ public JPanel p1; private JCheckBox check; private JTextField tipname, tport, tuser, tfrom; private JPasswordField tpass; private JTextArea emails, message, subject; private JLabel enable; public Emails(){ setLayout(null); setPreferredSize(new Dimension(450,480)); setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); setBackground(Color.WHITE); TitledBorder border = BorderFactory.createTitledBorder("SMTP server"); border.setTitleFont(new Font("Arial",Font.PLAIN,14)); border.setBorder(BorderFactory.createLineBorder(new Color(150,150,150), 1)); JPanel p1 = new JPanel(); p1.setBackground(Color.WHITE); p1.setBorder(border); p1.setLayout(null); p1.setBounds(80,5,350,68); JLabel ipname = new JLabel("IP/Name: "); ipname.setBounds(60,15,60,20); p1.add(ipname); tipname = new JTextField(); tipname.setBounds(125,15,150,20); p1.add(tipname); JLabel port = new JLabel("Port: "); port.setBounds(60,40,60,20); p1.add(port); tport = new JTextField(); tport.setBounds(125,40,150,20); p1.add(tport); add(p1); border = BorderFactory.createTitledBorder("Authentication"); border.setTitleFont(new Font("Arial",Font.PLAIN,14)); border.setBorder(BorderFactory.createLineBorder(new Color(150,150,150), 1)); JPanel p2 = new JPanel(); p2.setBackground(Color.WHITE); p2.setBorder(border); p2.setLayout(null); p2.setBounds(80,73,350,93); JLabel user = new JLabel("User: "); user.setBounds(60,15,60,20); p2.add(user); tuser = new JTextField(); tuser.setBounds(125,15,150,20); p2.add(tuser); JLabel pass = new JLabel("Password: "); pass.setBounds(60,40,80,20); p2.add(pass); tpass = new JPasswordField(); tpass.setBounds(125,40,150,20); p2.add(tpass); JLabel from = new JLabel("From: "); from.setBounds(60,65,60,20); p2.add(from); tfrom = new JTextField(); tfrom.setBounds(125,65,150,20); p2.add(tfrom); add(p2); border = BorderFactory.createTitledBorder("Email List"); border.setTitleFont(new Font("Arial",Font.PLAIN,14)); border.setBorder(BorderFactory.createLineBorder(new Color(150,150,150), 1)); JPanel p3 = new JPanel(); p3.setBackground(Color.WHITE); p3.setBorder(border); p3.setLayout(null); p3.setBounds(80,170,350,68); emails = new JTextArea(); emails.setLineWrap(true); emails.setWrapStyleWord(true); JScrollPane scroll = new JScrollPane(emails); //scroll.setBorder(null); scroll.setBounds(7,18,336,45); p3.add(scroll); add(p3); border = BorderFactory.createTitledBorder("Subject"); border.setTitleFont(new Font("Arial",Font.PLAIN,14)); border.setBorder(BorderFactory.createLineBorder(new Color(150,150,150), 1)); JPanel p5 = new JPanel(); p5.setBackground(Color.WHITE); p5.setBorder(border); p5.setLayout(null); p5.setBounds(80,240,350,58); subject = new JTextArea(); subject.setLineWrap(true); subject.setWrapStyleWord(true); JScrollPane scroll3 = new JScrollPane(subject); //scroll3.setBorder(null); scroll3.setBounds(7,18,336,35); p5.add(scroll3); add(p5); border = BorderFactory.createTitledBorder("Message"); border.setTitleFont(new Font("Arial",Font.PLAIN,14)); border.setBorder(BorderFactory.createLineBorder(new Color(150,150,150), 1)); JPanel p4 = new JPanel(); p4.setBackground(Color.WHITE); p4.setBorder(border); p4.setLayout(null); p4.setBounds(80,300,350,108); message = new JTextArea(); message.setLineWrap(true); message.setWrapStyleWord(true); JScrollPane scroll2 = new JScrollPane(message); //scroll2.setBorder(null); scroll2.setBounds(7,18,336,85); p4.add(scroll2); add(p4); enable = new JLabel("Disabled"); enable.setBounds(360,410,60,20); add(enable); check = new JCheckBox(); check.setBounds(412,410,20,20); check.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ev){ if(check.isSelected())enable.setText("Enabled"); else enable.setText("Disabled");}}); add(check); JButton save = new JButton("Save"); save.setBounds(352,435,80,20); save.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ev){ if(tpass.getPassword().length == 0){JOptionPane.showMessageDialog(Emails.this, "Warning, password not set, will be used the old one.", "Warning", JOptionPane.WARNING_MESSAGE);} // else{ try{ File theone = new File(Repository.temp+Repository.getBar()+"Twister"+Repository.getBar()+"Config"+Repository.getBar()+new File(Repository.REMOTEEMAILCONFIGFILE).getName()); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(theone); doc.getDocumentElement().normalize(); try{ NodeList nodeLst = doc.getElementsByTagName("Enabled"); if(nodeLst.item(0).getChildNodes().getLength()>0)nodeLst.item(0).getChildNodes().item(0).setNodeValue(check.isSelected()+""); else nodeLst.item(0).appendChild(doc.createTextNode(check.isSelected()+"")); nodeLst = doc.getElementsByTagName("SMTPPath"); String SMTPPath = tipname.getText()+":"+tport.getText(); if(nodeLst.item(0).getChildNodes().getLength()>0)nodeLst.item(0).getChildNodes().item(0).setNodeValue(SMTPPath); else nodeLst.item(0).appendChild(doc.createTextNode(SMTPPath)); nodeLst = doc.getElementsByTagName("SMTPUser"); if(nodeLst.item(0).getChildNodes().getLength()>0)nodeLst.item(0).getChildNodes().item(0).setNodeValue(tuser.getText()); else nodeLst.item(0).appendChild(doc.createTextNode(tuser.getText())); if(tpass.getPassword().length != 0){ nodeLst = doc.getElementsByTagName("SMTPPwd"); if(nodeLst.item(0).getChildNodes().getLength()>0)nodeLst.item(0).getChildNodes().item(0).setNodeValue(new String(tpass.getPassword())); else nodeLst.item(0).appendChild(doc.createTextNode(new String(tpass.getPassword())));} nodeLst = doc.getElementsByTagName("From"); if(nodeLst.item(0).getChildNodes().getLength()>0)nodeLst.item(0).getChildNodes().item(0).setNodeValue(tfrom.getText()); else nodeLst.item(0).appendChild(doc.createTextNode(tfrom.getText())); nodeLst = doc.getElementsByTagName("To"); if(nodeLst.item(0).getChildNodes().getLength()>0)nodeLst.item(0).getChildNodes().item(0).setNodeValue(emails.getText()); else nodeLst.item(0).appendChild(doc.createTextNode(emails.getText())); nodeLst = doc.getElementsByTagName("Message"); if(nodeLst.item(0).getChildNodes().getLength()>0)nodeLst.item(0).getChildNodes().item(0).setNodeValue(message.getText()); else nodeLst.item(0).appendChild(doc.createTextNode(message.getText())); nodeLst = doc.getElementsByTagName("Subject"); if(nodeLst.item(0).getChildNodes().getLength()>0)nodeLst.item(0).getChildNodes().item(0).setNodeValue(subject.getText()); else nodeLst.item(0).appendChild(doc.createTextNode(subject.getText()));} catch(Exception e){System.out.println(doc.getDocumentURI()+" may not be properly formatted");} Result result = new StreamResult(theone); try{DOMSource source = new DOMSource(doc); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.transform(source, result); try{Repository.c.cd(Repository.REMOTEEMAILCONFIGPATH);} catch(Exception e){System.out.println("could not get "+Repository.REMOTEEMAILCONFIGPATH); e.printStackTrace();} FileInputStream input = new FileInputStream(theone); Repository.c.put(input, theone.getName()); input.close();} catch(Exception e){e.printStackTrace(); System.out.println("Could not save in file : "+Repository.temp+Repository.getBar()+"Twister"+Repository.getBar()+"Config"+Repository.getBar()+Repository.REMOTEEMAILCONFIGFILE+" and send to "+Repository.REMOTEEMAILCONFIGPATH);}} catch(Exception e){e.printStackTrace();}} // } }); add(save);} public void setIPName(String ipname){ tipname.setText(ipname);} public void setPort(String port){ tport.setText(port);} public void setUser(String user){ tuser.setText(user);} public void setFrom(String from){ tfrom.setText(from);} public void setEmails(String emails){ this.emails.setText(emails);} public void setMessage(String message){ this.message.setText(message);} public void setSubject(String subject){ this.subject.setText(subject);} public void setCheck(boolean check){ this.check.setSelected(check); if(check)enable.setText("Enabled"); else enable.setText("Disabled");}}
latest version
src/client/userinterface/java/src/Emails.java
latest version
Java
apache-2.0
766929ef57270f1acb014de5123a714a3ce248a5
0
OpenXIP/xip-host,OpenXIP/xip-host
/** * Copyright (c) 2008 Washington University in Saint Louis. All Rights Reserved. */ package edu.wustl.xipHost.application; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.UUID; import javax.xml.ws.Endpoint; import org.apache.log4j.Logger; import org.jdom.Document; import org.nema.dicom.wg23.ArrayOfString; import org.nema.dicom.wg23.ArrayOfUUID; import org.nema.dicom.wg23.AvailableData; import org.nema.dicom.wg23.Host; import org.nema.dicom.wg23.ModelSetDescriptor; import org.nema.dicom.wg23.ObjectLocator; import org.nema.dicom.wg23.QueryResult; import org.nema.dicom.wg23.Rectangle; import org.nema.dicom.wg23.State; import org.nema.dicom.wg23.Uuid; import edu.wustl.xipHost.avt2ext.AVTQueryStub; import edu.wustl.xipHost.avt2ext.AVTUtil; import edu.wustl.xipHost.avt2ext.Query; import edu.wustl.xipHost.avt2ext.SearchResultSetupAvailableData; import edu.wustl.xipHost.avt2ext.iterator.IterationTarget; import edu.wustl.xipHost.avt2ext.iterator.IteratorElementEvent; import edu.wustl.xipHost.avt2ext.iterator.IteratorEvent; import edu.wustl.xipHost.avt2ext.iterator.TargetElement; import edu.wustl.xipHost.avt2ext.iterator.TargetIteratorRunner; import edu.wustl.xipHost.avt2ext.iterator.TargetIteratorListener; import edu.wustl.xipHost.dataModel.SearchResult; import edu.wustl.xipHost.dicom.DicomUtil; import edu.wustl.xipHost.gui.HostMainWindow; import edu.wustl.xipHost.hostControl.Util; import edu.wustl.xipHost.hostControl.XindiceManager; import edu.wustl.xipHost.hostControl.XindiceManagerFactory; import edu.wustl.xipHost.wg23.ClientToApplication; import edu.wustl.xipHost.wg23.HostImpl; import edu.wustl.xipHost.wg23.NativeModelListener; import edu.wustl.xipHost.wg23.NativeModelRunner; import edu.wustl.xipHost.wg23.WG23DataModel; public class Application implements NativeModelListener, TargetIteratorListener { final static Logger logger = Logger.getLogger(Application.class); UUID id; String name; File exePath; String vendor; String version; File iconFile; String type; boolean requiresGUI; String wg23DataModelType; int concurrentInstances; IterationTarget iterationTarget; /* Application is a WG23 compatibile application*/ public Application(String name, File exePath, String vendor, String version, File iconFile, String type, boolean requiresGUI, String wg23DataModelType, int concurrentInstances, IterationTarget iterationTarget){ if(name == null || exePath == null || vendor == null || version == null || type == null || wg23DataModelType == null || iterationTarget == null){ throw new IllegalArgumentException("Application parameters are invalid: " + name + " , " + exePath + " , " + vendor + " , " + version + type + " , " + requiresGUI + " , " + wg23DataModelType + " , " + iterationTarget); } else if(name.isEmpty() || name.trim().length() == 0 || exePath.exists() == false){ try { throw new IllegalArgumentException("Application parameters are invalid: " + name + " , " + exePath.getCanonicalPath() + " , " + vendor + " , " + version); } catch (IOException e) { throw new IllegalArgumentException("Application exePath is invalid. Application name: " + name); } } else{ id = UUID.randomUUID(); this.name = name; this.exePath = exePath; this.vendor = vendor; this.version = version; if(iconFile != null && iconFile.exists()){ this.iconFile = iconFile; }else{ this.iconFile = null; } this.type = type; this.requiresGUI = requiresGUI; this.wg23DataModelType = wg23DataModelType; this.concurrentInstances = concurrentInstances; this.iterationTarget = iterationTarget; } } //verify this pattern /*public boolean verifyFileName(String fileName){ String str = "/ \\ : * ? \" < > | , "; Pattern filePattern = Pattern.compile(str); boolean matches = filePattern.matcher(fileName).matches(); return matches; } public static void main (String args[]){ Application app = new Application("ApplicationTest", new File("test.txt"), "", ""); System.out.println(app.getExePath().getName()); System.out.println(app.verifyFileName(app.getExePath().getName())); }*/ public UUID getID(){ return id; } public String getName(){ return name; } public void setName(String name){ if(name == null || name.isEmpty() || name.trim().length() == 0){ throw new IllegalArgumentException("Invalid application name: " + name); }else{ this.name = name; } } public File getExePath(){ return exePath; } public void setExePath(File path){ if(path == null){ throw new IllegalArgumentException("Invalid exePath name: " + path); }else{ exePath = path; } } public String getVendor(){ return vendor; } public void setVendor(String vendor){ if(vendor == null){ throw new IllegalArgumentException("Invalid vendor: " + vendor); }else{ this.vendor = vendor; } } public String getVersion(){ return version; } public void setVersion(String version){ if(version == null){ throw new IllegalArgumentException("Invalid version: " + version); }else{ this.version = version; } } public File getIconFile(){ return iconFile; } public void setIconFile(File iconFile){ if(iconFile == null){ throw new IllegalArgumentException("Invalid exePath name: " + iconFile); }else{ this.iconFile = iconFile; } } public String getType() { return type; } public void setType(String type) { this.type = type; } public boolean requiresGUI() { return requiresGUI; } public void setRequiresGUI(boolean requiresGUI) { this.requiresGUI = requiresGUI; } public String getWG23DataModelType() { return wg23DataModelType; } public void setWG23DataModelType(String wg23DataModelType) { this.wg23DataModelType = wg23DataModelType; } public int getConcurrentInstances() { return concurrentInstances; } public void setConcurrentInstances(int concurrentInstances) { this.concurrentInstances = concurrentInstances; } public IterationTarget getIterationTarget() { return iterationTarget; } public void setIterationTarget(IterationTarget iterationTarget) { this.iterationTarget = iterationTarget; } //Each application has: //1. Out directories assigned //2. clientToApplication //3. Host scheleton (reciever) //4. Data assigned for processing //5. Data produced //when launching diploy service and set URLs ClientToApplication clientToApplication; public void startClientToApplication(){ clientToApplication = new ClientToApplication(getApplicationServiceURL()); } public ClientToApplication getClientToApplication(){ return clientToApplication; } //Implementation HostImpl is used to be able to add WG23Listener //It is eventually casted to Host type Host host = new HostImpl(this); //All loaded application by default will be saved again. //New instances of an application will be saved only when the save checkbox is selected Boolean doSave = true; public void setDoSave(boolean doSave){ this.doSave = doSave; } public boolean getDoSave(){ return doSave; } Endpoint hostEndpoint; URL hostServiceURL; URL appServiceURL; public void launch(URL hostServiceURL, URL appServiceURL){ this.hostServiceURL = hostServiceURL; this.appServiceURL = appServiceURL; setApplicationOutputDir(ApplicationManagerFactory.getInstance().getOutputDir()); setApplicationTmpDir(ApplicationManagerFactory.getInstance().getTmpDir()); setApplicationPreferredSize(HostMainWindow.getApplicationPreferredSize()); //prepare native models //createNativeModels(getWG23DataModel()); //diploy host service hostEndpoint = Endpoint.publish(hostServiceURL.toString(), host); // Ways of launching XIP application: exe, bat, class or jar //if(((String)getExePath().getName()).endsWith(".exe") || ((String)getExePath().getName()).endsWith(".bat")){ try { if(getExePath().toURI().toURL().toExternalForm().endsWith(".exe") || getExePath().toURI().toURL().toExternalForm().endsWith(".bat")){ //TODO unvoid try { Runtime.getRuntime().exec("cmd /c start /min " + getExePath().toURI().toURL().toExternalForm() + " " + "--hostURL" + " " + hostServiceURL.toURI().toURL().toExternalForm() + " " + "--applicationURL" + " " + appServiceURL.toURI().toURL().toExternalForm()); /*List< String > command = new LinkedList<String>(); command.add("cmd"); command.add("/c"); command.add("start"); command.add("/min"); command.add(getExePath().getCanonicalPath()); command.add("--hostURL"); command.add(hostServiceURL.toURI().toURL().toExternalForm()); command.add( "--applicationURL" ); command.add(appServiceURL.toURI().toURL().toExternalForm()); ProcessBuilder builder = new ProcessBuilder(command); String str =""; for(int i = 0; i < command.size(); i++){ str = str + command.get(i) + " "; } System.out.println(str); File dir = getExePath().getParentFile(); builder.directory(dir); builder.start();*/ } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (getExePath().toURI().toURL().toExternalForm().endsWith(".sh")){ try { //Runtime.getRuntime().exec("/bin/sh " + getExePath().getCanonicalPath() + " " + "--hostURL" + " " + hostServiceURL.toURI().toURL().toExternalForm() + " " + "--applicationURL" + " " + appServiceURL.toURI().toURL().toExternalForm()); System.out.println(getExePath().toURI().toURL().toExternalForm() + " " + "--hostURL" + " " + hostServiceURL.toURI().toURL().toExternalForm() + " " + "--applicationURL" + " " + appServiceURL.toURI().toURL().toExternalForm()); Runtime.getRuntime().exec("open " + getExePath().toURI().toURL().toExternalForm() + " " + "--hostURL" + " " + hostServiceURL.toURI().toURL().toExternalForm() + " " + "--applicationURL" + " " + appServiceURL.toURI().toURL().toExternalForm()); /*List<String> command = new ArrayList<String>(); command.add("/bin/sh"); command.add(getExePath().getCanonicalPath()); command.add("--hostURL"); command.add(hostServiceURL.toURI().toURL().toExternalForm()); command.add("--applicationURL"); command.add(appServiceURL.toURI().toURL().toExternalForm()); ProcessBuilder builder = new ProcessBuilder(command); //Map<String, String> environ = builder.environment(); //builder.directory(new File(System.getenv("temp"))); //System.out.println("Directory : " + System.getenv("temp") ); final Process process = builder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { System.out.println(line); } System.out.println("Program terminated!"); */ } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { try { Runtime.getRuntime().exec(getExePath().toURI().toURL().toExternalForm() + " " + "--hostURL" + " " + hostServiceURL.toURI().toURL().toExternalForm() + " " + "--applicationURL" + " " + appServiceURL.toURI().toURL().toExternalForm()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } // TODO Auto-generated catch block } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } //startIterator availableDataItems = new ArrayList<AvailableData>(); //Query query = new AVTQueryStub(null, null, null, null, null); //SearchResultSetupAvailableData resultForSubqueries = new SearchResultSetupAvailableData(); //SearchResult selectedDataSearchResult = resultForSubqueries.getSearchResult(); TargetIteratorRunner targetIter = new TargetIteratorRunner(selectedDataSearchResult, getIterationTarget(), query, getApplicationTmpDir(), this); try { Thread t = new Thread(targetIter); t.start(); } catch(Exception e) { logger.error(e, e); } } public Endpoint getHostEndpoint(){ return hostEndpoint; } File appOutputDir; public void setApplicationOutputDir(File outDir){ try { appOutputDir = Util.create("xipOUT_" + getName() + "_", "", outDir); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public File getApplicationOutputDir() { return appOutputDir; } File appTmpDir; public void setApplicationTmpDir(File tmpDir){ appTmpDir = tmpDir; } public File getApplicationTmpDir() { return appTmpDir; } java.awt.Rectangle preferredSize; public void setApplicationPreferredSize(java.awt.Rectangle preferredSize){ this.preferredSize = preferredSize; } State priorState = null; State state = null; public void setState(State state){ priorState = this.state; this.state = state; logger.debug("State changed to: " + this.state); if(this.state.equals(State.INPROGRESS)){ notifyDataAvailable(); } } public State getState(){ return state; } public State getPriorState(){ return priorState; } WG23DataModel wg23dm = null; public void setData(WG23DataModel wg23DataModel){ this.wg23dm = wg23DataModel; } public WG23DataModel getWG23DataModel(){ return wg23dm; } SearchResult selectedDataSearchResult; public void setSelectedDataSearchResult(SearchResult selectedDataSearchResult){ this.selectedDataSearchResult = selectedDataSearchResult; } Query query; public void setDataSource(Query query){ this.query = query; } public Rectangle getApplicationPreferredSize() { double x = preferredSize.getX(); double y = preferredSize.getY(); double width = preferredSize.getWidth(); double height = preferredSize.getHeight(); Rectangle rect = new Rectangle(); rect.setRefPointX(new Double(x).intValue()); rect.setRefPointY(new Double(y).intValue()); rect.setWidth(new Double(width).intValue()); rect.setHeight(new Double(height).intValue()); return rect; } public URL getApplicationServiceURL(){ return appServiceURL; } public void notifyAddSideTab(){ HostMainWindow.addTab(getName(), getID()); } public void bringToFront(){ clientToApplication.bringToFront(); } public boolean shutDown(){ if(getState().equals(State.IDLE)){ if(getClientToApplication().setState(State.EXIT)){ return true; } }else{ if(cancelProcessing()){ return shutDown(); } } return false; } public void runShutDownSequence(){ HostMainWindow.removeTab(getID()); getHostEndpoint().stop(); //Delete documents from Xindice created for this application XindiceManagerFactory.getInstance().deleteAllDocuments(getID().toString()); //Delete collection created for this application XindiceManagerFactory.getInstance().deleteCollection(getID().toString()); } public boolean cancelProcessing(){ if(getState().equals(State.INPROGRESS) || getState().equals(State.SUSPENDED)){ return getClientToApplication().setState(State.CANCELED); }else{ return false; } } public boolean suspendProcessing(){ if(getState().equals(State.INPROGRESS)){ return getClientToApplication().setState(State.SUSPENDED); }else{ return false; } } /** * Method is used to create XML native models for all object locators * found in WG23DataModel. * It uses threads and add NativeModelListener to the NativeModelRunner * @param wg23dm */ void createNativeModels(WG23DataModel wg23dm){ if(XindiceManagerFactory.getInstance().createCollection(getID().toString())){ ObjectLocator[] objLocs = wg23dm.getObjectLocators(); for (int i = 0; i < objLocs.length; i++){ boolean isDICOM = false; try { isDICOM = DicomUtil.isDICOM(new File(new URI(objLocs[i].getUri()))); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(isDICOM){ NativeModelRunner nmRunner; nmRunner = new NativeModelRunner(objLocs[i]); nmRunner.addNativeModelListener(this); Thread t = new Thread(nmRunner); t.start(); } } }else{ //TODO //Action when system cannot create collection } } /** * Adds JDOM Document to Xindice collection. * Only valid documents (e.g. not null, with root element) will be added * (non-Javadoc) * @see edu.wustl.xipHost.wg23.NativeModelListener#nativeModelAvailable(org.jdom.Document, org.nema.dicom.wg23.Uuid) */ public void nativeModelAvailable(Document doc, Uuid objUUID) { XindiceManagerFactory.getInstance().addDocument(doc, getID().toString(), objUUID); } public void nativeModelAvailable(String xmlNativeModel) { // Ignore in XIP Host. // Used by AVT AD } /** * Method returns ModelSetDescriptor containing UUID of native models * as well as UUID of object locators for which native models could * not be created * @param objUUIDs * @return */ public ModelSetDescriptor getModelSetDescriptor(List<Uuid> objUUIDs){ String[] models = XindiceManagerFactory.getInstance().getModelUUIDs(getID().toString()); List<String> listModels = Arrays.asList(models); ModelSetDescriptor msd = new ModelSetDescriptor(); ArrayOfUUID uuidsModels = new ArrayOfUUID(); List<Uuid> listUUIDs = uuidsModels.getUuid(); ArrayOfUUID uuidsFailed = new ArrayOfUUID(); List<Uuid> listUUIDsFailed = uuidsFailed.getUuid(); for(int i = 0; i < objUUIDs.size(); i++){ Uuid uuid = new Uuid(); if(objUUIDs.get(i) == null || objUUIDs.get(i).getUuid() == null){ //do not add anything to model set descriptor }else if(objUUIDs.get(i).getUuid().toString().trim().isEmpty()){ //do not add anything to model set descriptor }else if(listModels.contains("wg23NM-"+ objUUIDs.get(i).getUuid())){ int index = listModels.indexOf("wg23NM-"+ objUUIDs.get(i).getUuid()); uuid.setUuid(listModels.get(index)); listUUIDs.add(uuid); }else{ uuid.setUuid(objUUIDs.get(i).getUuid()); listUUIDsFailed.add(uuid); } } msd.setModels(uuidsModels); msd.setFailedSourceObjects(uuidsFailed); return msd; } /** * queryResults list hold teh values from queryResultAvailable */ List<QueryResult> queryResults; public List<QueryResult> queryModel(List<Uuid> modelUUIDs, List<String> listXPaths){ queryResults = new ArrayList<QueryResult>(); if(modelUUIDs == null || listXPaths == null){ return queryResults; } String collectionName = getID().toString(); XindiceManager xm = XindiceManagerFactory.getInstance(); for(int i = 0; i < listXPaths.size(); i++){ for(int j = 0; j < modelUUIDs.size(); j++){ //String[] results = xm.query(service, collectionName, modelUUIDs.get(j), listXPaths.get(i)); String[] results = xm.query(collectionName, modelUUIDs.get(j), listXPaths.get(i)); QueryResult queryResult = new QueryResult(); queryResult.setModel(modelUUIDs.get(j)); queryResult.setXpath(listXPaths.get(i)); ArrayOfString arrayOfString = new ArrayOfString(); List<String> listString = arrayOfString.getString(); for(int k = 0; k < results.length; k++){ listString.add(results[k]); } queryResult.setResults(arrayOfString); queryResults.add(queryResult); } } return queryResults; } Iterator<TargetElement> iter = null; @SuppressWarnings("unchecked") @Override public synchronized void fullIteratorAvailable(IteratorEvent e) { iter = (Iterator<TargetElement>)e.getSource(); } List<AvailableData> availableDataItems; AVTUtil util = new AVTUtil(); @Override public void targetElementAvailable(IteratorElementEvent e) { TargetElement element = (TargetElement) e.getSource(); WG23DataModel wg23data = util.getWG23DataModel(element); AvailableData availableData = wg23data.getAvailableData(); synchronized(availableDataItems){ availableDataItems.add(availableData); } } void notifyDataAvailable(){ // for loop need to be replaced. When state changes to INPROGRESS and // availableDataItems is empty (size = 0) notification is going to fail. int size = availableDataItems.size(); for (int i = 0; i < size; i++){ AvailableData availableData = availableDataItems.get(i); if(iter != null && size == i){ getClientToApplication().notifyDataAvailable(availableData, true); } else { getClientToApplication().notifyDataAvailable(availableData, false); } if(iter != null){ size = availableDataItems.size(); } while(iter == null && size == i){ } } } }
src/edu/wustl/xipHost/application/Application.java
/** * Copyright (c) 2008 Washington University in Saint Louis. All Rights Reserved. */ package edu.wustl.xipHost.application; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.UUID; import javax.xml.ws.Endpoint; import org.apache.log4j.Logger; import org.jdom.Document; import org.nema.dicom.wg23.ArrayOfString; import org.nema.dicom.wg23.ArrayOfUUID; import org.nema.dicom.wg23.AvailableData; import org.nema.dicom.wg23.Host; import org.nema.dicom.wg23.ModelSetDescriptor; import org.nema.dicom.wg23.ObjectLocator; import org.nema.dicom.wg23.QueryResult; import org.nema.dicom.wg23.Rectangle; import org.nema.dicom.wg23.State; import org.nema.dicom.wg23.Uuid; import edu.wustl.xipHost.avt2ext.AVTQueryStub; import edu.wustl.xipHost.avt2ext.AVTUtil; import edu.wustl.xipHost.avt2ext.Query; import edu.wustl.xipHost.avt2ext.SearchResultSetupAvailableData; import edu.wustl.xipHost.avt2ext.iterator.IterationTarget; import edu.wustl.xipHost.avt2ext.iterator.IteratorElementEvent; import edu.wustl.xipHost.avt2ext.iterator.IteratorEvent; import edu.wustl.xipHost.avt2ext.iterator.TargetElement; import edu.wustl.xipHost.avt2ext.iterator.TargetIteratorRunner; import edu.wustl.xipHost.avt2ext.iterator.TargetIteratorListener; import edu.wustl.xipHost.dataModel.SearchResult; import edu.wustl.xipHost.dicom.DicomUtil; import edu.wustl.xipHost.gui.HostMainWindow; import edu.wustl.xipHost.hostControl.Util; import edu.wustl.xipHost.hostControl.XindiceManager; import edu.wustl.xipHost.hostControl.XindiceManagerFactory; import edu.wustl.xipHost.wg23.ClientToApplication; import edu.wustl.xipHost.wg23.HostImpl; import edu.wustl.xipHost.wg23.NativeModelListener; import edu.wustl.xipHost.wg23.NativeModelRunner; import edu.wustl.xipHost.wg23.WG23DataModel; public class Application implements NativeModelListener, TargetIteratorListener { final static Logger logger = Logger.getLogger(Application.class); UUID id; String name; File exePath; String vendor; String version; File iconFile; String type; boolean requiresGUI; String wg23DataModelType; int concurrentInstances; IterationTarget iterationTarget; /* Application is a WG23 compatibile application*/ public Application(String name, File exePath, String vendor, String version, File iconFile, String type, boolean requiresGUI, String wg23DataModelType, int concurrentInstances, IterationTarget iterationTarget){ if(name == null || exePath == null || vendor == null || version == null || type == null || wg23DataModelType == null || iterationTarget == null){ throw new IllegalArgumentException("Application parameters are invalid: " + name + " , " + exePath + " , " + vendor + " , " + version + type + " , " + requiresGUI + " , " + wg23DataModelType + " , " + iterationTarget); } else if(name.isEmpty() || name.trim().length() == 0 || exePath.exists() == false){ try { throw new IllegalArgumentException("Application parameters are invalid: " + name + " , " + exePath.getCanonicalPath() + " , " + vendor + " , " + version); } catch (IOException e) { throw new IllegalArgumentException("Application exePath is invalid. Application name: " + name); } } else{ id = UUID.randomUUID(); this.name = name; this.exePath = exePath; this.vendor = vendor; this.version = version; if(iconFile != null && iconFile.exists()){ this.iconFile = iconFile; }else{ this.iconFile = null; } this.type = type; this.requiresGUI = requiresGUI; this.wg23DataModelType = wg23DataModelType; this.concurrentInstances = concurrentInstances; this.iterationTarget = iterationTarget; } } //verify this pattern /*public boolean verifyFileName(String fileName){ String str = "/ \\ : * ? \" < > | , "; Pattern filePattern = Pattern.compile(str); boolean matches = filePattern.matcher(fileName).matches(); return matches; } public static void main (String args[]){ Application app = new Application("ApplicationTest", new File("test.txt"), "", ""); System.out.println(app.getExePath().getName()); System.out.println(app.verifyFileName(app.getExePath().getName())); }*/ public UUID getID(){ return id; } public String getName(){ return name; } public void setName(String name){ if(name == null || name.isEmpty() || name.trim().length() == 0){ throw new IllegalArgumentException("Invalid application name: " + name); }else{ this.name = name; } } public File getExePath(){ return exePath; } public void setExePath(File path){ if(path == null){ throw new IllegalArgumentException("Invalid exePath name: " + path); }else{ exePath = path; } } public String getVendor(){ return vendor; } public void setVendor(String vendor){ if(vendor == null){ throw new IllegalArgumentException("Invalid vendor: " + vendor); }else{ this.vendor = vendor; } } public String getVersion(){ return version; } public void setVersion(String version){ if(version == null){ throw new IllegalArgumentException("Invalid version: " + version); }else{ this.version = version; } } public File getIconFile(){ return iconFile; } public void setIconFile(File iconFile){ if(iconFile == null){ throw new IllegalArgumentException("Invalid exePath name: " + iconFile); }else{ this.iconFile = iconFile; } } public String getType() { return type; } public void setType(String type) { this.type = type; } public boolean requiresGUI() { return requiresGUI; } public void setRequiresGUI(boolean requiresGUI) { this.requiresGUI = requiresGUI; } public String getWG23DataModelType() { return wg23DataModelType; } public void setWG23DataModelType(String wg23DataModelType) { this.wg23DataModelType = wg23DataModelType; } public int getConcurrentInstances() { return concurrentInstances; } public void setConcurrentInstances(int concurrentInstances) { this.concurrentInstances = concurrentInstances; } public IterationTarget getIterationTarget() { return iterationTarget; } public void setIterationTarget(IterationTarget iterationTarget) { this.iterationTarget = iterationTarget; } //Each application has: //1. Out directories assigned //2. clientToApplication //3. Host scheleton (reciever) //4. Data assigned for processing //5. Data produced //when launching diploy service and set URLs ClientToApplication clientToApplication; public void startClientToApplication(){ clientToApplication = new ClientToApplication(getApplicationServiceURL()); } public ClientToApplication getClientToApplication(){ return clientToApplication; } //Implementation HostImpl is used to be able to add WG23Listener //It is eventually casted to Host type Host host = new HostImpl(this); //All loaded application by default will be saved again. //New instances of an application will be saved only when the save checkbox is selected Boolean doSave = true; public void setDoSave(boolean doSave){ this.doSave = doSave; } public boolean getDoSave(){ return doSave; } Endpoint hostEndpoint; URL hostServiceURL; URL appServiceURL; public void launch(URL hostServiceURL, URL appServiceURL){ this.hostServiceURL = hostServiceURL; this.appServiceURL = appServiceURL; setApplicationOutputDir(ApplicationManagerFactory.getInstance().getOutputDir()); setApplicationTmpDir(ApplicationManagerFactory.getInstance().getTmpDir()); setApplicationPreferredSize(HostMainWindow.getApplicationPreferredSize()); //prepare native models //createNativeModels(getWG23DataModel()); //diploy host service hostEndpoint = Endpoint.publish(hostServiceURL.toString(), host); // Ways of launching XIP application: exe, bat, class or jar //if(((String)getExePath().getName()).endsWith(".exe") || ((String)getExePath().getName()).endsWith(".bat")){ try { if(getExePath().toURI().toURL().toExternalForm().endsWith(".exe") || getExePath().toURI().toURL().toExternalForm().endsWith(".bat")){ //TODO unvoid try { Runtime.getRuntime().exec("cmd /c start /min " + getExePath().toURI().toURL().toExternalForm() + " " + "--hostURL" + " " + hostServiceURL.toURI().toURL().toExternalForm() + " " + "--applicationURL" + " " + appServiceURL.toURI().toURL().toExternalForm()); /*List< String > command = new LinkedList<String>(); command.add("cmd"); command.add("/c"); command.add("start"); command.add("/min"); command.add(getExePath().getCanonicalPath()); command.add("--hostURL"); command.add(hostServiceURL.toURI().toURL().toExternalForm()); command.add( "--applicationURL" ); command.add(appServiceURL.toURI().toURL().toExternalForm()); ProcessBuilder builder = new ProcessBuilder(command); String str =""; for(int i = 0; i < command.size(); i++){ str = str + command.get(i) + " "; } System.out.println(str); File dir = getExePath().getParentFile(); builder.directory(dir); builder.start();*/ } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (getExePath().toURI().toURL().toExternalForm().endsWith(".sh")){ try { //Runtime.getRuntime().exec("/bin/sh " + getExePath().getCanonicalPath() + " " + "--hostURL" + " " + hostServiceURL.toURI().toURL().toExternalForm() + " " + "--applicationURL" + " " + appServiceURL.toURI().toURL().toExternalForm()); System.out.println(getExePath().toURI().toURL().toExternalForm() + " " + "--hostURL" + " " + hostServiceURL.toURI().toURL().toExternalForm() + " " + "--applicationURL" + " " + appServiceURL.toURI().toURL().toExternalForm()); Runtime.getRuntime().exec("open " + getExePath().toURI().toURL().toExternalForm() + " " + "--hostURL" + " " + hostServiceURL.toURI().toURL().toExternalForm() + " " + "--applicationURL" + " " + appServiceURL.toURI().toURL().toExternalForm()); /*List<String> command = new ArrayList<String>(); command.add("/bin/sh"); command.add(getExePath().getCanonicalPath()); command.add("--hostURL"); command.add(hostServiceURL.toURI().toURL().toExternalForm()); command.add("--applicationURL"); command.add(appServiceURL.toURI().toURL().toExternalForm()); ProcessBuilder builder = new ProcessBuilder(command); //Map<String, String> environ = builder.environment(); //builder.directory(new File(System.getenv("temp"))); //System.out.println("Directory : " + System.getenv("temp") ); final Process process = builder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { System.out.println(line); } System.out.println("Program terminated!"); */ } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { try { Runtime.getRuntime().exec(getExePath().toURI().toURL().toExternalForm() + " " + "--hostURL" + " " + hostServiceURL.toURI().toURL().toExternalForm() + " " + "--applicationURL" + " " + appServiceURL.toURI().toURL().toExternalForm()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } // TODO Auto-generated catch block } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } //startIterator availableDataItems = new ArrayList<AvailableData>(); Query avtQuery = new AVTQueryStub(null, null, null, null, null); SearchResultSetupAvailableData resultForSubqueries = new SearchResultSetupAvailableData(); SearchResult selectedDataSearchResult = resultForSubqueries.getSearchResult(); TargetIteratorRunner targetIter = new TargetIteratorRunner(selectedDataSearchResult, IterationTarget.SERIES, avtQuery, getApplicationTmpDir(), this); try { Thread t = new Thread(targetIter); t.start(); } catch(Exception e) { logger.error(e, e); } } public Endpoint getHostEndpoint(){ return hostEndpoint; } File appOutputDir; public void setApplicationOutputDir(File outDir){ try { appOutputDir = Util.create("xipOUT_" + getName() + "_", "", outDir); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public File getApplicationOutputDir() { return appOutputDir; } File appTmpDir; public void setApplicationTmpDir(File tmpDir){ appTmpDir = tmpDir; } public File getApplicationTmpDir() { return appTmpDir; } java.awt.Rectangle preferredSize; public void setApplicationPreferredSize(java.awt.Rectangle preferredSize){ this.preferredSize = preferredSize; } State priorState = null; State state = null; public void setState(State state){ priorState = this.state; this.state = state; logger.debug("State changed to: " + this.state); if(this.state.equals(State.INPROGRESS)){ notifyDataAvailable(); } } public State getState(){ return state; } public State getPriorState(){ return priorState; } WG23DataModel wg23dm = null; public void setData(WG23DataModel wg23DataModel){ this.wg23dm = wg23DataModel; } SearchResult selectedDataSearchResult; public void setSelectedDataSearchResult(SearchResult selectedDataSearchResult){ this.selectedDataSearchResult = selectedDataSearchResult; } public WG23DataModel getWG23DataModel(){ return wg23dm; } public Rectangle getApplicationPreferredSize() { double x = preferredSize.getX(); double y = preferredSize.getY(); double width = preferredSize.getWidth(); double height = preferredSize.getHeight(); Rectangle rect = new Rectangle(); rect.setRefPointX(new Double(x).intValue()); rect.setRefPointY(new Double(y).intValue()); rect.setWidth(new Double(width).intValue()); rect.setHeight(new Double(height).intValue()); return rect; } public URL getApplicationServiceURL(){ return appServiceURL; } public void notifyAddSideTab(){ HostMainWindow.addTab(getName(), getID()); } public void bringToFront(){ clientToApplication.bringToFront(); } public boolean shutDown(){ if(getState().equals(State.IDLE)){ if(getClientToApplication().setState(State.EXIT)){ return true; } }else{ if(cancelProcessing()){ return shutDown(); } } return false; } public void runShutDownSequence(){ HostMainWindow.removeTab(getID()); getHostEndpoint().stop(); //Delete documents from Xindice created for this application XindiceManagerFactory.getInstance().deleteAllDocuments(getID().toString()); //Delete collection created for this application XindiceManagerFactory.getInstance().deleteCollection(getID().toString()); } public boolean cancelProcessing(){ if(getState().equals(State.INPROGRESS) || getState().equals(State.SUSPENDED)){ return getClientToApplication().setState(State.CANCELED); }else{ return false; } } public boolean suspendProcessing(){ if(getState().equals(State.INPROGRESS)){ return getClientToApplication().setState(State.SUSPENDED); }else{ return false; } } /** * Method is used to create XML native models for all object locators * found in WG23DataModel. * It uses threads and add NativeModelListener to the NativeModelRunner * @param wg23dm */ void createNativeModels(WG23DataModel wg23dm){ if(XindiceManagerFactory.getInstance().createCollection(getID().toString())){ ObjectLocator[] objLocs = wg23dm.getObjectLocators(); for (int i = 0; i < objLocs.length; i++){ boolean isDICOM = false; try { isDICOM = DicomUtil.isDICOM(new File(new URI(objLocs[i].getUri()))); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(isDICOM){ NativeModelRunner nmRunner; nmRunner = new NativeModelRunner(objLocs[i]); nmRunner.addNativeModelListener(this); Thread t = new Thread(nmRunner); t.start(); } } }else{ //TODO //Action when system cannot create collection } } /** * Adds JDOM Document to Xindice collection. * Only valid documents (e.g. not null, with root element) will be added * (non-Javadoc) * @see edu.wustl.xipHost.wg23.NativeModelListener#nativeModelAvailable(org.jdom.Document, org.nema.dicom.wg23.Uuid) */ public void nativeModelAvailable(Document doc, Uuid objUUID) { XindiceManagerFactory.getInstance().addDocument(doc, getID().toString(), objUUID); } public void nativeModelAvailable(String xmlNativeModel) { // Ignore in XIP Host. // Used by AVT AD } /** * Method returns ModelSetDescriptor containing UUID of native models * as well as UUID of object locators for which native models could * not be created * @param objUUIDs * @return */ public ModelSetDescriptor getModelSetDescriptor(List<Uuid> objUUIDs){ String[] models = XindiceManagerFactory.getInstance().getModelUUIDs(getID().toString()); List<String> listModels = Arrays.asList(models); ModelSetDescriptor msd = new ModelSetDescriptor(); ArrayOfUUID uuidsModels = new ArrayOfUUID(); List<Uuid> listUUIDs = uuidsModels.getUuid(); ArrayOfUUID uuidsFailed = new ArrayOfUUID(); List<Uuid> listUUIDsFailed = uuidsFailed.getUuid(); for(int i = 0; i < objUUIDs.size(); i++){ Uuid uuid = new Uuid(); if(objUUIDs.get(i) == null || objUUIDs.get(i).getUuid() == null){ //do not add anything to model set descriptor }else if(objUUIDs.get(i).getUuid().toString().trim().isEmpty()){ //do not add anything to model set descriptor }else if(listModels.contains("wg23NM-"+ objUUIDs.get(i).getUuid())){ int index = listModels.indexOf("wg23NM-"+ objUUIDs.get(i).getUuid()); uuid.setUuid(listModels.get(index)); listUUIDs.add(uuid); }else{ uuid.setUuid(objUUIDs.get(i).getUuid()); listUUIDsFailed.add(uuid); } } msd.setModels(uuidsModels); msd.setFailedSourceObjects(uuidsFailed); return msd; } /** * queryResults list hold teh values from queryResultAvailable */ List<QueryResult> queryResults; public List<QueryResult> queryModel(List<Uuid> modelUUIDs, List<String> listXPaths){ queryResults = new ArrayList<QueryResult>(); if(modelUUIDs == null || listXPaths == null){ return queryResults; } String collectionName = getID().toString(); XindiceManager xm = XindiceManagerFactory.getInstance(); for(int i = 0; i < listXPaths.size(); i++){ for(int j = 0; j < modelUUIDs.size(); j++){ //String[] results = xm.query(service, collectionName, modelUUIDs.get(j), listXPaths.get(i)); String[] results = xm.query(collectionName, modelUUIDs.get(j), listXPaths.get(i)); QueryResult queryResult = new QueryResult(); queryResult.setModel(modelUUIDs.get(j)); queryResult.setXpath(listXPaths.get(i)); ArrayOfString arrayOfString = new ArrayOfString(); List<String> listString = arrayOfString.getString(); for(int k = 0; k < results.length; k++){ listString.add(results[k]); } queryResult.setResults(arrayOfString); queryResults.add(queryResult); } } return queryResults; } Iterator<TargetElement> iter = null; @SuppressWarnings("unchecked") @Override public synchronized void fullIteratorAvailable(IteratorEvent e) { iter = (Iterator<TargetElement>)e.getSource(); } List<AvailableData> availableDataItems; AVTUtil util = new AVTUtil(); @Override public void targetElementAvailable(IteratorElementEvent e) { TargetElement element = (TargetElement) e.getSource(); WG23DataModel wg23data = util.getWG23DataModel(element); AvailableData availableData = wg23data.getAvailableData(); synchronized(availableDataItems){ availableDataItems.add(availableData); } } void notifyDataAvailable(){ // for loop need to be replaced. When state changes to INPROGRESS and // availableDataItems is empty (size = 0) notification is going to fail. int size = availableDataItems.size(); for (int i = 0; i < size; i++){ AvailableData availableData = availableDataItems.get(i); if(iter != null && size == i){ getClientToApplication().notifyDataAvailable(availableData, true); } else { getClientToApplication().notifyDataAvailable(availableData, false); } if(iter != null){ size = availableDataItems.size(); } while(iter == null && size == i){ } } } }
Replaced stub code with actual implementation in launch() method of the Application class. SVN-Revision: 483
src/edu/wustl/xipHost/application/Application.java
Replaced stub code with actual implementation in launch() method of the Application class.
Java
apache-2.0
d0c51aa671acbb6eeb88730a0ec3cb6a657599e2
0
davidmelo26/Proyectos
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package estructurasdedatos.cap4.arboles; /** * * @author tusk */ public class ArbolAVL { private NodoAVL raiz; public ArbolAVL (){ raiz = null; } public int factorEquilibrio (NodoAVL dato){ if (dato==null){ return -1; }else{ return dato.factorEquilibrio; } } //rotacion derecha public NodoAVL rotarDerecha (NodoAVL c){ NodoAVL auxiliar = c.hijoIzquierdo; c.hijoIzquierdo = auxiliar.hijoDerecho; auxiliar.hijoDerecho = c; c.factorEquilibrio = Math.max(factorEquilibrio(c.hijoDerecho), factorEquilibrio(c.hijoDerecho))+1; auxiliar.factorEquilibrio = Math.max(factorEquilibrio(auxiliar.hijoDerecho), factorEquilibrio(auxiliar.hijoDerecho))+1; return auxiliar; } //rotacion izquierda public NodoAVL rotarIzquierda (NodoAVL c){ NodoAVL auxiliar = c.hijoDerecho; c.hijoDerecho = auxiliar.hijoIzquierdo; auxiliar.hijoIzquierdo = c; c.factorEquilibrio = Math.max(factorEquilibrio(c.hijoIzquierdo), factorEquilibrio(c.hijoDerecho))+1; auxiliar.factorEquilibrio = Math.max(factorEquilibrio(auxiliar.hijoIzquierdo), factorEquilibrio(auxiliar.hijoDerecho))+1; return auxiliar; } public void insertar(int dato){ NodoAVL nuevo = new NodoAVL(dato); if(raiz == null){ raiz = nuevo; }else{ raiz = insertarAVL(nuevo, raiz); } } //Mostrar public void preOrden (NodoArbolBinario raiz){ if(raiz != null){ System.out.println(raiz.getDato()); preOrden(raiz.getHijoIzquierdo()); preOrden (raiz.getHijoDerecho()); } } public void orden(NodoArbolBinario raiz){ if(raiz != null){ orden (raiz.getHijoIzquierdo()); System.out.println(raiz.getDato()); orden (raiz.getHijoDerecho()); } } public void postOrden (NodoArbolBinario raiz){ if(raiz != null){ postOrden(raiz.getHijoIzquierdo()); postOrden(raiz.getHijoDerecho()); System.out.println(raiz.getDato()); } } }
src/estructurasdedatos/cap4/arboles/ArbolAVL.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package estructurasdedatos.cap4.arboles; /** * * @author tusk */ public class ArbolAVL { private int dato; private NodoAVL hijoDerecho; private NodoAVL hijoIzquierdo; private NodoAVL FactorEquilibrio; public ArbolAVL (int dato){ this.dato = dato; } }
Update ArbolAVL.java
src/estructurasdedatos/cap4/arboles/ArbolAVL.java
Update ArbolAVL.java
Java
apache-2.0
ad398bc76214356350dce76efdb0ca0a5a88693d
0
fishercoder1534/Leetcode,fishercoder1534/Leetcode,fishercoder1534/Leetcode,fishercoder1534/Leetcode,fishercoder1534/Leetcode
package com.fishercoder.solutions; import java.util.Arrays; public class _646 { public static class Solution1 { /** * credit: https://discuss.leetcode.com/topic/96804/java-o-nlog-n-time-o-1-space */ public int findLongestChain(int[][] pairs) { Arrays.sort(pairs, (o1, o2) -> o1[1] - o2[1]); int result = 0; int n = pairs.length; int i = -1; while (++i < n) { result++; int curEnd = pairs[i][1]; while (i + 1 < n && pairs[i + 1][0] <= curEnd) { /**This means, we'll keep incrementing i until pairs[i+1][0] is * exactly greater than curEnd.*/ i++; } } return result; } } }
src/main/java/com/fishercoder/solutions/_646.java
package com.fishercoder.solutions; import java.util.Arrays; /** * 646. Maximum Length of Pair Chain * * You are given n pairs of numbers. In every pair, the first number is always smaller than the second number. Now, we define a pair (c, d) can follow another pair (a, b) if and only if b < c. Chain of pairs can be formed in this fashion. Given a set of pairs, find the length longest chain which can be formed. You needn't use up all the given pairs. You can select pairs in any order. Example 1: Input: [[1,2], [2,3], [3,4]] Output: 2 Explanation: The longest chain is [1,2] -> [3,4] Note: The number of given pairs will be in the range [1, 1000]. */ public class _646 { public static class Solution1 { /** * credit: https://discuss.leetcode.com/topic/96804/java-o-nlog-n-time-o-1-space */ public int findLongestChain(int[][] pairs) { Arrays.sort(pairs, (o1, o2) -> o1[1] - o2[1]); int result = 0; int n = pairs.length; int i = -1; while (++i < n) { result++; int curEnd = pairs[i][1]; while (i + 1 < n && pairs[i + 1][0] <= curEnd) { /**This means, we'll keep incrementing i until pairs[i+1][0] is * exactly greater than curEnd.*/ i++; } } return result; } } }
refactor 646
src/main/java/com/fishercoder/solutions/_646.java
refactor 646