repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
beninato8/MenloHacksMod
src/main/java/beninato/menlohacks/items/ItemDonut.java
672
package beninato.menlohacks.items; import beninato.menlohacks.FirstMod; import beninato.menlohacks.Reference; import net.minecraft.item.ItemFood; import net.minecraft.potion.PotionEffect; public class ItemDonut extends ItemFood { public ItemDonut() { super(5, 10f, false); setUnlocalizedName(Reference.FirstModItems.DONUT.getUnlocalizedName()); setRegistryName(Reference.FirstModItems.DONUT.getRegistryName()); setCreativeTab(FirstMod.CREATIVE_TAB); } /*public ItemFood setPotionEffect(PotionEffect p_185070_1_, float p_185070_2_) { this.potionId = p_185070_1_; this.potionEffectProbability = p_185070_2_; return this; }*/ }
lgpl-3.0
tango-controls/JTango
common/src/test/java/fr/esrf/TangoApi/DevicePipeTest.java
2745
package fr.esrf.TangoApi; import fr.esrf.Tango.DevFailed; import fr.esrf.Tango.DevState; import org.junit.Before; import org.junit.Test; import static junit.framework.Assert.assertEquals; import static org.junit.Assert.*; /** * @author Igor Khokhriakov <igor.khokhriakov@hzg.de> * @since 02.10.14 */ public class DevicePipeTest { private PipeBlob blob; @Before public void before() throws Exception{ PipeBlobBuilder childBuilder = new PipeBlobBuilder("Name / Age"); childBuilder.add("Chloe", 30); childBuilder.add("Nicolas", 28); childBuilder.add("Auxane", 21); // Build the main blob and insert inner one PipeBlobBuilder blobBuilder = new PipeBlobBuilder("Pascal"); blobBuilder.add("City", "Grenoble"); blobBuilder.add("Values", new float[]{1.23f, 4.56f, 7.89f}); blobBuilder.add("Children", childBuilder.build()); blobBuilder.add("Status", DevState.RUNNING); blob = blobBuilder.build(); } @Test public void testScannerAPI() throws Exception{ PipeScanner instance = new DevicePipe("TestPipe",blob); assertEquals("Grenoble", instance.nextString()); float[] actualFloatArray = new float[3]; instance.nextArray(actualFloatArray, 3); assertArrayEquals(new float[]{1.23f, 4.56f, 7.89f}, actualFloatArray, 0.1F); PipeScanner innerInstance = instance.nextScanner(); assertEquals(30, innerInstance.nextInt()); assertEquals(28, innerInstance.nextInt()); assertEquals(21, innerInstance.nextInt()); assertSame(DevState.RUNNING, instance.nextState()); assertFalse(instance.hasNext()); } @Test(expected = DevFailed.class) public void testScannerAPI_wrongType() throws Exception{ PipeScanner instance = new DevicePipe("TestPipe",blob); instance.nextDouble(); } @Test(expected = DevFailed.class) public void testScannerAPI_wrongSize() throws Exception{ PipeScanner instance = new DevicePipe("TestPipe",blob); instance.move(); instance.nextArray(new float[0], 5); } @Test(expected = DevFailed.class) public void testScannerAPI_arrayOfWrongType() throws Exception { PipeScanner instance = new DevicePipe("TestPipe", blob); instance.move(); instance.nextArray(int[].class); } @Test public void testScannerAPI_nextArray() throws Exception { PipeScanner instance = new DevicePipe("TestPipe", blob); instance.move(); float[] result = instance.nextArray(float[].class); assertTrue(3 == result.length); assertArrayEquals(new float[]{1.23f, 4.56f, 7.89f}, result, 0.1F); } }
lgpl-3.0
SINTEF-9012/sensapp-acceptance
src/main/java/net/modelbased/sensapp/acceptance/driver/configuration/EndPoints.java
2360
/** * This file is part of SensApp Acceptance. * * SensApp Acceptance 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 3 of the License, or * (at your option) any later version. * * SensApp Acceptance 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 SensApp Acceptance. If not, see <http://www.gnu.org/licenses/>. */ package net.modelbased.sensapp.acceptance.driver.configuration; import java.net.MalformedURLException; import java.net.URL; import net.modelbased.sensapp.acceptance.driver.Service; import java.util.EnumMap; import java.util.Map; import static net.modelbased.sensapp.util.dbc.Contracts.*; import static org.hamcrest.Matchers.*; /** * Hold the URL associated with the endpoints of the SensApp services */ public class EndPoints { private final Map<Service, URL> endPoints; /** * Create the EndPoints set from a mapping between service name and URL. * * @param urlByService a mapping from service name to URL * @throws MissingEndPointException if some service are not provided with * any URL * @throws MalformedURLException if some URL are invalid */ public EndPoints(Map<String, String> urlByService) throws MissingEndPointException, MalformedURLException { require(urlByService, is(not(nullValue()))); this.endPoints = new EnumMap<>(Service.class); for (Service eachService: Service.values()) { final String urlText = urlByService.get(eachService.toString()); if (urlText == null) { throw new MissingEndPointException(eachService); } this.endPoints.put(eachService, new URL(urlText)); } } /** * @return the URL associated with the given service * @param service the service whose URL is needed * */ public URL getUrlOf(Service service) { require(service, is(not(nullValue()))); return endPoints.get(service); } }
lgpl-3.0
holycrap872/green-solver
green/src/za/ac/sun/cs/green/service/factorizer/ModelFactorizerService.java
3560
package za.ac.sun.cs.green.service.factorizer; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import za.ac.sun.cs.green.Green; import za.ac.sun.cs.green.Instance; import za.ac.sun.cs.green.Service; import za.ac.sun.cs.green.expr.Expression; import za.ac.sun.cs.green.expr.Variable; import za.ac.sun.cs.green.service.BasicService; import za.ac.sun.cs.green.util.Reporter; public class ModelFactorizerService extends BasicService { private static final String FACTORS = "FACTORS"; private static final String MODELS = "MODELS"; private static final String FACTORS_UNSOLVED = "FACTORS_UNSOLVED"; /** * Number of times the slicer has been invoked. */ private int invocationCount = 0; /** * Total number of constraints processed. */ private int constraintCount = 0; /** * Number of factored constraints returned. */ private int factorCount = 0; public ModelFactorizerService(Green solver) { super(solver); } @Override public Set<Instance> processRequest(Instance instance) { @SuppressWarnings("unchecked") Set<Instance> result = (Set<Instance>) instance.getData(FACTORS); if (result == null) { final Instance p = instance.getParent(); FactorExpression fc0 = null; if (p != null) { fc0 = (FactorExpression) p.getData(FactorExpression.class); if (fc0 == null) { // Construct the parent's factor and store it fc0 = new FactorExpression(null, p.getFullExpression()); p.setData(FactorExpression.class, fc0); } } final FactorExpression fc = new FactorExpression(fc0, instance.getExpression()); instance.setData(FactorExpression.class, fc); result = new HashSet<Instance>(); for (Expression e : fc.getFactors()) { System.out.println("Factorizer computes instance for :" + e); final Instance i = new Instance(getSolver(), instance.getSource(), null, e); result.add(i); } result = Collections.unmodifiableSet(result); instance.setData(FACTORS, result); instance.setData(FACTORS_UNSOLVED, new HashSet<Instance>(result)); instance.setData(MODELS, new HashMap<Variable,Object>()); System.out.println("Factorize exiting with " + result.size() + " results"); constraintCount += 1; factorCount += fc.getNumFactors(); } return result; } @SuppressWarnings("unchecked") @Override public Object childDone(Instance instance, Service subservice, Instance subinstance, Object result) { HashSet<Instance> unsolved = (HashSet<Instance>) instance.getData(FACTORS_UNSOLVED); if (unsolved.contains(subinstance)) { // new child finished HashMap<Variable,Object> parent_solutions = (HashMap<Variable,Object>) instance.getData(MODELS); parent_solutions.putAll((HashMap<Variable,Object>)result); instance.setData(MODELS, parent_solutions); // Remove the subinstance now that it is solved unsolved.remove(subinstance); instance.setData(FACTORS_UNSOLVED, unsolved); // Return true of no more unsolved factors; else return null to carry on the computation return (unsolved.isEmpty()) ? parent_solutions : null; } else { // We have already solved this subinstance; return null to carry on the computation return null; } } @Override public void report(Reporter reporter) { reporter.report(getClass().getSimpleName(), "invocations = " + invocationCount); reporter.report(getClass().getSimpleName(), "totalConstraints = " + constraintCount); reporter.report(getClass().getSimpleName(), "factoredConstraints = " + factorCount); } }
lgpl-3.0
Agem-Bilisim/arya
arya-metadata-persistence/src/test/java/tr/com/agem/AppTest.java
639
package tr.com.agem; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AppTest.class ); } /** * Rigourous Test :-) */ public void testApp() { assertTrue( true ); } }
lgpl-3.0
zakski/project-soisceal
2p-mvn/tuProlog-3.2.1-mvn/src/alice/tuprolog/BuiltIn.java
19659
/* * tuProlog - Copyright (C) 2001-2007 aliCE team at deis.unibo.it * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package alice.tuprolog; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; /** * Library of built-in predicates * * @author Alex Benini */ public class BuiltIn extends Library { private static final long serialVersionUID = 1L; private EngineManager engineManager; private TheoryManager theoryManager; private LibraryManager libraryManager; private FlagManager flagManager; private PrimitiveManager primitiveManager; private OperatorManager operatorManager; public BuiltIn(Prolog mediator) { super(); setEngine(mediator); engineManager = mediator.getEngineManager(); theoryManager = mediator.getTheoryManager(); libraryManager = mediator.getLibraryManager(); flagManager = mediator.getFlagManager(); primitiveManager = mediator.getPrimitiveManager(); operatorManager = mediator.getOperatorManager(); } /** * Defines some synonyms */ public String[][] getSynonymMap() { return new String[][] { { "!", "cut", "predicate" }, { "=", "unify", "predicate" }, { "\\=", "deunify", "predicate" }, { ",", "comma", "predicate" }, { "op", "$op", "predicate" }, { "solve", "initialization", "directive" }, { "consult", "include", "directive" }, { "load_library", "$load_library", "directive" } }; } /* * PREDICATES */ public boolean fail_0() { return false; } public boolean true_0() { return true; } public boolean halt_0() { System.exit(0); return true; } public boolean cut_0() { engineManager.cut(); return true; } public boolean asserta_1(Term arg0) throws PrologError { arg0 = arg0.getTerm(); if (arg0 instanceof Struct ) { if (((Struct) arg0).getName().equals(":-")) { for(int i=0; i<(((Struct) arg0).toList().listSize())-1; i++) { Term argi=((Struct) arg0).getArg(i); if (!(argi instanceof Struct) ) { if (argi instanceof Var) throw PrologError.instantiation_error(engineManager, 1); else throw PrologError.type_error(engineManager, 1, "clause", arg0); } } } theoryManager.assertA((Struct) arg0, true, null, false); return true; } if (arg0 instanceof Var) throw PrologError.instantiation_error(engineManager, 1); else throw PrologError.type_error(engineManager, 1, "clause", arg0); } public boolean assertz_1(Term arg0) throws PrologError { arg0 = arg0.getTerm(); if (arg0 instanceof Struct) { if (((Struct) arg0).getName().equals(":-")) { for(int i=0; i<(((Struct) arg0).toList().listSize())-1; i++) { Term argi=((Struct) arg0).getArg(i); if (!(argi instanceof Struct) ) { if (argi instanceof Var) throw PrologError.instantiation_error(engineManager, 1); else throw PrologError.type_error(engineManager, 1, "clause", arg0); } } } theoryManager.assertZ((Struct) arg0, true, null, false); return true; } if (arg0 instanceof Var) throw PrologError.instantiation_error(engineManager, 1); else throw PrologError.type_error(engineManager, 1, "clause", arg0); } public boolean $retract_1(Term arg0) throws PrologError { arg0 = arg0.getTerm(); if (!(arg0 instanceof Struct)) { if (arg0 instanceof Var) throw PrologError.instantiation_error(engineManager, 1); else throw PrologError.type_error(engineManager, 1, "clause", arg0); } Struct sarg0 = (Struct) arg0; ClauseInfo c = theoryManager.retract(sarg0); // if clause to retract found -> retract + true if (c != null) { Struct clause = null; if (!sarg0.isClause()) { clause = new Struct(":-", arg0, new Struct("true")); } else { clause = sarg0; } unify(clause, c.getClause()); return true; } return false; } public boolean abolish_1(Term arg0) throws PrologError { arg0 = arg0.getTerm(); if (arg0 instanceof Var) throw PrologError.instantiation_error(engineManager, 1); if (!(arg0 instanceof Struct) || !arg0.isGround()) throw PrologError.type_error(engineManager, 1, "predicate_indicator", arg0); if( ((Struct)arg0).getArg(0).toString().equals("abolish") ) throw PrologError.permission_error(engineManager, "modify", "static_procedure", arg0, new Struct("")); return theoryManager.abolish((Struct) arg0); } /*Castagna 06/2011*/ /* public boolean halt_1(Term arg0) throws HaltException, PrologError { if (arg0 instanceof Int) throw new HaltException(((Int) arg0).intValue()); if (arg0 instanceof Var) throw PrologError.instantiation_error(engineManager, 1); else { throw PrologError.type_error(engineManager, 1, "integer", arg0); } } */ public boolean halt_1(Term arg0) throws PrologError { if (arg0 instanceof Int) System.exit(((Int) arg0).intValue()); if (arg0 instanceof Var) throw PrologError.instantiation_error(engineManager, 1); else { throw PrologError.type_error(engineManager, 1, "integer", arg0); } } /**/ /* * loads a tuprolog library, given its java class name */ public boolean load_library_1(Term arg0) throws PrologError { arg0 = arg0.getTerm(); if (!arg0.isAtom()) { if (arg0 instanceof Var) throw PrologError.instantiation_error(engineManager, 1); else throw PrologError.type_error(engineManager, 1, "atom", arg0); } try { libraryManager.loadLibrary(((Struct) arg0).getName()); return true; } catch (Exception ex) { throw PrologError.existence_error(engineManager, 1, "class", arg0, new Struct(ex.getMessage())); } } /* * loads a tuprolog library, given its java class name and the list of the paths where may be contained */ public boolean load_library_2(Term arg0, Term arg1) throws PrologError { arg0 = arg0.getTerm(); arg1 = arg1.getTerm(); if (!arg0.isAtom()) { if (arg0 instanceof Var) throw PrologError.instantiation_error(engineManager, 1); else throw PrologError.type_error(engineManager, 1, "atom", arg0); } if(!arg1.isList()) { throw PrologError.type_error(engineManager, 2, "list", arg1); } try { String[] paths = getStringArrayFromStruct((Struct) arg1); if(paths == null || paths.length == 0) throw PrologError.existence_error(engineManager, 2, "paths", arg1, new Struct("Invalid paths' list.")); libraryManager.loadLibrary(((Struct) arg0).getName(), paths); return true; } catch (Exception ex) { throw PrologError.existence_error(engineManager, 1, "class", arg0, new Struct(ex.getMessage())); } } private String[] getStringArrayFromStruct(Struct list) { String args[] = new String[list.listSize()]; Iterator<? extends Term> it = list.listIterator(); int count = 0; while (it.hasNext()) { String path = alice.util.Tools.removeApices(it.next().toString()); args[count++] = path; } return args; } /* * unloads a tuprolog library, given its java class name */ public boolean unload_library_1(Term arg0) throws PrologError { arg0 = arg0.getTerm(); if (!arg0.isAtom()) { if (arg0 instanceof Var) throw PrologError.instantiation_error(engineManager, 1); else throw PrologError.type_error(engineManager, 1, "atom", arg0); } try { libraryManager.unloadLibrary(((Struct) arg0).getName()); return true; } catch (Exception ex) { throw PrologError.existence_error(engineManager, 1, "class", arg0, new Struct(ex.getMessage())); } } /* * get flag list: flag_list(-List) */ public boolean flag_list_1(Term arg0) { arg0 = arg0.getTerm(); Struct flist = flagManager.getPrologFlagList(); return unify(arg0, flist); } public boolean comma_2(Term arg0, Term arg1) { arg0 = arg0.getTerm(); arg1 = arg1.getTerm(); Struct s = new Struct(",", arg0, arg1); engineManager.pushSubGoal(ClauseInfo.extractBody(s)); return true; } /** * It is the same as call/1, but it is not opaque to cut. * * @throws PrologError */ public boolean $call_1(Term goal) throws PrologError { goal = goal.getTerm(); if (goal instanceof Var) throw PrologError.instantiation_error(engineManager, 1); if (!isCallable(goal)) throw PrologError.type_error(engineManager, 1, "callable", goal); goal = convertTermToGoal(goal); if (goal == null) throw PrologError.type_error(engineManager, 1, "callable", goal); engineManager.identify(goal); engineManager.pushSubGoal(ClauseInfo.extractBody(goal)); return true; } /** * Convert a term to a goal before executing it by means of call/1. See * section 7.6.2 of the ISO Standard for details. * <ul> * <li>If T is a variable then G is the control construct call, whose * argument is T.</li> * <li>If the principal functor of T is t ,?/2 or ;/2 or ->/2, then each * argument of T shall also be converted to a goal.</li> * <li>If T is an atom or compound term with principal functor FT, then G is * a predication whose predicate indicator is FT, and the arguments, if any, * of T and G are identical.</li> * </ul> * Note that a variable X and a term call(X) are converted to identical * bodies. Also note that if T is a number, then there is no goal which * corresponds to T. */ static Term convertTermToGoal(Term term) { if (term instanceof Number) return null; if(term instanceof Var && ((Var)term).getLink() instanceof Number) return null; term = term.getTerm(); if (term instanceof Var) return new Struct("call", term); if (term instanceof Struct) { Struct s = (Struct) term; String pi = s.getPredicateIndicator(); if (pi.equals(";/2") || pi.equals(",/2") || pi.equals("->/2")) { for (int i = 0; i < s.getArity(); i++) { Term t = s.getArg(i); Term arg = convertTermToGoal(t); if (arg == null) return null; s.setArg(i, arg); } } } return term; } /** * A callable term is an atom of a compound term. See the ISO Standard * definition in section 3.24. */ private boolean isCallable(Term goal) { return (goal.isAtom() || goal.isCompound()); } private void handleError(Throwable t) throws PrologError { // errore durante la valutazione if (t instanceof ArithmeticException) { ArithmeticException cause = (ArithmeticException) t; // System.out.println(cause.getMessage()); if (cause.getMessage().equals("/ by zero")) throw PrologError.evaluation_error(engineManager, 2, "zero_divisor"); } } public boolean is_2(Term arg0, Term arg1) throws PrologError { if (arg1.getTerm() instanceof Var) throw PrologError.instantiation_error(engineManager, 2); Term val1 = null; try { val1 = evalExpression(arg1); } catch (Throwable t) { handleError(t); } if (val1 == null) throw PrologError.type_error(engineManager, 2, "evaluable", arg1.getTerm()); else return unify(arg0.getTerm(), val1); } public boolean unify_2(Term arg0, Term arg1) { return unify(arg0, arg1); } // \= public boolean deunify_2(Term arg0, Term arg1) { return !unify(arg0, arg1); } // $tolist public boolean $tolist_2(Term arg0, Term arg1) throws PrologError { // transform arg0 to a list, unify it with arg1 arg0 = arg0.getTerm(); arg1 = arg1.getTerm(); if (arg0 instanceof Var) throw PrologError.instantiation_error(engineManager, 1); if (arg0 instanceof Struct) { Term val0 = ((Struct) arg0).toList(); return (val0 != null && unify(arg1, val0)); } throw PrologError.type_error(engineManager, 1, "struct", arg0); } // $fromlist public boolean $fromlist_2(Term arg0, Term arg1) throws PrologError { // get the compound representation of the list // provided as arg1, and unify it with arg0 arg0 = arg0.getTerm(); arg1 = arg1.getTerm(); if (arg1 instanceof Var) throw PrologError.instantiation_error(engineManager, 2); if (!arg1.isList()) { throw PrologError.type_error(engineManager, 2, "list", arg1); } Term val1 = ((Struct) arg1).fromList(); if (val1 == null) //throw PrologError.type_error(engineManager, 2, "list", arg1); return false; return (unify(arg0, val1)); } public boolean copy_term_2(Term arg0, Term arg1) { // unify arg1 with a renamed copy of arg0 arg0 = arg0.getTerm(); arg1 = arg1.getTerm(); int id = engineManager.getEnv().nDemoSteps; return unify(arg1, arg0.copy(new IdentityHashMap<Var,Var>(), id)); } // $append public boolean $append_2(Term arg0, Term arg1) throws PrologError { // append arg0 to arg1 arg0 = arg0.getTerm(); arg1 = arg1.getTerm(); if (arg1 instanceof Var) throw PrologError.instantiation_error(engineManager, 2); if (!arg1.isList()) { throw PrologError.type_error(engineManager, 2, "list", arg1); } ((Struct) arg1).append(arg0); return true; } // $find public boolean $find_2(Term arg0, Term arg1) throws PrologError { // look for clauses whose head unifies whith arg0 and enqueue them to // list arg1 arg0 = arg0.getTerm(); arg1 = arg1.getTerm(); if (arg0 instanceof Var) throw PrologError.instantiation_error(engineManager, 1); if (/* !arg0 instanceof Struct || */!arg1.isList()) throw PrologError.type_error(engineManager, 2, "list", arg1); List<ClauseInfo> l = null; try { l = theoryManager.find(arg0); } catch (RuntimeException e) { } java.util.Iterator<ClauseInfo> it = l.iterator(); while (it.hasNext()) { ClauseInfo b = (ClauseInfo) it.next(); if (match(arg0, b.getHead())) { b.getClause().resolveTerm(); ((Struct) arg1).append(b.getClause()); } } return true; } // set_prolog_flag(+Name,@Value) public boolean set_prolog_flag_2(Term arg0, Term arg1) throws PrologError { arg0 = arg0.getTerm(); arg1 = arg1.getTerm(); if (arg0 instanceof Var) throw PrologError.instantiation_error(engineManager, 1); if (arg1 instanceof Var) throw PrologError.instantiation_error(engineManager, 2); if ((!arg0.isAtom() && !(arg0 instanceof Struct))) throw PrologError.type_error(engineManager, 1, "struct", arg0); if (!arg1.isGround()) throw PrologError.type_error(engineManager, 2, "ground", arg1); String name = arg0.toString(); if (flagManager.getFlag(name) == null) throw PrologError.domain_error(engineManager, 1, "prolog_flag",arg0); if (!flagManager.isValidValue(name, arg1)) throw PrologError.domain_error(engineManager, 2, "flag_value", arg1); if (!flagManager.isModifiable(name)) throw PrologError.permission_error(engineManager, "modify", "flag", arg0, new Int(0)); return flagManager.setFlag(name, arg1); } // get_prolog_flag(@Name,?Value) public boolean get_prolog_flag_2(Term arg0, Term arg1) throws PrologError { arg0 = arg0.getTerm(); arg1 = arg1.getTerm(); if (arg0 instanceof Var) throw PrologError.instantiation_error(engineManager, 1); if (!arg0.isAtom() && !(arg0 instanceof Struct)) { throw PrologError.type_error(engineManager, 1, "struct", arg0); } String name = arg0.toString(); Term value = flagManager.getFlag(name); if (value == null) throw PrologError.domain_error(engineManager, 1, "prolog_flag", arg0); return unify(value, arg1); } public boolean $op_3(Term arg0, Term arg1, Term arg2) throws PrologError { arg0 = arg0.getTerm(); arg1 = arg1.getTerm(); arg2 = arg2.getTerm(); if (arg0 instanceof Var) throw PrologError.instantiation_error(engineManager, 1); if (arg1 instanceof Var) throw PrologError.instantiation_error(engineManager, 2); if (arg2 instanceof Var) throw PrologError.instantiation_error(engineManager, 3); if (!(arg0 instanceof Int)) throw PrologError.type_error(engineManager, 1, "integer", arg0); if (!arg1.isAtom()) throw PrologError.type_error(engineManager, 2, "atom", arg1); if (!arg2.isAtom() && !arg2.isList()) throw PrologError.type_error(engineManager, 3, "atom_or_atom_list", arg2); int priority = ((Int) arg0).intValue(); if (priority < OperatorManager.OP_LOW || priority > OperatorManager.OP_HIGH) throw PrologError.domain_error(engineManager, 1, "operator_priority", arg0); String specifier = ((Struct) arg1).getName(); if (!specifier.equals("fx") && !specifier.equals("fy") && !specifier.equals("xf") && !specifier.equals("yf") && !specifier.equals("xfx") && !specifier.equals("yfx") && !specifier.equals("xfy")) throw PrologError.domain_error(engineManager, 2, "operator_specifier", arg1); if (arg2.isList()) { for (Iterator<? extends Term> operators = ((Struct) arg2).listIterator(); operators .hasNext();) { Struct operator = (Struct) operators.next(); operatorManager.opNew(operator.getName(), specifier, priority); } } else operatorManager.opNew(((Struct) arg2).getName(), specifier, priority); return true; } /* * DIRECTIVES */ public void op_3(Term arg0, Term arg1, Term arg2) throws PrologError { $op_3(arg0, arg1, arg2); } public void flag_4(Term flagName, Term flagSet, Term flagDefault, Term flagModifiable) { flagName = flagName.getTerm(); flagSet = flagSet.getTerm(); flagDefault = flagDefault.getTerm(); flagModifiable = flagModifiable.getTerm(); if (flagSet.isList() && (flagModifiable.equals(Term.TRUE) || flagModifiable .equals(Term.FALSE))) { // TODO libName che futuro deve avere?? -------------------- String libName = ""; // ------------ flagManager.defineFlag(flagName.toString(), (Struct) flagSet, flagDefault, flagModifiable.equals(Term.TRUE), libName); } } public void initialization_1(Term goal) { goal = goal.getTerm(); if (goal instanceof Struct) { primitiveManager.identifyPredicate(goal); theoryManager.addStartGoal((Struct) goal); } } public void $load_library_1(Term lib) throws InvalidLibraryException { lib = lib.getTerm(); if (lib.isAtom()) libraryManager.loadLibrary(((Struct) lib).getName()); } public void include_1(Term theory) throws FileNotFoundException, InvalidTheoryException, IOException { theory = theory.getTerm(); String path = alice.util.Tools.removeApices(theory.toString()); if(! new File(path).isAbsolute()) { path = engine.getCurrentDirectory() + File.separator + path; } engine.pushDirectoryToList(new File(path).getParent()); engine.addTheory(new Theory(new FileInputStream(path))); engine.popDirectoryFromList(); } }
lgpl-3.0
octopus-platform/joern
projects/extensions/joern-fuzzyc/src/main/java/ddg/DefUseCFG/ReadWriteDbFactory.java
3360
package ddg.DefUseCFG; import java.util.Collection; import java.util.List; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.index.IndexHits; import databaseNodes.EdgeTypes; import misc.Pair; import neo4j.readWriteDB.Neo4JDBInterface; import neo4j.traversals.readWriteDB.Traversals; public class ReadWriteDbFactory extends DefUseCFGFactory { DefUseCFG cfg; List<String> parameters; @Override public DefUseCFG create(Long funcId) { cfg = new DefUseCFG(); getStatementsOfFunction(funcId); getUsesAndDefs(); getParentBlocks(); getChildBlocks(); getExitNode(funcId); getParameters(funcId); cfg.addUsesForExitNode(); return cfg; } private void getParameters(Long funcId) { String query = "type:Parameter AND functionId:" + funcId; IndexHits<Node> hits = Neo4JDBInterface.queryIndex(query); for (Node node : hits) { Collection<Object> params = cfg.getSymbolsDefinedBy(node.getId()); for (Object o : params) { cfg.addParameter((String) o); } } } private void getExitNode(Long funcId) { String query = "type:CFGExitNode AND functionId:" + funcId; IndexHits<Node> hits = Neo4JDBInterface.queryIndex(query); for (Node node : hits) { cfg.setExitNode(node.getId()); } } private void getStatementsOfFunction(Long funcId) { String query = "isCFGNode:True AND functionId:" + funcId; IndexHits<Node> hits = Neo4JDBInterface.queryIndex(query); for (Node node : hits) cfg.addStatement(node.getId()); } private void getUsesAndDefs() { for (Object obj : cfg.getStatements()) { Long statementId = (Long) obj; List<Pair<Long, String>> used = Traversals .getSymbolsUsedByStatement(statementId); for (Pair<Long, String> symbolIdAndCode : used) { Long symbolId = symbolIdAndCode.getL(); String symbolCode = symbolIdAndCode.getR(); cfg.addSymbolUsed(statementId, symbolCode); cfg.setSetSymbolId(symbolCode, symbolId); } List<Pair<Long, String>> defined = Traversals .getSymbolsDefinedByStatement(statementId); for (Pair<Long, String> symbolIdAndCode : defined) { Long symbolId = symbolIdAndCode.getL(); String symbolCode = symbolIdAndCode.getR(); cfg.addSymbolDefined(statementId, symbolCode); cfg.setSetSymbolId(symbolCode, symbolId); } } } private void getParentBlocks() { for (Object obj : cfg.getStatements()) { Long statementId = (Long) obj; Node statement = Neo4JDBInterface.getNodeById(statementId); Iterable<Relationship> rels = statement .getRelationships(Direction.INCOMING); for (Relationship rel : rels) { if (!rel.getType().name().toString().equals(EdgeTypes.FLOWS_TO)) continue; long parentId = rel.getStartNode().getId(); cfg.addParentBlock(statementId, parentId); } } } private void getChildBlocks() { for (Object obj : cfg.getStatements()) { Long statementId = (Long) obj; Node statement = Neo4JDBInterface.getNodeById(statementId); Iterable<Relationship> rels = statement .getRelationships(Direction.OUTGOING); for (Relationship rel : rels) { if (!rel.getType().name().toString().equals(EdgeTypes.FLOWS_TO)) continue; long childId = rel.getEndNode().getId(); cfg.addChildBlock(statementId, childId); } } } }
lgpl-3.0
ZalemSoftware/Ymir
ymir.client-android.commons/src/main/java/br/com/zalem/ymir/client/android/widget/SquareLayout.java
4053
package br.com.zalem.ymir.client.android.widget; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.View; import android.widget.FrameLayout; import br.com.zalem.ymir.client.android.commons.R; /** * SquareLayout é uma extensão de {@link android.widget.FrameLayout} que obrigatoriamente terá medidas quadradas, ou seja, * a largura e a altura sempre serão iguais. Funciona a partir de uma <code>medida base</code> (largura ou altura), * sendo que o valor correspondente da medida base será refletido para a outra medida no momento do <code>layout</code>. * A configuração da <code>medida base</code> pode ser feita através do atributo de xml <code>baseMeasure</code> * ou através do método {@link #setBaseMeasure(br.com.zalem.ymir.client.android.widget.SquareLayout.Measure)}. * * @author Thiago Gesser */ public final class SquareLayout extends FrameLayout { public enum Measure {WIDTH, HEIGHT} private Measure baseMeasure; private int minSize = Integer.MAX_VALUE; private boolean remeasureNeeded; public SquareLayout(Context context) { super(context); } public SquareLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public SquareLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SquareLayout); try { int bmInt = a.getInteger(R.styleable.SquareLayout_baseMeasure, Measure.HEIGHT.ordinal()); if (bmInt < 0 || bmInt >= Measure.values().length) { throw new IllegalArgumentException("Invalid baseMeasure: " + bmInt); } baseMeasure = Measure.values()[bmInt]; } finally { a.recycle(); } } public void setBaseMeasure(Measure baseMeasure) { if (baseMeasure == null) { throw new NullPointerException("baseMeasure == null"); } this.baseMeasure = baseMeasure; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { //Utiliza a medida base configurada para determinar o tamanho do quadrado. int baseMeasureSize; int otherMeasureSize; switch (baseMeasure) { case WIDTH: baseMeasureSize = MeasureSpec.getSize(widthMeasureSpec); otherMeasureSize = MeasureSpec.getSize(heightMeasureSpec); break; case HEIGHT: baseMeasureSize = MeasureSpec.getSize(heightMeasureSpec); otherMeasureSize = MeasureSpec.getSize(widthMeasureSpec); break; default: throw new RuntimeException("Unsupported Measure: " + baseMeasure); } //Só é necessário remensurar se este layout tentar ocupar um espaço diferente do tamanho disponível para ele. remeasureNeeded = baseMeasureSize != otherMeasureSize; //TODO rever esta lógica. Ela foi necessária pq a aparição do teclado virtual na tela de detalhes (filtro) fazia com //que o layout do cabeçalho ficasse perdido. if (baseMeasureSize > 0 && baseMeasureSize < minSize) { minSize = baseMeasureSize; } super.onMeasure(MeasureSpec.makeMeasureSpec(minSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(minSize, MeasureSpec.EXACTLY)); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { if (remeasureNeeded) { View parent = (View) getParent(); if (parent != null) { //Se o layout acabou ocupando mais do que o tamanho disponível para ficar poder ficar quadrado, é obrigado a //remensurar o pai, se não há o risto de uma View irmã ficará com o tamanho / posicionamento errado. int widthMeasureSpec = MeasureSpec.makeMeasureSpec(parent.getMeasuredWidth(), MeasureSpec.EXACTLY); int heightMeasureSpec = MeasureSpec.makeMeasureSpec(parent.getMeasuredHeight(), MeasureSpec.EXACTLY); parent.measure(widthMeasureSpec, heightMeasureSpec); } remeasureNeeded = false; } super.onLayout(changed, left, top, right, bottom); } }
lgpl-3.0
HisenseUSA/Cling-1.0.5
support/src/main/java/org/teleal/cling/support/igd/callback/GetStatusInfo.java
2339
/* * Copyright (C) 2010 Teleal GmbH, Switzerland * * This program 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 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.teleal.cling.support.igd.callback; import org.teleal.cling.controlpoint.ActionCallback; import org.teleal.cling.model.action.ActionException; import org.teleal.cling.model.action.ActionInvocation; import org.teleal.cling.model.meta.Service; import org.teleal.cling.model.types.ErrorCode; import org.teleal.cling.model.types.UnsignedIntegerFourBytes; import org.teleal.cling.support.model.Connection; /** * @author Christian Bauer */ public abstract class GetStatusInfo extends ActionCallback { public GetStatusInfo(Service service) { super(new ActionInvocation(service.getAction("GetStatusInfo"))); } @Override public void success(ActionInvocation invocation) { try { Connection.Status status = Connection.Status.valueOf(invocation.getOutput("NewConnectionStatus").getValue().toString()); Connection.Error lastError = Connection.Error.valueOf(invocation.getOutput("NewLastConnectionError").getValue().toString()); success(new Connection.StatusInfo(status, (UnsignedIntegerFourBytes) invocation.getOutput("NewUptime").getValue(), lastError)); } catch (Exception ex) { invocation.setFailure( new ActionException( ErrorCode.ARGUMENT_VALUE_INVALID, "Invalid status or last error string: " + ex, ex ) ); failure(invocation, null); } } protected abstract void success(Connection.StatusInfo statusInfo); }
lgpl-3.0
kyungtaekLIM/PSI-BLASTexB
src/ncbi-blast-2.5.0+/c++/src/build-system/project_tree_builder_gui/src/ptbgui/PtbguiMain.java
94823
/* $Id: PtbguiMain.java 446504 2014-09-16 14:46:53Z gouriano $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Andrei Gourianov * * File Description: * GUI application that works with project_tree_builder * NCBI C++ Toolkit */ package ptbgui; import java.awt.*; import java.io.*; import java.util.*; import javax.swing.*; import javax.swing.text.JTextComponent; public class PtbguiMain extends javax.swing.JFrame { private static final long serialVersionUID = 1L; private String[] m_OriginalArgs; private ArgsParser m_ArgsParser; private Properties m_ArgsProp; private Process m_Ptb; private BufferedReader m_PtbOut; private BufferedReader m_PtbErr; private OutputStream m_PtbIn; private String m_Params, m_TmpParams; private String m_Key3root, m_KeyCpath; private Map<String, String[]> m_ProjectTags; private SortedSet<String> m_UndefSelTags; private Vector<String> m_KnownTags; private Vector<String> m_CompositeTags; private KTagsDialog m_KtagsDlg; enum eState { beforePtb, got3rdparty, gotProjects, donePtb } private eState m_State; /** Creates new form PtbguiMain */ public PtbguiMain() { initComponents(); initObjects(); resetState(); } private void initObjects() { m_ArgsParser = new ArgsParser(); m_ProjectTags = new HashMap<String, String[]>(); m_UndefSelTags = new TreeSet<String>(); m_KnownTags = new Vector<String>(); m_CompositeTags = new Vector<String>(); ButtonGroup group = new ButtonGroup(); group.add(jRadioButtonStatic); group.add(jRadioButtonDLL); initCheckList(jListApps); initCheckList(jListLibs); initCheckList(jListOther); initCheckList(jListTags); initCheckList(jListUserReq); } private void resetState() { jTabbedPane.setSelectedIndex(0); jTabbedPane.setEnabledAt(0,true); jTabbedPane.setEnabledAt(1,true); jTabbedPane.setEnabledAt(2,false); jTabbedPane.setEnabledAt(3,false); jTabbedPane.setEnabledAt(4,false); m_State = eState.beforePtb; jButtonGOK.setText("Next"); jButtonGOK.setEnabled(true); jButtonGOK.setVisible(true); jButtonGCancel.setText("Cancel"); jButtonGCancel.setEnabled(true); jButtonGCancel.setVisible(true); ((DefaultListModel)jListApps.getModel()).clear(); ((DefaultListModel)jListLibs.getModel()).clear(); ((DefaultListModel)jListOther.getModel()).clear(); ((DefaultListModel)jListTags.getModel()).clear(); ((DefaultListModel)jListUserReq.getModel()).clear(); showMoreAdvanced(false); } private void showMoreAdvanced(boolean show) { jCheckBoxNoPtb.setVisible(show); jCheckBoxNws.setVisible(show); jCheckBoxExt.setVisible(show); jLabel1.setVisible(show); jLabel2.setVisible(show); jTextFieldPtb.setVisible(show); jTextFieldRoot.setVisible(show); jButtonPtb.setVisible(show); jButtonMore.setText(show ? "< less" : "more >"); } private void initData() { initData(m_OriginalArgs); } private void initData(String args[]) { if (m_OriginalArgs == null) { m_OriginalArgs = new String[args.length]; for (int i=0; i<args.length; ++i) { m_OriginalArgs[i] = args[i]; } } m_ArgsParser.init(args); setPathText(jTextFieldPtb, m_ArgsParser.getPtb(), true); setPathText(jTextFieldRoot, m_ArgsParser.getRoot(), true); setPathText(jTextFieldLst, m_ArgsParser.getRoot(), m_ArgsParser.getSubtree()); setPathText(jTextFieldSolution, m_ArgsParser.getSolutionFile(), false); jTextFieldTags.setToolTipText( "Expression. For example: (core || web) && !test"); jTextFieldLstTags.setToolTipText( "When 'Use project tags' field above is empty, default tags will be used"); if (m_ArgsParser.getArgsFile().length() > 0) { initData(m_ArgsParser.getArgsFile(), true); return; } jTextFieldTags.setText(m_ArgsParser.getProjTag()); jTextFieldLstTags.setText(""); jTextFieldIde.setText(m_ArgsParser.getIde()); String arch = m_ArgsParser.getArch(); jTextFieldArch.setText(arch); if (arch.equals("Win32") || arch.equals("x64")) { jTextFieldArch.setToolTipText("Win32 or x64"); } jRadioButtonDLL.setSelected(m_ArgsParser.getDll()); jRadioButtonStatic.setSelected(!m_ArgsParser.getDll()); jCheckBoxNoPtb.setSelected(m_ArgsParser.m_nobuildptb); jCheckBoxNws.setSelected(m_ArgsParser.m_nws); jCheckBoxExt.setSelected(m_ArgsParser.m_ext); jTextFieldExt.setText(m_ArgsParser.getExtRoot()); jLabelArgs.setText(" "); jButtonArgsReset.setEnabled(false); if (m_ArgsProp != null) { m_ArgsProp.clear(); } // jRadioButtonDLL.setEnabled(false); // jRadioButtonStatic.setEnabled(false); adjustArch(); initKnownTags(); initTagsFromSubtree(); } private void adjustArch() { File build_root = new File(m_ArgsParser.getBuildRoot()); File[] arrFile = build_root.listFiles( new FilenameFilter() { public boolean accept(File dir, String name) { return (name.toLowerCase().matches("__configured_platform.*")); } }); jTextFieldArch.setEditable(arrFile == null || arrFile.length==0); } private void adjustBuildType() { m_ArgsParser.setDll( jRadioButtonDLL.isSelected(),true); setPathText(jTextFieldSolution, m_ArgsParser.getSolutionFile(), false); } private void initData(String file, Boolean fromArgs) { try { if (m_ArgsProp != null) { m_ArgsProp.clear(); } else { m_ArgsProp = new Properties(); } m_ArgsProp.load(new FileInputStream(new File(file))); initData(m_ArgsProp, fromArgs); jLabelArgs.setText(file); jButtonArgsReset.setEnabled(!fromArgs); } catch (Exception e) { System.err.println(e.toString()); e.printStackTrace(); JOptionPane.showMessageDialog( this, "This file does not contain valid data", "Error", JOptionPane.ERROR_MESSAGE); } } private void initData(Properties prop, Boolean fromArgs) { String v; if (fromArgs) { v = m_ArgsParser.getRoot(); } else { v = getProp(prop,"__arg_root"); setPathText(jTextFieldRoot, getProp(prop,"__arg_root"), true); setPathText(jTextFieldSolution, getProp(prop,"__arg_solution"), false); } setPathText(jTextFieldLst, v, getProp(prop,"__arg_subtree")); jTextFieldTags.setText(getProp(prop,"__arg_projtag")); jTextFieldLstTags.setText(""); jTextFieldIde.setText(getProp(prop,"__arg_ide")); jTextFieldArch.setText(getProp(prop,"__arg_arch")); jRadioButtonDLL.setSelected(getProp(prop,"__arg_dll").equals("yes")); jRadioButtonStatic.setSelected(!jRadioButtonDLL.isSelected()); jCheckBoxNoPtb.setSelected(getProp(prop,"__arg_nobuildptb").equals("yes")); jCheckBoxNws.setSelected(getProp(prop,"__arg_nws").equals("yes")); jCheckBoxExt.setSelected(getProp(prop,"__arg_ext").equals("yes")); jTextFieldExt.setText(getProp(prop,"__arg_extroot")); adjustArch(); initKnownTags(); initTagsFromSubtree(); } private void initKnownTags() { String from = jTextFieldRoot.getText()+ "/src/build-system/project_tags.txt"; int n = 0; m_KnownTags.clear(); m_CompositeTags.clear(); if (!ArgsParser.existsPath(from)) { return; } try { BufferedReader r = new BufferedReader(new InputStreamReader( new FileInputStream(new File(nativeFileSeparator(from))))); String line; while ((line = r.readLine()) != null) { if (line.length() == 0 || line.charAt(0) == '#') { continue; } String[] t = line.split("="); if (t.length > 1) { m_CompositeTags.add(line.trim()); continue; } t = line.split("[, ]"); for (int i=0; i<t.length; ++i) { if (t[i].trim().length() != 0) { ++n; m_KnownTags.add(t[i].trim()); } } } } catch (Exception e) { System.err.println(e.toString()); e.printStackTrace(); } } private void initTagsFromSubtree() { jTextFieldLstTags.setText(""); String lst = jTextFieldRoot.getText() + File.separatorChar + jTextFieldLst.getText(); File f = new File(nativeFileSeparator(lst)); if (f.isFile()) { try { BufferedReader r = new BufferedReader(new InputStreamReader( new FileInputStream(f))); String key = "#define TAGS"; String line; while ((line = r.readLine()) != null) { line = line.trim(); if (line.startsWith(key)) { line = line.replaceAll(key,""); line = line.replaceAll("\\[",""); line = line.replaceAll("\\]",""); line = line.trim(); // m_ArgsParser.setProjTagFromLst(line); jTextFieldLstTags.setText(line); break; } } } catch (Exception e) { System.err.println(e.toString()); e.printStackTrace(); } } } private void updateData() { m_ArgsParser.setPtb(jTextFieldPtb.getText()); if (m_ArgsProp != null && !m_ArgsProp.isEmpty()) { setProp(m_ArgsProp, "__arg_root", jTextFieldRoot.getText()); setProp(m_ArgsProp, "__arg_subtree", jTextFieldLst.getText()); setProp(m_ArgsProp, "__arg_solution", jTextFieldSolution.getText()); setProp(m_ArgsProp, "__arg_projtag", jTextFieldTags.getText()); setProp(m_ArgsProp, "__arg_ide", jTextFieldIde.getText()); setProp(m_ArgsProp, "__arg_arch", jTextFieldArch.getText()); setProp(m_ArgsProp, "__arg_dll", jRadioButtonDLL.isSelected()); setProp(m_ArgsProp, "__arg_nobuildptb", jCheckBoxNoPtb.isSelected()); setProp(m_ArgsProp, "__arg_nws", jCheckBoxNws.isSelected()); setProp(m_ArgsProp, "__arg_ext", jCheckBoxExt.isSelected()); setProp(m_ArgsProp, "__arg_extroot", jTextFieldExt.getText()); try { File f = File.createTempFile("PTBconf",".ini"); f.deleteOnExit(); FileOutputStream fout = new FileOutputStream(f); Enumeration props = m_ArgsProp.propertyNames(); while (props.hasMoreElements()) { String key = props.nextElement().toString(); String value = m_ArgsProp.getProperty(key); String line = key + "=" + value + "\n"; fout.write(line.getBytes()); } fout.flush(); fout.close(); m_TmpParams = f.getPath(); } catch (Exception e) { System.err.println(e.toString()); e.printStackTrace(); } m_ArgsParser.setArgsFile(m_TmpParams); } else { m_ArgsParser.setRoot(jTextFieldRoot.getText()); m_ArgsParser.setSubtree(jTextFieldLst.getText()); m_ArgsParser.setSolutionFile(jTextFieldSolution.getText()); m_ArgsParser.setProjTag(jTextFieldTags.getText()); m_ArgsParser.setArch(jTextFieldArch.getText()); m_ArgsParser.setDll(jRadioButtonDLL.isSelected(), false); m_ArgsParser.m_nobuildptb = jCheckBoxNoPtb.isSelected(); m_ArgsParser.m_nws = jCheckBoxNws.isSelected(); m_ArgsParser.m_ext = jCheckBoxExt.isSelected(); m_ArgsParser.setExtRoot(jTextFieldExt.getText()); m_ArgsParser.setArgsFile(null); } } public static String nativeFileSeparator(String s) { return s.replace('/',File.separatorChar); } public static String getProp(Properties prop, String key) { return prop.containsKey(key) ? nativeFileSeparator(prop.getProperty(key).trim()) : ""; } public static String portableFileSeparator(String s) { return s.replace(File.separatorChar,'/'); } public static void setProp(Properties prop, String key, String value) { prop.setProperty(key,portableFileSeparator(value)); } public static void setProp(Properties prop, String key, boolean value) { prop.setProperty(key,value ? "yes" : "no"); } public static boolean copyFile(String from, String to) { boolean res = true; if (!from.equals(to)) { try { InputStream in = new FileInputStream(new File(from)); OutputStream out = new FileOutputStream(new File(to)); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } catch (Exception e) { res = false; System.err.println(e.toString()); e.printStackTrace(); } } return res; } private void setPathText(JTextComponent c, String path, boolean verify) { c.setText(path); if (!verify || ArgsParser.existsPath(path)) { c.setForeground(SystemColor.controlText); c.setToolTipText(""); } else { c.setForeground(Color.red); c.setToolTipText("Path not found"); } } private void setPathText(JTextComponent c, String root, String path) { c.setText(path); if (ArgsParser.existsPath(root + File.separator + path)) { c.setForeground(SystemColor.controlText); c.setToolTipText(""); } else { c.setForeground(Color.red); c.setToolTipText("Path not found"); } } private void processPtbOutput() { String line; while (isPtbRunning()) { try { Thread.sleep(3); while (m_PtbErr != null && m_PtbErr.ready() && (line = m_PtbErr.readLine()) != null) { System.err.println(line); } while (m_PtbOut != null && m_PtbOut.ready() && (line = m_PtbOut.readLine()) != null) { if (line.startsWith("*PTBGUI{* custom")) { processAdditionalParams(); return; } else if (line.startsWith("*PTBGUI{* projects")) { processProjects(); return; } System.out.println(line); } } catch (Exception e) { System.err.println(e.toString()); e.printStackTrace(); } } try { while (m_PtbErr != null && m_PtbErr.ready() && (line = m_PtbErr.readLine()) != null) { System.err.println(line); } while (m_PtbOut != null && m_PtbOut.ready() && (line = m_PtbOut.readLine()) != null) { System.out.println(line); } } catch (Exception e) { System.err.println(e.toString()); e.printStackTrace(); } if (m_State == eState.gotProjects || m_State == eState.got3rdparty) { processDone(m_Ptb.exitValue()); return; } System.exit(m_Ptb != null ? m_Ptb.exitValue() : 1); } private void processAdditionalParams() { m_State = eState.got3rdparty; jButtonGOK.setText("Next"); jButtonGCancel.setEnabled(true); int i = jTabbedPane.indexOfComponent(jPanelAdd); jTabbedPane.setEnabledAt(i,true); jTabbedPane.setSelectedIndex(i); jTextField3root.setText(""); jTextField3root.setEnabled(false); jTextFieldCpath.setText(""); jTextFieldCpath.setEnabled(false); jCheckBoxVTuneR.setEnabled(false); jCheckBoxVTuneR.setVisible(false); jCheckBoxVTuneD.setEnabled(false); jCheckBoxVTuneD.setVisible(false); jCheckBoxVTune.setSelected(false); jCheckBoxVTune.setEnabled(false); jPanelUserReq.setVisible(false); boolean vtune = false; String[] userRequests = new String[0]; String[] enabledRequests = new String[0]; try { String line; while (m_PtbOut != null && /*m_PtbOut.ready() &&*/ (line = m_PtbOut.readLine()) != null) { if (line.startsWith("*PTBGUI}*")) { if (vtune) { jCheckBoxVTune.setEnabled(true); jCheckBoxVTuneR.setEnabled(true); jCheckBoxVTuneD.setEnabled(true); jCheckBoxVTune.setSelected( jCheckBoxVTuneR.isSelected() || jCheckBoxVTuneD.isSelected()); jCheckBoxVTuneD.setVisible(jCheckBoxVTune.isSelected()); jCheckBoxVTuneR.setVisible(jCheckBoxVTune.isSelected()); } if (userRequests.length > 0) { jPanelUserReq.setVisible(true); for (int r=0; r < userRequests.length; ++r) { boolean sel = false; for (int e=0; !sel && e < enabledRequests.length; ++e) { sel = userRequests[r].equals( enabledRequests[e] ); } addProject(jListUserReq, userRequests[r], sel); } } return; } String[] kv = line.split("="); if (kv.length > 1) { String k = kv[0].trim(); String v = kv[1].trim(); if (k.equals("ThirdPartyBasePath") || k.equals("XCode_ThirdPartyBasePath")) { m_Key3root = k; jTextField3root.setEnabled(true); setPathText(jTextField3root,nativeFileSeparator(v),true); } else if (k.equals("ThirdParty_C_ncbi") || k.equals("XCode_ThirdParty_C_ncbi")) { m_KeyCpath = k; jTextFieldCpath.setEnabled(true); setPathText(jTextFieldCpath,nativeFileSeparator(v),true); } else if (k.equals("__TweakVTuneR")) { vtune = true; jCheckBoxVTuneR.setSelected(v.equals("yes")); } else if (k.equals("__TweakVTuneD")) { vtune = true; jCheckBoxVTuneD.setSelected(v.equals("yes")); } else if (k.equals("__UserRequests")) { userRequests = v.split(" "); } else if (k.equals("__EnabledUserRequests")) { enabledRequests = v.split(" "); } } } } catch (Exception e) { System.err.println(e.toString()); e.printStackTrace(); } } private void doneAdditionalParams() { if (isPtbRunning()) { try { String s; s = "*PTBGUI{* custom" + "\n"; m_PtbIn.write(s.getBytes()); if (jTextField3root.isEnabled()) { s = m_Key3root+" = "+jTextField3root.getText()+"\n"; m_PtbIn.write(s.getBytes()); } if (jTextFieldCpath.isEnabled()) { s = m_KeyCpath+" = "+jTextFieldCpath.getText()+"\n"; m_PtbIn.write(s.getBytes()); } String yn = (jCheckBoxVTune.isSelected() && jCheckBoxVTuneR.isSelected()) ? "yes" : "no"; if (jCheckBoxVTuneR.isEnabled()) { s = "__TweakVTuneR"+" = "+ yn +"\n"; m_PtbIn.write(s.getBytes()); } yn = (jCheckBoxVTune.isSelected() && jCheckBoxVTuneD.isSelected()) ? "yes" : "no"; if (jCheckBoxVTuneD.isEnabled()) { s = "__TweakVTuneD"+" = "+ yn +"\n"; m_PtbIn.write(s.getBytes()); } if (jPanelUserReq.isVisible()) { s = "__EnabledUserRequests ="; DefaultListModel model = (DefaultListModel)jListUserReq.getModel(); for (int i =0; i< model.getSize(); ++i) { JCheckBox b = (JCheckBox)model.getElementAt(i); if (b.isSelected()) { s += " " + b.getText(); } } s += "\n"; m_PtbIn.write(s.getBytes()); } s = "*PTBGUI}* custom" + "\n"; m_PtbIn.write(s.getBytes()); m_PtbIn.flush(); } catch (Exception e) { System.err.println(e.toString()); e.printStackTrace(); } } } private void initCheckList(JList list) { list.setModel(new DefaultListModel()); list.setCellRenderer(new CheckListRenderer()); list.addMouseListener(new CheckListMouseAdapter()); list.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jListSelectionChanged(evt); } }); } private void addProject(JList list, String project, boolean selected) { DefaultListModel model = (DefaultListModel)list.getModel(); JCheckBox b = new JCheckBox(); b.setText(project); b.setSelected(selected); model.addElement(b); } private void selectProjects(JList list, boolean select) { DefaultListModel model = (DefaultListModel)list.getModel(); for (int i =0; i< model.getSize(); ++i) { JCheckBox b = (JCheckBox)model.getElementAt(i); b.setSelected(select); } countSelected(); list.repaint(); } private void selectProjects(JList list, Vector<String> selected, Vector<String> unselected) { DefaultListModel model = (DefaultListModel)list.getModel(); for (int i =0; i< model.getSize(); ++i) { JCheckBox b = (JCheckBox)model.getElementAt(i); String prj = b.getText(); if (m_ProjectTags.containsKey(prj)) { String[] tags = m_ProjectTags.get(prj); boolean done = false; for (int t=0; !done && t<tags.length; ++t) { if (unselected.contains(tags[t])) { b.setSelected(false); done = true; } } for (int t=0; !done && t<tags.length; ++t) { if (selected.contains(tags[t])) { b.setSelected(true); done = true; } } } } list.repaint(); } private void checkProjectSelection(JList list, Vector<String> selected, Vector<String> unselected) { DefaultListModel model = (DefaultListModel)list.getModel(); for (int i =0; i< model.getSize(); ++i) { JCheckBox b = (JCheckBox)model.getElementAt(i); String prj = b.getText(); if (m_ProjectTags.containsKey(prj)) { String[] tags = m_ProjectTags.get(prj); boolean hasProhibited = false; for (int t=0; t<tags.length; ++t) { if (unselected.contains(tags[t])) { if (b.isSelected()) { m_UndefSelTags.add(tags[t]); } hasProhibited = true; } } if (!hasProhibited) { for (int t=0; t<tags.length; ++t) { if (selected.contains(tags[t])) { if (!b.isSelected()) { m_UndefSelTags.add(tags[t]); } } } } } } } private int getSelectedCount(JList list) { int count = 0; DefaultListModel model = (DefaultListModel)list.getModel(); for (int i =0; i< model.getSize(); ++i) { JCheckBox b = (JCheckBox)model.getElementAt(i); if (b.isSelected()) { ++count; } } return count; } private void countSelected() { String t = "Applications (" + getSelectedCount(jListApps) + "/" + jListApps.getModel().getSize()+ ")"; jLabelApps.setText(t); t = "Libraries (" + getSelectedCount(jListLibs) + "/" + jListLibs.getModel().getSize()+ ")"; jLabelLibs.setText(t); t = "Other (" + getSelectedCount(jListOther) + "/" + jListOther.getModel().getSize()+ ")"; jLabelOther.setText(t); verifyTagSelection(); } private void verifyTagSelection() { Vector<String> selected = new Vector<String>(); Vector<String> unselected = new Vector<String>(); DefaultListModel model = (DefaultListModel)jListTags.getModel(); for (int i =0; i< model.getSize(); ++i) { JCheckBox b = (JCheckBox)model.getElementAt(i); if (b.isSelected()) { selected.add(b.getText()); } else { unselected.add(b.getText()); } } m_UndefSelTags.clear(); checkProjectSelection(jListApps, selected, unselected); checkProjectSelection(jListLibs, selected, unselected); checkProjectSelection(jListOther, selected, unselected); for (int i =0; i< model.getSize(); ++i) { JCheckBox b = (JCheckBox)model.getElementAt(i); if (m_UndefSelTags.contains(b.getText())) { if (b.isSelected()) { b.setSelected(false); } } } CheckListRenderer r = (CheckListRenderer)(jListTags.getCellRenderer()); r.setUndefinedSelection(m_UndefSelTags); jListTags.repaint(); } private void jListSelectionChanged(java.awt.event.MouseEvent evt) { JList list = (JList) evt.getSource(); if (list == jListTags) { Vector<String> selected = new Vector<String>(); Vector<String> unselected = new Vector<String>(); DefaultListModel model = (DefaultListModel)jListTags.getModel(); int index = jListTags.locationToIndex(evt.getPoint()); JCheckBox item = (JCheckBox)model.getElementAt(index); if (m_UndefSelTags.contains(item.getText()) && !item.isSelected()) { item.setSelected(true); jListTags.repaint(); } if (item.isSelected()) { selected.add(item.getText()); } else { unselected.add(item.getText()); } /* for (int i =0; i< model.getSize(); ++i) { JCheckBox b = (JCheckBox)model.getElementAt(i); if (b.isSelected()) { selected.add(b.getText()); } else { unselected.add(b.getText()); } } */ selectProjects(jListApps, selected, unselected); selectProjects(jListLibs, selected, unselected); selectProjects(jListOther, selected, unselected); } countSelected(); } private void writeSelected(JList list, OutputStream out) { DefaultListModel model = (DefaultListModel)list.getModel(); for (int i =0; i< model.getSize(); ++i) { JCheckBox b = (JCheckBox)model.getElementAt(i); if (b.isSelected()) { try { String s = b.getText() + "\n"; out.write(s.getBytes()); } catch (Exception e) { System.err.println(e.toString()); e.printStackTrace(); } } } } private void processProjects() { m_State = eState.gotProjects; jButtonGOK.setText("Generate project"); jButtonGCancel.setEnabled(true); int i = jTabbedPane.indexOfComponent(jPanelPrj); jTabbedPane.setEnabledAt(i,true); jTabbedPane.setSelectedIndex(i); SortedSet<String> alltags = new TreeSet<String>(); try { String line; while (m_PtbOut != null && /*m_PtbOut.ready() &&*/ (line = m_PtbOut.readLine()) != null) { if (line.startsWith("*PTBGUI}*")) { Iterator<String> tt = alltags.iterator(); while (tt.hasNext()) { addProject(jListTags,tt.next(),false); } countSelected(); return; } String[] kv = line.split(","); if (kv.length > 2) { String prj = kv[0].trim(); String type = kv[1].trim(); boolean selected = kv[2].trim().equals("select"); if (type.equals("lib")) { addProject(jListLibs,prj,selected); } else if (type.equals("app")) { addProject(jListApps,prj,selected); } else { addProject(jListOther,prj,selected); } if (kv.length > 4) { String[] tags = kv[4].trim().split("/"); for (int t=0; t<tags.length; ++t) { alltags.add(tags[t]); } m_ProjectTags.put(prj, tags); } } } } catch (Exception e) { System.err.println(e.toString()); e.printStackTrace(); } } private void doneProjects() { if (isPtbRunning()) { try { String s; s = "*PTBGUI{* projects" + "\n"; m_PtbIn.write(s.getBytes()); writeSelected(jListApps, m_PtbIn); writeSelected(jListLibs, m_PtbIn); writeSelected(jListOther, m_PtbIn); s = "*PTBGUI}* projects" + "\n"; m_PtbIn.write(s.getBytes()); m_PtbIn.flush(); } catch (Exception e) { System.err.println(e.toString()); e.printStackTrace(); } } } private void processDone(int exitcode) { m_State = eState.donePtb; jButtonGOK.setVisible(false); jButtonGCancel.setEnabled(true); jButtonGCancel.setText("Finish"); int i = jTabbedPane.indexOfComponent(jPanelDone); jTabbedPane.setEnabledAt(i,true); jTabbedPane.setSelectedIndex(i); if (exitcode == 0) { jLabelDone.setText("Configuration has completed successfully"); jLabelSln.setText(m_ArgsParser.getSolution()); jLabelSln.setVisible(true); jLabelGen.setVisible(true); } else { jLabelDone.setText("Configuration has FAILED"); jLabelSln.setVisible(false); jLabelGen.setVisible(false); } File args = new File(m_ArgsParser.getSolution()); m_Params = args.getParent() + File.separator + "project_tree_builder.ini.custom"; File prm = new File(m_Params); jButtonSave.setEnabled(prm.exists()); } private void startPtb() { updateData(); String[] cmdline = m_ArgsParser.createCommandline(); for (int i=0; i<cmdline.length; ++i) { System.err.print(cmdline[i]); System.err.print(" "); } System.err.println(""); Runtime r = Runtime.getRuntime(); try { String cwd = System.getProperty("user.dir"); m_Ptb = r.exec(cmdline, null, new File(cwd)); m_PtbIn = m_Ptb.getOutputStream(); InputStream out = m_Ptb.getInputStream(); InputStream err = m_Ptb.getErrorStream(); m_PtbOut = new BufferedReader(new InputStreamReader(out)); m_PtbErr = new BufferedReader(new InputStreamReader(err)); } catch (Exception e) { System.err.println(e.toString()); e.printStackTrace(); } } private void stopPtb() { if (isPtbRunning()) { try { String s; s = "*PTBGUIabort*" + "\n"; m_PtbIn.write(s.getBytes()); m_PtbIn.flush(); for (int i=0; i<5; ++i) { if (isPtbRunning()) { Thread.sleep(300); } else { break; } } } catch (Exception e) { System.err.println(e.toString()); e.printStackTrace(); } } if (isPtbRunning()) { m_Ptb.destroy(); } if (ArgsParser.existsPath(m_TmpParams)) { System.gc(); (new File(m_TmpParams)).delete(); } } private boolean isPtbRunning() { boolean isRunning = false; if (m_Ptb != null) { try { m_Ptb.exitValue(); } catch (IllegalThreadStateException e) { isRunning = true; } } return isRunning; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jTabbedPane = new javax.swing.JTabbedPane(); jPanelCmnd = new javax.swing.JPanel(); jTextFieldTags = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jTextFieldLst = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jButtonLst = new javax.swing.JButton(); jLabel11 = new javax.swing.JLabel(); jButtonArgs = new javax.swing.JButton(); jRadioButtonStatic = new javax.swing.JRadioButton(); jRadioButtonDLL = new javax.swing.JRadioButton(); jSeparator2 = new javax.swing.JSeparator(); jLabel14 = new javax.swing.JLabel(); jLabelArgs = new javax.swing.JLabel(); jButtonArgsReset = new javax.swing.JButton(); jButtonKTags = new javax.swing.JButton(); jLabel10 = new javax.swing.JLabel(); jTextFieldLstTags = new javax.swing.JTextField(); jPanelAdvanced = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jTextFieldPtb = new javax.swing.JTextField(); jButtonPtb = new javax.swing.JButton(); jLabel5 = new javax.swing.JLabel(); jTextFieldSolution = new javax.swing.JTextField(); jCheckBoxNoPtb = new javax.swing.JCheckBox(); jCheckBoxNws = new javax.swing.JCheckBox(); jCheckBoxExt = new javax.swing.JCheckBox(); jTextFieldExt = new javax.swing.JTextField(); jLabel12 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jTextFieldIde = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); jTextFieldArch = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jTextFieldRoot = new javax.swing.JTextField(); jButtonMore = new javax.swing.JButton(); jPanelAdd = new javax.swing.JPanel(); jLabel8 = new javax.swing.JLabel(); jTextField3root = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); jTextFieldCpath = new javax.swing.JTextField(); jCheckBoxVTuneR = new javax.swing.JCheckBox(); jCheckBoxVTuneD = new javax.swing.JCheckBox(); jCheckBoxVTune = new javax.swing.JCheckBox(); jPanelUserReq = new javax.swing.JPanel(); jLabelUserReq = new javax.swing.JLabel(); jScrollPane5 = new javax.swing.JScrollPane(); jListUserReq = new javax.swing.JList(); jPanelPrj = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jLabelApps = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jListApps = new javax.swing.JList(); jButtonAppsPlus = new javax.swing.JButton(); jButtonAppsMinus = new javax.swing.JButton(); jPanel3 = new javax.swing.JPanel(); jLabelLibs = new javax.swing.JLabel(); jScrollPane2 = new javax.swing.JScrollPane(); jListLibs = new javax.swing.JList(); jButtonLibsMinus = new javax.swing.JButton(); jButtonLibsPlus = new javax.swing.JButton(); jPanel4 = new javax.swing.JPanel(); jLabelOther = new javax.swing.JLabel(); jScrollPane3 = new javax.swing.JScrollPane(); jListOther = new javax.swing.JList(); jButtonOtherMinus = new javax.swing.JButton(); jButtonOtherPlus = new javax.swing.JButton(); jPanel5 = new javax.swing.JPanel(); jLabelTags = new javax.swing.JLabel(); jScrollPane4 = new javax.swing.JScrollPane(); jListTags = new javax.swing.JList(); jPanelDone = new javax.swing.JPanel(); jLabelDone = new javax.swing.JLabel(); jButtonSave = new javax.swing.JButton(); jButtonStartOver = new javax.swing.JButton(); jLabelGen = new javax.swing.JLabel(); jLabelSln = new javax.swing.JLabel(); jButtonGCancel = new javax.swing.JButton(); jButtonGOK = new javax.swing.JButton(); jLabel13 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("The Toolkit configuration parameters"); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); jTextFieldTags.setText("jTextFieldTags"); jLabel4.setText("Use project tags"); jTextFieldLst.setText("jTextFieldLst"); jTextFieldLst.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { jTextFieldLstFocusLost(evt); } }); jLabel3.setText("Subtree, or LST file"); jButtonLst.setText("..."); jButtonLst.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonLstActionPerformed(evt); } }); jLabel11.setText("Originally loaded from"); jButtonArgs.setText("Load from file..."); jButtonArgs.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonArgsActionPerformed(evt); } }); jRadioButtonStatic.setText("Static"); jRadioButtonStatic.setEnabled(false); jRadioButtonStatic.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonStaticActionPerformed(evt); } }); jRadioButtonDLL.setText("Dynamic"); jRadioButtonDLL.setEnabled(false); jRadioButtonDLL.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonDLLActionPerformed(evt); } }); jLabel14.setText("Build libraries as"); jLabelArgs.setText("l"); jLabelArgs.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jButtonArgsReset.setText("Reset"); jButtonArgsReset.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonArgsResetActionPerformed(evt); } }); jButtonKTags.setText("..."); jButtonKTags.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonKTagsActionPerformed(evt); } }); jLabel10.setText("Default project tags"); jTextFieldLstTags.setEditable(false); jTextFieldLstTags.setText("jTextFieldLstTags"); org.jdesktop.layout.GroupLayout jPanelCmndLayout = new org.jdesktop.layout.GroupLayout(jPanelCmnd); jPanelCmnd.setLayout(jPanelCmndLayout); jPanelCmndLayout.setHorizontalGroup( jPanelCmndLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelCmndLayout.createSequentialGroup() .addContainerGap() .add(jPanelCmndLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelCmndLayout.createSequentialGroup() .add(jPanelCmndLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelCmndLayout.createSequentialGroup() .add(jLabel14, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 149, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanelCmndLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false) .add(org.jdesktop.layout.GroupLayout.LEADING, jRadioButtonDLL, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(org.jdesktop.layout.GroupLayout.LEADING, jRadioButtonStatic, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE))) .add(jSeparator2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 624, Short.MAX_VALUE) .add(jPanelCmndLayout.createSequentialGroup() .add(jPanelCmndLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false) .add(jLabel11, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(jButtonArgs, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 167, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanelCmndLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jLabelArgs, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 451, Short.MAX_VALUE) .add(jButtonArgsReset, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 87, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanelCmndLayout.createSequentialGroup() .add(jPanelCmndLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(org.jdesktop.layout.GroupLayout.LEADING, jPanelCmndLayout.createSequentialGroup() .add(jLabel4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 149, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jTextFieldTags, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 398, Short.MAX_VALUE)) .add(jPanelCmndLayout.createSequentialGroup() .add(jLabel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 148, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jTextFieldLst, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 399, Short.MAX_VALUE))) .add(18, 18, 18) .add(jPanelCmndLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jButtonKTags, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 55, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jButtonLst, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 55, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))) .addContainerGap()) .add(jPanelCmndLayout.createSequentialGroup() .add(jLabel10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 149, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jTextFieldLstTags, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 398, Short.MAX_VALUE) .add(83, 83, 83)))) ); jPanelCmndLayout.setVerticalGroup( jPanelCmndLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelCmndLayout.createSequentialGroup() .add(jPanelCmndLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelCmndLayout.createSequentialGroup() .addContainerGap() .add(jRadioButtonStatic) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jRadioButtonDLL)) .add(jPanelCmndLayout.createSequentialGroup() .add(24, 24, 24) .add(jLabel14))) .add(19, 19, 19) .add(jPanelCmndLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel3) .add(jTextFieldLst, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jButtonLst, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(jPanelCmndLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel4) .add(jTextFieldTags, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jButtonKTags, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(jPanelCmndLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(jLabel10) .add(jTextFieldLstTags, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 27, Short.MAX_VALUE) .add(jSeparator2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanelCmndLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jButtonArgs, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jButtonArgsReset)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanelCmndLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel11) .add(jLabelArgs)) .add(36, 36, 36)) ); jTabbedPane.addTab("Configuration", jPanelCmnd); jLabel1.setText("Project tree builder"); jTextFieldPtb.setText("jTextFieldPtb"); jButtonPtb.setText("..."); jButtonPtb.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonPtbActionPerformed(evt); } }); jLabel5.setText("Solution to generate"); jTextFieldSolution.setText("jTextFieldSolution"); jCheckBoxNoPtb.setText("Exclude 'Build PTB' step from CONFIGURE project"); jCheckBoxNws.setText("Do not scan the whole source tree for missing project dependencies"); jCheckBoxExt.setText("Use external libraries instead of missing in-tree ones"); jTextFieldExt.setText("jTextFieldExt"); jLabel12.setText("Look for missing libraries in this tree"); jLabel6.setText("Target IDE"); jTextFieldIde.setEditable(false); jTextFieldIde.setText("jTextFieldIde"); jLabel7.setText("Target architecture"); jTextFieldArch.setText("jTextFieldArch"); jLabel2.setText("Source root"); jTextFieldRoot.setText("jTextFieldRoot"); jTextFieldRoot.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { jTextFieldRootFocusLost(evt); } }); jButtonMore.setText("more >"); jButtonMore.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonMoreActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout jPanelAdvancedLayout = new org.jdesktop.layout.GroupLayout(jPanelAdvanced); jPanelAdvanced.setLayout(jPanelAdvancedLayout); jPanelAdvancedLayout.setHorizontalGroup( jPanelAdvancedLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelAdvancedLayout.createSequentialGroup() .addContainerGap() .add(jPanelAdvancedLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelAdvancedLayout.createSequentialGroup() .add(jPanelAdvancedLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jLabel12, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE) .add(jLabel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE) .add(jLabel6, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE) .add(jLabel7, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanelAdvancedLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelAdvancedLayout.createSequentialGroup() .add(jPanelAdvancedLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false) .add(org.jdesktop.layout.GroupLayout.LEADING, jTextFieldIde) .add(org.jdesktop.layout.GroupLayout.LEADING, jTextFieldArch, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 112, Short.MAX_VALUE)) .add(289, 289, 289)) .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanelAdvancedLayout.createSequentialGroup() .add(jPanelAdvancedLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(org.jdesktop.layout.GroupLayout.LEADING, jTextFieldSolution, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 397, Short.MAX_VALUE) .add(jTextFieldExt, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 397, Short.MAX_VALUE) .add(org.jdesktop.layout.GroupLayout.LEADING, jButtonMore)) .addContainerGap()))) .add(jPanelAdvancedLayout.createSequentialGroup() .add(jPanelAdvancedLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(jCheckBoxNws, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 444, Short.MAX_VALUE) .add(jCheckBoxNoPtb, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 444, Short.MAX_VALUE) .add(org.jdesktop.layout.GroupLayout.LEADING, jCheckBoxExt, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 444, Short.MAX_VALUE)) .add(190, 190, 190)) .add(jPanelAdvancedLayout.createSequentialGroup() .add(jPanelAdvancedLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false) .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(jPanelAdvancedLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelAdvancedLayout.createSequentialGroup() .add(jTextFieldPtb, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 365, Short.MAX_VALUE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jButtonPtb, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 55, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(jTextFieldRoot, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 426, Short.MAX_VALUE)) .addContainerGap()))) ); jPanelAdvancedLayout.setVerticalGroup( jPanelAdvancedLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelAdvancedLayout.createSequentialGroup() .addContainerGap() .add(jPanelAdvancedLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel6) .add(jTextFieldIde, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanelAdvancedLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel7) .add(jTextFieldArch, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanelAdvancedLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel5) .add(jTextFieldSolution, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(jPanelAdvancedLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel12) .add(jTextFieldExt, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jButtonMore) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(jCheckBoxNoPtb) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jCheckBoxNws) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jCheckBoxExt) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(jPanelAdvancedLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel1) .add(jTextFieldPtb, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jButtonPtb, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanelAdvancedLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel2) .add(jTextFieldRoot, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jTabbedPane.addTab("Advanced", jPanelAdvanced); jLabel8.setText("Root directory of 3-rd party libraries"); jTextField3root.setText("jTextField3root"); jLabel9.setText("Path to the NCBI C Toolkit"); jTextFieldCpath.setText("jTextFieldCpath"); jCheckBoxVTuneR.setText("Release"); jCheckBoxVTuneD.setText("Debug"); jCheckBoxVTune.setText("Add VTune configurations:"); jCheckBoxVTune.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxVTuneActionPerformed(evt); } }); jLabelUserReq.setText("Additional requests"); jListUserReq.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPane5.setViewportView(jListUserReq); org.jdesktop.layout.GroupLayout jPanelUserReqLayout = new org.jdesktop.layout.GroupLayout(jPanelUserReq); jPanelUserReq.setLayout(jPanelUserReqLayout); jPanelUserReqLayout.setHorizontalGroup( jPanelUserReqLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelUserReqLayout.createSequentialGroup() .addContainerGap() .add(jPanelUserReqLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jScrollPane5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 122, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabelUserReq, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jPanelUserReqLayout.setVerticalGroup( jPanelUserReqLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelUserReqLayout.createSequentialGroup() .addContainerGap() .add(jLabelUserReq) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jScrollPane5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 144, Short.MAX_VALUE) .addContainerGap()) ); org.jdesktop.layout.GroupLayout jPanelAddLayout = new org.jdesktop.layout.GroupLayout(jPanelAdd); jPanelAdd.setLayout(jPanelAddLayout); jPanelAddLayout.setHorizontalGroup( jPanelAddLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelAddLayout.createSequentialGroup() .addContainerGap() .add(jPanelAddLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelUserReq, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jPanelAddLayout.createSequentialGroup() .add(jPanelAddLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false) .add(jCheckBoxVTune, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(jLabel9, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(jLabel8, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)) .add(jPanelAddLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelAddLayout.createSequentialGroup() .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(jPanelAddLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jTextFieldCpath, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE) .add(jTextField3root, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE))) .add(jPanelAddLayout.createSequentialGroup() .add(72, 72, 72) .add(jCheckBoxVTuneR) .add(18, 18, 18) .add(jCheckBoxVTuneD))))) .addContainerGap()) ); jPanelAddLayout.setVerticalGroup( jPanelAddLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelAddLayout.createSequentialGroup() .addContainerGap() .add(jPanelAddLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel8) .add(jTextField3root, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanelAddLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel9) .add(jTextFieldCpath, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanelAddLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jCheckBoxVTuneR) .add(jCheckBoxVTuneD) .add(jCheckBoxVTune)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(jPanelUserReq, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jTabbedPane.addTab("Libraries and Tools", jPanelAdd); jPanelPrj.setLayout(new java.awt.GridLayout(1, 0)); jPanel2.setPreferredSize(new java.awt.Dimension(165, 280)); jLabelApps.setText("Applications"); jListApps.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPane1.setViewportView(jListApps); jButtonAppsPlus.setText("+all"); jButtonAppsPlus.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonAppsPlusActionPerformed(evt); } }); jButtonAppsMinus.setText("-all"); jButtonAppsMinus.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonAppsMinusActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 151, Short.MAX_VALUE) .add(jPanel2Layout.createSequentialGroup() .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel2Layout.createSequentialGroup() .add(jButtonAppsPlus) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jButtonAppsMinus)) .add(jLabelApps)) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel2Layout.createSequentialGroup() .add(jLabelApps) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jButtonAppsPlus) .add(jButtonAppsMinus))) ); jPanel3.setPreferredSize(new java.awt.Dimension(160, 280)); jLabelLibs.setText("Libraries"); jListLibs.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPane2.setViewportView(jListLibs); jButtonLibsMinus.setText("-all"); jButtonLibsMinus.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonLibsMinusActionPerformed(evt); } }); jButtonLibsPlus.setText("+all"); jButtonLibsPlus.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonLibsPlusActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 156, Short.MAX_VALUE) .add(jPanel3Layout.createSequentialGroup() .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jLabelLibs) .add(jPanel3Layout.createSequentialGroup() .add(jButtonLibsPlus) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jButtonLibsMinus))) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel3Layout.createSequentialGroup() .add(jLabelLibs) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jButtonLibsPlus) .add(jButtonLibsMinus))) ); jPanel4.setPreferredSize(new java.awt.Dimension(150, 280)); jLabelOther.setText("Other"); jListOther.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPane3.setViewportView(jListOther); jButtonOtherMinus.setText("-all"); jButtonOtherMinus.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonOtherMinusActionPerformed(evt); } }); jButtonOtherPlus.setText("+all"); jButtonOtherPlus.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonOtherPlusActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout jPanel4Layout = new org.jdesktop.layout.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jScrollPane3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 146, Short.MAX_VALUE) .add(jPanel4Layout.createSequentialGroup() .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jLabelOther) .add(jPanel4Layout.createSequentialGroup() .add(jButtonOtherPlus) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jButtonOtherMinus))) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel4Layout.createSequentialGroup() .add(jLabelOther) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jScrollPane3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jButtonOtherPlus) .add(jButtonOtherMinus))) ); jPanel5.setPreferredSize(new java.awt.Dimension(140, 280)); jLabelTags.setText("Tags"); jListTags.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPane4.setViewportView(jListTags); org.jdesktop.layout.GroupLayout jPanel5Layout = new org.jdesktop.layout.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel5Layout.createSequentialGroup() .add(jLabelTags) .addContainerGap(111, Short.MAX_VALUE)) .add(jScrollPane4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 134, Short.MAX_VALUE) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel5Layout.createSequentialGroup() .add(jLabelTags) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jScrollPane4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE) .add(29, 29, 29)) ); org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel1Layout.createSequentialGroup() .addContainerGap() .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 151, Short.MAX_VALUE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 156, Short.MAX_VALUE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 146, Short.MAX_VALUE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 134, Short.MAX_VALUE) .add(29, 29, 29)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel1Layout.createSequentialGroup() .addContainerGap() .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 264, Short.MAX_VALUE) .add(jPanel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 264, Short.MAX_VALUE) .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 264, Short.MAX_VALUE) .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 264, Short.MAX_VALUE)) .addContainerGap()) ); jPanelPrj.add(jPanel1); jTabbedPane.addTab("Projects", jPanelPrj); jLabelDone.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabelDone.setText("jLabelDone"); jButtonSave.setText("Save configuration parameters into a file..."); jButtonSave.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonSaveActionPerformed(evt); } }); jButtonStartOver.setText("Start over"); jButtonStartOver.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonStartOverActionPerformed(evt); } }); jLabelGen.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabelGen.setText("Generated project file:"); jLabelSln.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabelSln.setText("jLabelSln"); org.jdesktop.layout.GroupLayout jPanelDoneLayout = new org.jdesktop.layout.GroupLayout(jPanelDone); jPanelDone.setLayout(jPanelDoneLayout); jPanelDoneLayout.setHorizontalGroup( jPanelDoneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelDoneLayout.createSequentialGroup() .addContainerGap() .add(jPanelDoneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jButtonStartOver, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 305, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(org.jdesktop.layout.GroupLayout.TRAILING, jButtonSave, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 305, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabelDone, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 624, Short.MAX_VALUE) .add(jLabelGen, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 624, Short.MAX_VALUE) .add(jLabelSln, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 624, Short.MAX_VALUE)) .addContainerGap()) ); jPanelDoneLayout.setVerticalGroup( jPanelDoneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanelDoneLayout.createSequentialGroup() .add(29, 29, 29) .add(jLabelDone) .add(18, 18, 18) .add(jLabelGen) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(jLabelSln) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 118, Short.MAX_VALUE) .add(jButtonSave) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(jButtonStartOver) .addContainerGap()) ); jTabbedPane.addTab("Done", jPanelDone); jButtonGCancel.setText("Cancel"); jButtonGCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonGCancelActionPerformed(evt); } }); jButtonGOK.setText("Next"); jButtonGOK.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonGOKActionPerformed(evt); } }); jLabel13.setText(" version 1.3.4"); jLabel13.setToolTipText(""); jLabel13.setEnabled(false); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .addContainerGap() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() .add(jLabel13) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(jButtonGOK, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 276, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(jButtonGCancel)) .add(jTabbedPane)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() .addContainerGap() .add(jTabbedPane) .add(11, 11, 11) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jButtonGCancel) .add(jButtonGOK) .add(jLabel13)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButtonPtbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonPtbActionPerformed JFileChooser fd = new JFileChooser(); fd.setDialogTitle(jLabel1.getText()); File f = new File(jTextFieldPtb.getText()); fd.setCurrentDirectory(f.getParentFile()); if (fd.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { setPathText(jTextFieldPtb, fd.getSelectedFile().getPath(),true); } }//GEN-LAST:event_jButtonPtbActionPerformed private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing stopPtb(); processPtbOutput(); }//GEN-LAST:event_formWindowClosing private void jButtonLstActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLstActionPerformed JFileChooser fd = new JFileChooser(); fd.setDialogTitle(jLabel3.getText()); String root = jTextFieldRoot.getText(); String lst = root + File.separator + jTextFieldLst.getText(); File flst = new File(ArgsParser.existsPath(lst) ? lst : root); fd.setCurrentDirectory(flst.isDirectory()? flst : flst.getParentFile()); if (fd.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { String f = fd.getSelectedFile().getPath(); if (f.startsWith(root)) { f = f.substring(root.length()); if (f.startsWith("\\") || f.startsWith("/")) { f = f.substring(1); } setPathText(jTextFieldLst, root, f); } else { JOptionPane.showMessageDialog( this, "The file must be in the same tree", "Error", JOptionPane.ERROR_MESSAGE); } initTagsFromSubtree(); } }//GEN-LAST:event_jButtonLstActionPerformed private void jButtonArgsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonArgsActionPerformed JFileChooser fd = new JFileChooser(); fd.setDialogTitle(jLabel3.getText()); String args = jLabelArgs.getText(); if (ArgsParser.existsPath(args)) { File f = new File(args); fd.setCurrentDirectory(f.getParentFile()); } else { fd.setCurrentDirectory(new File(".")); } if (fd.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { initData(fd.getSelectedFile().getPath(), false); } }//GEN-LAST:event_jButtonArgsActionPerformed private void jButtonGCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGCancelActionPerformed stopPtb(); processPtbOutput(); }//GEN-LAST:event_jButtonGCancelActionPerformed private void jButtonGOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGOKActionPerformed if (m_State == eState.beforePtb) { startPtb(); } else if (m_State == eState.got3rdparty) { doneAdditionalParams(); } else if (m_State == eState.gotProjects) { doneProjects(); } if (isPtbRunning()) { jButtonGOK.setText("Please wait..."); jButtonGOK.setForeground(Color.red); jButtonGOK.paintImmediately(0,0, jButtonGOK.getWidth(), jButtonGOK.getHeight()); jButtonGOK.setForeground(SystemColor.controlText); jButtonGCancel.setText("Stop"); } processPtbOutput(); }//GEN-LAST:event_jButtonGOKActionPerformed private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSaveActionPerformed JFileChooser fd = new JFileChooser(); fd.setDialogTitle(jButtonSave.getText()); String args = jLabelArgs.getText(); if (ArgsParser.existsPath(args)) { File f = new File(args); fd.setCurrentDirectory(f.getParentFile()); } else { fd.setCurrentDirectory(new File(".")); } if (fd.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { try { String f = fd.getSelectedFile().getPath(); copyFile(m_Params, f); } catch (Exception e) { System.err.println(e.toString()); e.printStackTrace(); } } }//GEN-LAST:event_jButtonSaveActionPerformed private void jButtonArgsResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonArgsResetActionPerformed initData(); }//GEN-LAST:event_jButtonArgsResetActionPerformed private void jButtonAppsPlusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAppsPlusActionPerformed selectProjects(jListApps, true); }//GEN-LAST:event_jButtonAppsPlusActionPerformed private void jButtonAppsMinusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAppsMinusActionPerformed selectProjects(jListApps, false); }//GEN-LAST:event_jButtonAppsMinusActionPerformed private void jButtonLibsPlusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLibsPlusActionPerformed selectProjects(jListLibs, true); }//GEN-LAST:event_jButtonLibsPlusActionPerformed private void jButtonLibsMinusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLibsMinusActionPerformed selectProjects(jListLibs, false); }//GEN-LAST:event_jButtonLibsMinusActionPerformed private void jButtonOtherPlusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOtherPlusActionPerformed selectProjects(jListOther, true); }//GEN-LAST:event_jButtonOtherPlusActionPerformed private void jButtonOtherMinusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOtherMinusActionPerformed selectProjects(jListOther, false); }//GEN-LAST:event_jButtonOtherMinusActionPerformed private void jButtonStartOverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonStartOverActionPerformed resetState(); initData(); }//GEN-LAST:event_jButtonStartOverActionPerformed private void jButtonMoreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonMoreActionPerformed showMoreAdvanced(!jCheckBoxNoPtb.isVisible()); }//GEN-LAST:event_jButtonMoreActionPerformed private void jCheckBoxVTuneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxVTuneActionPerformed jCheckBoxVTuneD.setVisible(jCheckBoxVTune.isSelected()); jCheckBoxVTuneR.setVisible(jCheckBoxVTune.isSelected()); }//GEN-LAST:event_jCheckBoxVTuneActionPerformed private void jRadioButtonStaticActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonStaticActionPerformed adjustBuildType(); }//GEN-LAST:event_jRadioButtonStaticActionPerformed private void jRadioButtonDLLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonDLLActionPerformed adjustBuildType(); }//GEN-LAST:event_jRadioButtonDLLActionPerformed private void jButtonKTagsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonKTagsActionPerformed if (m_KtagsDlg == null) { m_KtagsDlg = new KTagsDialog(this,false); m_KtagsDlg.setLocationRelativeTo(this); } if (!m_KtagsDlg.isVisible()) { m_KtagsDlg.setTextData(m_KnownTags, m_CompositeTags); m_KtagsDlg.setVisible(true); } }//GEN-LAST:event_jButtonKTagsActionPerformed private void jTextFieldLstFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldLstFocusLost initTagsFromSubtree(); }//GEN-LAST:event_jTextFieldLstFocusLost private void jTextFieldRootFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldRootFocusLost initTagsFromSubtree(); }//GEN-LAST:event_jTextFieldRootFocusLost /** * @param args the command line arguments */ public static void main(String args[]) { PtbguiMain ptbgui = new PtbguiMain(); ptbgui.initData(args); ptbgui.setLocationRelativeTo(null); ptbgui.setVisible(true); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonAppsMinus; private javax.swing.JButton jButtonAppsPlus; private javax.swing.JButton jButtonArgs; private javax.swing.JButton jButtonArgsReset; private javax.swing.JButton jButtonGCancel; private javax.swing.JButton jButtonGOK; private javax.swing.JButton jButtonKTags; private javax.swing.JButton jButtonLibsMinus; private javax.swing.JButton jButtonLibsPlus; private javax.swing.JButton jButtonLst; private javax.swing.JButton jButtonMore; private javax.swing.JButton jButtonOtherMinus; private javax.swing.JButton jButtonOtherPlus; private javax.swing.JButton jButtonPtb; private javax.swing.JButton jButtonSave; private javax.swing.JButton jButtonStartOver; private javax.swing.JCheckBox jCheckBoxExt; private javax.swing.JCheckBox jCheckBoxNoPtb; private javax.swing.JCheckBox jCheckBoxNws; private javax.swing.JCheckBox jCheckBoxVTune; private javax.swing.JCheckBox jCheckBoxVTuneD; private javax.swing.JCheckBox jCheckBoxVTuneR; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JLabel jLabelApps; private javax.swing.JLabel jLabelArgs; private javax.swing.JLabel jLabelDone; private javax.swing.JLabel jLabelGen; private javax.swing.JLabel jLabelLibs; private javax.swing.JLabel jLabelOther; private javax.swing.JLabel jLabelSln; private javax.swing.JLabel jLabelTags; private javax.swing.JLabel jLabelUserReq; private javax.swing.JList jListApps; private javax.swing.JList jListLibs; private javax.swing.JList jListOther; private javax.swing.JList jListTags; private javax.swing.JList jListUserReq; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanelAdd; private javax.swing.JPanel jPanelAdvanced; private javax.swing.JPanel jPanelCmnd; private javax.swing.JPanel jPanelDone; private javax.swing.JPanel jPanelPrj; private javax.swing.JPanel jPanelUserReq; private javax.swing.JRadioButton jRadioButtonDLL; private javax.swing.JRadioButton jRadioButtonStatic; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JScrollPane jScrollPane5; private javax.swing.JSeparator jSeparator2; private javax.swing.JTabbedPane jTabbedPane; private javax.swing.JTextField jTextField3root; private javax.swing.JTextField jTextFieldArch; private javax.swing.JTextField jTextFieldCpath; private javax.swing.JTextField jTextFieldExt; private javax.swing.JTextField jTextFieldIde; private javax.swing.JTextField jTextFieldLst; private javax.swing.JTextField jTextFieldLstTags; private javax.swing.JTextField jTextFieldPtb; private javax.swing.JTextField jTextFieldRoot; private javax.swing.JTextField jTextFieldSolution; private javax.swing.JTextField jTextFieldTags; // End of variables declaration//GEN-END:variables }
lgpl-3.0
bendem/OreBroadcast
src/main/java/be/bendem/bukkit/orebroadcast/updater/OreBroadcastUpdater.java
3000
package be.bendem.bukkit.orebroadcast.updater; import be.bendem.bukkit.orebroadcast.OreBroadcast; import net.gravitydevelopment.updater.Updater; import org.bukkit.command.CommandSender; import org.bukkit.scheduler.BukkitRunnable; import java.io.File; /** * @author bendem */ public class OreBroadcastUpdater { private final OreBroadcast plugin; private final File pluginFile; private Updater updater; private boolean isUpdateAvailable = false; private boolean isUpdated = false; public OreBroadcastUpdater(OreBroadcast plugin, File pluginFile) { this.plugin = plugin; this.pluginFile = pluginFile; } public void checkUpdate(final CommandSender sender, final boolean download) { if(!isUpdateAvailable) { new UpdateCheck(plugin, sender, download).runTaskAsynchronously(plugin); } } public void downloadUpdate() { updater = new GravityUpdater(plugin, 72299, pluginFile, Updater.UpdateType.NO_VERSION_CHECK, true); isUpdated = true; } public boolean isUpdateAvailable() { return isUpdateAvailable; } public boolean isUpdated() { return isUpdated; } private class UpdateCheck extends BukkitRunnable { private final OreBroadcast plugin; private final CommandSender sender; private final boolean download; public UpdateCheck(OreBroadcast plugin, CommandSender sender, boolean download) { this.plugin = plugin; this.sender = sender; this.download = download; } @Override public void run() { updater = new GravityUpdater(plugin, 72299, pluginFile, Updater.UpdateType.NO_DOWNLOAD, true); isUpdateAvailable = updater.getResult() == Updater.UpdateResult.UPDATE_AVAILABLE; if(isUpdateAvailable) { new UpdateNotifier(sender, download).runTask(plugin); } } } private class UpdateNotifier extends BukkitRunnable { private final CommandSender sender; private final boolean download; public UpdateNotifier(CommandSender sender, boolean download) { this.sender = sender; this.download = download; } @Override public void run() { if(sender == null) { if(download) { plugin.getLogger().warning(updater.getLatestName() + " is available, downloading it..."); downloadUpdate(); } else { plugin.getLogger().warning(updater.getLatestName() + " is available, type '/ob update download' to download it"); } } else { if(download) { sender.sendMessage("Downloading update..."); downloadUpdate(); } else { sender.sendMessage("Update available"); } } } } }
lgpl-3.0
ArticulatedSocialAgentsPlatform/AsapRealizer
Engines/AsapAudioEngine/src/asap/audioengine/TimedAbstractAudioUnit.java
6784
/******************************************************************************* * Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands * * This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer). * * ASAPRealizer is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License (LGPL) as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ASAPRealizer 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 Lesser General Public License * along with ASAPRealizer. If not, see http://www.gnu.org/licenses/. ******************************************************************************/ package asap.audioengine; import java.io.InputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import saiba.bml.BMLGestureSync; import saiba.bml.feedback.BMLSyncPointProgressFeedback; import asap.realizer.feedback.FeedbackManager; import asap.realizer.pegboard.BMLBlockPeg; import asap.realizer.pegboard.TimePeg; import asap.realizer.planunit.TimedAbstractPlanUnit; /** * Skeleton class for the implementation of TimedAudioUnits * @author hvanwelbergen * */ public abstract class TimedAbstractAudioUnit extends TimedAbstractPlanUnit { private static Logger logger = LoggerFactory.getLogger(TimedAbstractAudioUnit.class.getName()); protected InputStream inputStream; private double duration; protected double systemStartTime; protected double bmlStartTime; private TimePeg startPeg; private TimePeg endPeg; public TimedAbstractAudioUnit(FeedbackManager bfm, BMLBlockPeg bbPeg, InputStream inputStream, String bmlId, String id) { super(bfm, bbPeg, bmlId, id); this.inputStream = inputStream; } /** * Clean up any resources associated with the TimedAbstractAudioUnit */ public abstract void cleanup(); /** * @return the startSync */ public TimePeg getStartPeg() { return startPeg; } /** * @param startSync * the startSync to set */ public void setStartPeg(TimePeg startSync) { this.startPeg = startSync; } /** * @return the endSync */ public TimePeg getEndPeg() { return endPeg; } /** * @param endSync * the endSync to set */ public void setEndPeg(TimePeg endSync) { this.endPeg = endSync; } public void setStart(TimePeg start) { startPeg = start; } public void setEnd(TimePeg end) { endPeg = end; } @Override public double getStartTime() { if (startPeg == null) { return TimePeg.VALUE_UNKNOWN; } return startPeg.getGlobalValue(); } @Override public double getEndTime() { if (endPeg == null || endPeg.getGlobalValue() == TimePeg.VALUE_UNKNOWN) { double startTime = getStartTime(); if (startTime != TimePeg.VALUE_UNKNOWN) { return startTime + getPreferedDuration(); } } else { return endPeg.getGlobalValue(); } return TimePeg.VALUE_UNKNOWN; } @Override public double getRelaxTime() { return getEndTime(); } @Override public void setTimePeg(String syncId, TimePeg peg) { if (BMLGestureSync.isBMLSync(syncId)) { if (BMLGestureSync.get(syncId).isAfter(BMLGestureSync.STROKE)) { setEndPeg(peg); } else { setStartPeg(peg); } } else { logger.warn("Can't set TimePeg on non-BML sync {}", syncId); } } @Override public boolean hasValidTiming() { if (getStartTime() > getEndTime()) { return false; } else if (Math.abs((getEndTime() - getStartTime()) - getPreferedDuration()) > 0.0001) { logger.debug("End time: {}", getEndTime()); logger.debug("Start time: {}", getStartTime()); logger.debug("End-start: {}", (getEndTime() - getStartTime())); logger.debug("Duration: {}", getPreferedDuration()); return false; } return true; } /** * @return Preferred duration (in seconds) of this audio unit (call setup before calling this) */ @Override public double getPreferedDuration() { return duration; } /** * load file, determine timing/duration, etc * * @throws AudioUnitPlanningException */ protected void setupCache() throws AudioUnitPlanningException { }; /** * Setup the Audiounit. Calls setupCache * * @throws AudioUnitPlanningException */ public void setup() throws AudioUnitPlanningException { setupCache(); } protected void sendStartProgress(double time) { logger.debug("sendStartProgress"); String bmlId = getBMLId(); String behaviorId = getId(); double bmlBlockTime = time - bmlBlockPeg.getValue(); feedback(new BMLSyncPointProgressFeedback(bmlId, behaviorId, "start", bmlBlockTime, time)); } /** * Send progress feedback for all bookmarks passed at playTime. * * @param playTime * time since start of the audio unit * @param time * time since start of BML execution */ public abstract void sendProgress(double playTime, double time); /** * Send the end progress feedback info, should be called only from the AudioPlanPlayer. * * @param time * time since start of BML execution */ public void sendEndProgress(double time) { logger.debug("sendEndProgress"); String bmlId = getBMLId(); String behaviorId = getId(); double bmlBlockTime = time - bmlBlockPeg.getValue(); feedback(new BMLSyncPointProgressFeedback(bmlId, behaviorId, "end", bmlBlockTime, time)); } public void setPrefferedDuration(double duration) { this.duration = duration; } @Override public TimePeg getTimePeg(String syncId) { if (syncId.equals("start")) return startPeg; if (syncId.equals("end")) return endPeg; return null; } }
lgpl-3.0
ArticulatedSocialAgentsPlatform/AsapRealizer
Environments/AsapRealizerEmbodiments/src/asap/realizerembodiments/SchedulingClockEmbodiment.java
1270
/******************************************************************************* * Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands * * This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer). * * ASAPRealizer is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License (LGPL) as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ASAPRealizer 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 Lesser General Public License * along with ASAPRealizer. If not, see http://www.gnu.org/licenses/. ******************************************************************************/ package asap.realizerembodiments; import hmi.environmentbase.Embodiment; import hmi.util.Clock; /** * provides access to the scheduling clock of a VH */ public interface SchedulingClockEmbodiment extends Embodiment { Clock getSchedulingClock(); }
lgpl-3.0
RedhawkSDR/framework-bulkioInterfaces
libsrc/java/src/bulkio/InUInt16Port.java
14812
/* * This file is protected by Copyright. Please refer to the COPYRIGHT file * distributed with this source distribution. * * This file is part of REDHAWK bulkioInterfaces. * * REDHAWK bulkioInterfaces 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 3 of the License, or (at your * option) any later version. * * REDHAWK bulkioInterfaces 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 program. If not, see http://www.gnu.org/licenses/. */ package bulkio; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Iterator; import java.util.Map; import org.omg.CORBA.TCKind; import org.ossie.properties.AnyUtils; import CF.DataType; import java.util.ArrayDeque; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import BULKIO.PrecisionUTCTime; import BULKIO.StreamSRI; import BULKIO.PortStatistics; import BULKIO.PortUsageType; import org.apache.log4j.Logger; import bulkio.sriState; import bulkio.linkStatistics; import bulkio.DataTransfer; import bulkio.UInt16Size; import org.ossie.component.PortBase; /** * */ public class InUInt16Port extends BULKIO.jni.dataUshortPOA implements org.ossie.component.PortBase { /** * A class to hold packet data. * */ public class Packet extends DataTransfer < short[] > { public Packet(short[] data, PrecisionUTCTime time, boolean endOfStream, String streamID, StreamSRI H, boolean sriChanged, boolean inputQueueFlushed ) { super(data,time,endOfStream,streamID,H,sriChanged,inputQueueFlushed); }; }; /** * */ protected String name; /** * */ protected linkStatistics stats; /** * */ protected Object sriUpdateLock; /** * */ protected Object statUpdateLock; /** * */ protected Map<String, sriState> currentHs; /** * */ protected Object dataBufferLock; /** * */ protected int maxQueueDepth; /** * */ protected Semaphore queueSem; /** * */ protected Semaphore dataSem; /** * */ protected boolean blocking; /** * */ protected Logger logger = null; protected bulkio.sri.Comparator sri_cmp; protected bulkio.SriListener sriCallback; /** * This queue stores all packets received from pushPacket. * */ private ArrayDeque< Packet > workQueue; /** * */ public InUInt16Port( String portName ) { this( portName, null, new bulkio.sri.DefaultComparator(), null ); } public InUInt16Port( String portName, bulkio.sri.Comparator compareSRI ){ this( portName, null, compareSRI, null ); } public InUInt16Port( String portName, bulkio.sri.Comparator compareSRI, bulkio.SriListener sriCallback ) { this( portName, null, compareSRI, sriCallback ); } public InUInt16Port( String portName, Logger logger ) { this( portName, logger, new bulkio.sri.DefaultComparator(), null ); } public InUInt16Port( String portName, Logger logger, bulkio.sri.Comparator compareSRI, bulkio.SriListener sriCallback ) { this.name = portName; this.stats = new linkStatistics(this.name, new UInt16Size() ); this.sriUpdateLock = new Object(); this.statUpdateLock = new Object(); this.currentHs = new HashMap<String, sriState>(); this.dataBufferLock = new Object(); this.maxQueueDepth = 100; this.queueSem = new Semaphore(this.maxQueueDepth); this.dataSem = new Semaphore(0); this.blocking = false; this.workQueue = new ArrayDeque< Packet >(); sri_cmp = compareSRI; sriCallback = sriCallback; if ( this.logger != null ) { this.logger.debug( "bulkio::InPort CTOR port: " + portName ); } } public void setLogger( Logger newlogger ){ synchronized (this.sriUpdateLock) { logger = newlogger; } } /** * */ public void setSriListener( bulkio.SriListener sriCallback ) { synchronized(this.sriUpdateLock) { this.sriCallback = sriCallback; } } /** * */ public String getName() { return this.name; } /** * */ public void enableStats(boolean enable) { this.stats.setEnabled(enable); } /** * */ public PortStatistics statistics() { synchronized (statUpdateLock) { return this.stats.retrieve(); } } /** * */ public PortUsageType state() { int queueSize = 0; synchronized (dataBufferLock) { queueSize = workQueue.size(); if (queueSize == maxQueueDepth) { return PortUsageType.BUSY; } else if (queueSize == 0) { return PortUsageType.IDLE; } return PortUsageType.ACTIVE; } } /** * */ public StreamSRI[] activeSRIs() { synchronized (this.sriUpdateLock) { ArrayList<StreamSRI> sris = new ArrayList<StreamSRI>(); Iterator<sriState> iter = this.currentHs.values().iterator(); while(iter.hasNext()) { sris.add(iter.next().getSRI()); } return sris.toArray(new StreamSRI[sris.size()]); } } /** * */ public int getCurrentQueueDepth() { synchronized (this.dataBufferLock) { return workQueue.size(); } } /** * */ public int getMaxQueueDepth() { synchronized (this.dataBufferLock) { return this.maxQueueDepth; } } /** * */ public void setMaxQueueDepth(int newDepth) { synchronized (this.dataBufferLock) { this.maxQueueDepth = newDepth; queueSem = new Semaphore(newDepth); } } /** * */ public void pushSRI(StreamSRI header) { if ( logger != null ) { logger.trace("bulkio.InPort pushSRI ENTER (port=" + name +")" ); } synchronized (sriUpdateLock) { if (!currentHs.containsKey(header.streamID)) { if ( logger != null ) { logger.debug("pushSRI PORT:" + name + " NEW SRI:" + header.streamID ); } if ( sriCallback != null ) { sriCallback.newSRI(header); } currentHs.put(header.streamID, new sriState(header, true)); if (header.blocking) { //If switching to blocking we have to set the semaphore synchronized (dataBufferLock) { if (!blocking) { try { queueSem.acquire(workQueue.size()); } catch (InterruptedException e) { e.printStackTrace(); } } blocking = true; } } } else { StreamSRI oldSri = currentHs.get(header.streamID).getSRI(); boolean cval = false; if ( sri_cmp != null ) { cval = sri_cmp.compare( header, oldSri ); } if ( cval == false ) { if ( sriCallback != null ) { sriCallback.changedSRI(header); } this.currentHs.put(header.streamID, new sriState(header, true)); if (header.blocking) { //If switching to blocking we have to set the semaphore synchronized (dataBufferLock) { if (!blocking) { try { queueSem.acquire(workQueue.size()); } catch (InterruptedException e) { e.printStackTrace(); } } blocking = true; } } } } } if ( logger != null ) { logger.trace("bulkio.InPort pushSRI EXIT (port=" + name +")" ); } } /** * */ public void pushPacket(short[] data, PrecisionUTCTime time, boolean eos, String streamID) { if ( logger != null ) { logger.trace("bulkio.InPort pushPacket ENTER (port=" + name +")" ); } synchronized (this.dataBufferLock) { if (this.maxQueueDepth == 0) { return; } } boolean portBlocking = false; StreamSRI tmpH = null; boolean sriChanged = false; synchronized (this.sriUpdateLock) { if (this.currentHs.containsKey(streamID)) { tmpH = this.currentHs.get(streamID).getSRI(); sriChanged = this.currentHs.get(streamID).isChanged(); if ( eos == false ) { this.currentHs.get(streamID).setChanged(false); } portBlocking = blocking; } else { if (logger != null) { logger.warn("bulkio.InPort pushPacket received data from stream '" + streamID + "' with no SRI"); } tmpH = new StreamSRI(1, 0.0, 1.0, (short)1, 0, 0.0, 0.0, (short)0, (short)0, streamID, false, new DataType[0]); if (sriCallback != null) { sriCallback.newSRI(tmpH); } sriChanged = true; currentHs.put(streamID, new sriState(tmpH, false)); } } // determine whether to block and wait for an empty space in the queue Packet p = null; if (portBlocking) { p = new Packet(data, time, eos, streamID, tmpH, sriChanged, false); try { queueSem.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (this.dataBufferLock) { this.stats.update(data.length, this.workQueue.size()/(float)this.maxQueueDepth, eos, streamID, false); this.workQueue.add(p); this.dataSem.release(); } } else { synchronized (this.dataBufferLock) { if (this.workQueue.size() == this.maxQueueDepth) { if ( logger != null ) { logger.debug( "bulkio::InPort pushPacket PURGE INPUT QUEUE (SIZE" + this.workQueue.size() + ")" ); } boolean sriChangedHappened = false; boolean flagEOS = false; for (Iterator< Packet > itr = this.workQueue.iterator(); itr.hasNext();) { if (sriChangedHappened && flagEOS) { break; } Packet currentPacket = itr.next(); if (currentPacket.sriChanged) { sriChangedHappened = true; } if (currentPacket.EOS) { flagEOS = true; } } if (sriChangedHappened) { sriChanged = true; } if (flagEOS) { eos = true; } this.workQueue.clear(); p = new Packet( data, time, eos, streamID, tmpH, sriChanged, true); this.stats.update(data.length, 0, eos, streamID, true); } else { p = new Packet(data, time, eos, streamID, tmpH, sriChanged, false); this.stats.update(data.length, this.workQueue.size()/(float)this.maxQueueDepth, eos, streamID, false); } if ( logger != null ) { logger.trace( "bulkio::InPort pushPacket NEW Packet (QUEUE=" + workQueue.size() + ")"); } this.workQueue.add(p); this.dataSem.release(); } } if ( logger != null ) { logger.trace("bulkio.InPort pushPacket EXIT (port=" + name +")" ); } return; } /** * */ public Packet getPacket(long wait) { if ( logger != null ) { logger.trace("bulkio.InPort getPacket ENTER (port=" + name +")" ); } try { if (wait < 0) { if ( logger != null ) { logger.trace("bulkio.InPort getPacket PORT:" + name +" Block until data arrives" ); } this.dataSem.acquire(); } else { if ( logger != null ) { logger.trace("bulkio.InPort getPacket PORT:" + name +" TIMED WAIT:" + wait ); } this.dataSem.tryAcquire(wait, TimeUnit.MILLISECONDS); } } catch (InterruptedException ex) { if ( logger != null ) { logger.trace("bulkio.InPort getPacket EXIT (port=" + name +")" ); } return null; } Packet p = null; synchronized (this.dataBufferLock) { p = this.workQueue.poll(); } if (p != null) { if (p.getEndOfStream()) { synchronized (this.sriUpdateLock) { if (this.currentHs.containsKey(p.getStreamID())) { sriState rem = this.currentHs.remove(p.getStreamID()); if (rem.getSRI().blocking) { boolean stillBlocking = false; Iterator<sriState> iter = currentHs.values().iterator(); while (iter.hasNext()) { if (iter.next().getSRI().blocking) { stillBlocking = true; break; } } if (!stillBlocking) { blocking = false; } } } } } if (blocking) { queueSem.release(); } } if ( logger != null ) { logger.trace("bulkio.InPort getPacket EXIT (port=" + name +")" ); } return p; } public String getRepid() { return BULKIO.dataUshortHelper.id(); } public String getDirection() { return "Provides"; } }
lgpl-3.0
lburgazzoli/Chronicle-Engine
src/test/java/net/openhft/chronicle/engine/ChassisRFCTest.java
9546
/* * Copyright (C) 2015 higherfrequencytrading.com * * This program 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 3 of the License. * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.openhft.chronicle.engine; import net.openhft.chronicle.core.threads.ThreadDump; import net.openhft.chronicle.engine.api.map.MapEvent; import net.openhft.chronicle.engine.api.map.MapView; import net.openhft.chronicle.engine.api.pubsub.*; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Map; import static net.openhft.chronicle.engine.Chassis.*; import static org.junit.Assert.assertEquals; /** * Created by peter on 22/05/15. */ public class ChassisRFCTest { private ThreadDump threadDump; @Before public void threadDump() { threadDump = new ThreadDump(); } @After public void checkThreadDump() { threadDump.assertNoNewThreads(); } @Before public void setUpTest() { Chassis.resetChassis(); } @Test public void subscriptionToATopic() { Map<String, String> map = acquireMap("group-A", String.class, String.class); map.put("Key-1", "Value-1"); List<String> values = new ArrayList<>(); Subscriber<String> subscriber = values::add; registerSubscriber("group-A/Key-1?bootstrap=true", String.class, subscriber); map.put("Key-1", "Value-2"); map.remove("Key-1"); assertEquals("[Value-1, Value-2, null]", values.toString()); } @Test public void subscriptionToAGroupOfTopics() { Map<String, String> map = acquireMap("group-A", String.class, String.class); map.put("Key-1", "Value-1"); List<String> values = new ArrayList<>(); TopicSubscriber<String, String> subscriber = (topic, message) -> values.add("{name: " + topic + ", message: " + message + "}"); registerTopicSubscriber("group-A", String.class, String.class, subscriber); map.put("Key-1", "Value-2"); map.remove("Key-1"); assertEquals("[{name: Key-1, message: Value-1}, " + "{name: Key-1, message: Value-2}, " + "{name: Key-1, message: null}]", values.toString()); } @Test public void subscriptionToChangesInEntries() { Map<String, String> map = acquireMap("group-A", String.class, String.class); map.put("Key-1", "Value-1"); List<MapEvent> values = new ArrayList<>(); Subscriber<MapEvent> subscriber = values::add; registerSubscriber("group-A?view=map&bootstrap=true", MapEvent.class, subscriber); map.put("Key-1", "Value-2"); map.remove("Key-1"); assertEquals("[!InsertedEvent {\n" + " assetName: /group-A,\n" + " key: Key-1,\n" + " value: Value-1,\n" + " isReplicationEvent: false\n" + "}\n" + ", !UpdatedEvent {\n" + " assetName: /group-A,\n" + " key: Key-1,\n" + " oldValue: Value-1,\n" + " value: Value-2,\n" + " isReplicationEvent: false,\n" + " hasValueChanged: true\n" + "}\n" + ", !RemovedEvent {\n" + " assetName: /group-A,\n" + " key: Key-1,\n" + " oldValue: Value-2,\n" + " isReplicationEvent: false\n" + "}\n" + "]", values.toString()); } @Test public void publishToATopic() { Map<String, String> map = acquireMap("group", String.class, String.class); Publisher<String> publisher = acquirePublisher("group/topic", String.class); List<String> values = new ArrayList<>(); Subscriber<String> subscriber = values::add; registerSubscriber("group/topic?bootstrap=false", String.class, subscriber); publisher.publish("Message-1"); assertEquals("Message-1", map.get("topic")); map.put("topic", "Message-2"); assertEquals("Message-2", map.get("topic")); assertEquals("[Message-1, Message-2]", values.toString()); } @Test public void referenceToATopic() { Map<String, String> map = acquireMap("group", String.class, String.class); Reference<String> reference = acquireReference("group/topic", String.class); List<String> values = new ArrayList<>(); Subscriber<String> subscriber = values::add; registerSubscriber("group/topic?bootstrap=false", String.class, subscriber); List<String> values2 = new ArrayList<>(); Subscriber<String> subscriber2 = values2::add; reference.registerSubscriber(true, 0, subscriber2); reference.set("Message-1"); assertEquals("Message-1", reference.get()); assertEquals("Message-1", map.get("topic")); reference.publish("Message-2"); assertEquals("Message-2", reference.get()); assertEquals("Message-2", map.get("topic")); assertEquals("[Message-1, Message-2]", values.toString()); assertEquals("[null, Message-1, Message-2]", values2.toString()); reference.set("Message-3"); assertEquals("Message-3", reference.get()); assertEquals("Message-3", map.get("topic")); assertEquals("[Message-1, Message-2, Message-3]", values.toString()); assertEquals("[null, Message-1, Message-2, Message-3]", values2.toString()); assertEquals("Message-3".length(), reference.applyTo(String::length), 0); reference.asyncUpdate(String::toUpperCase); assertEquals("MESSAGE-3", reference.get()); assertEquals("MESSAGE-3", map.get("topic")); assertEquals("[Message-1, Message-2, Message-3, MESSAGE-3]", values.toString()); assertEquals("[null, Message-1, Message-2, Message-3, MESSAGE-3]", values2.toString()); assertEquals("Message-3A".length(), reference.syncUpdate(s -> s.concat("A"), String::length), 0); assertEquals("MESSAGE-3A", reference.get()); assertEquals("MESSAGE-3A", map.get("topic")); assertEquals("[Message-1, Message-2, Message-3, MESSAGE-3, MESSAGE-3A]", values.toString()); assertEquals("[null, Message-1, Message-2, Message-3, MESSAGE-3, MESSAGE-3A]", values2.toString()); } @Test public void publishToAnyTopicInAGroup() { Map<String, String> map = acquireMap("group", String.class, String.class); map.clear(); TopicPublisher<String, String> publisher = acquireTopicPublisher("group", String.class, String.class); List<String> values = new ArrayList<>(); TopicSubscriber<String, String> subscriber = (topic, message) -> values.add("{name: " + topic + ", message: " + message + "}"); registerTopicSubscriber("group", String.class, String.class, subscriber); List<String> values2 = new ArrayList<>(); TopicSubscriber<String, String> subscriber2 = (topic, message) -> values2.add("{name: " + topic + ", message: " + message + "}"); publisher.registerTopicSubscriber(subscriber2); publisher.publish("topic-1", "Message-1"); assertEquals("Message-1", map.get("topic-1")); publisher.publish("topic-1", "Message-2"); assertEquals("Message-2", map.get("topic-1")); assertEquals("[{name: topic-1, message: Message-1}, {name: topic-1, message: Message-2}]", values2.toString()); assertEquals("[{name: topic-1, message: Message-1}, {name: topic-1, message: Message-2}]", values.toString()); } @Test public void updateTheMapView() { MapView<String, String> map = acquireMap("group", String.class, String.class); List<String> values = new ArrayList<>(); TopicSubscriber<String, String> subscriber = (topic, message) -> values.add("{name: " + topic + ", message: " + message + "}"); registerTopicSubscriber("group", String.class, String.class, subscriber); map.put("topic-1", "Message-1"); assertEquals("Message-1", map.get("topic-1")); assertEquals(1, map.applyTo(Map::size), 0); map.remove("topic-1"); assertEquals(null, map.get("topic-1")); assertEquals("[{name: topic-1, message: Message-1}, {name: topic-1, message: null}]", values.toString()); map.asyncUpdate(m -> map.put("topic-2", "Message-2")); assertEquals("Message-2", map.get("topic-2")); assertEquals("[{name: topic-1, message: Message-1}, {name: topic-1, message: null}, {name: topic-2, message: Message-2}]", values.toString()); assertEquals(0, map.syncUpdate(m -> m.remove("topic-2"), Map::size), 0); assertEquals(null, map.get("topic-2")); assertEquals("[{name: topic-1, message: Message-1}, {name: topic-1, message: null}, {name: topic-2, message: Message-2}, {name: topic-2, message: null}]", values.toString()); } }
lgpl-3.0
c2mon/c2mon
c2mon-shared/c2mon-shared-common/src/main/java/cern/c2mon/shared/common/datatag/address/OPCDataHardwareAddress.java
1209
/****************************************************************************** * Copyright (C) 2010-2016 CERN. All rights not expressly granted are reserved. * * This file is part of the CERN Control and Monitoring Platform 'C2MON'. * C2MON 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 3 of the license. * * C2MON 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 C2MON. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************/ package cern.c2mon.shared.common.datatag.address; public interface OPCDataHardwareAddress { /** * Gets a second address * The item name can never be null. * @return the name of the OPC item not being currently used */ String getOpcRedundantItemName(); }
lgpl-3.0
myoKun345/ElementalExperimentation
elex_common/myokun/mods/elex/core/RenderUtilities.java
832
package myokun.mods.elex.core; import net.minecraftforge.common.ForgeDirection; /** * Elemental Experimentation * * RenderUtilities * * @author Myo-kun * @credit BuildCraft team * @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html) */ public class RenderUtilities { public static ForgeDirection get2dOrientation(Position pos1, Position pos2) { double Dx = pos1.x - pos2.x; double Dz = pos1.z - pos2.z; double angle = Math.atan2(Dz, Dx) / Math.PI * 180 + 180; if (angle < 45 || angle > 315) { return ForgeDirection.EAST; } else if (angle < 135) { return ForgeDirection.SOUTH; } else if (angle < 225) { return ForgeDirection.WEST; } else { return ForgeDirection.NORTH; } } }
lgpl-3.0
smallAreaHealthStatisticsUnit/rapidInquiryFacility
rifServices/src/main/java/org/sahsu/rif/services/graphics/RIFMapsParameters.java
16616
package org.sahsu.rif.services.graphics; import java.io.BufferedReader; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import org.geotools.feature.DefaultFeatureCollection; import org.json.JSONArray; import org.json.JSONObject; import org.sahsu.rif.generic.fileformats.AppFile; import org.sahsu.rif.generic.system.RIFServiceException; import org.sahsu.rif.generic.util.RIFLogger; import org.sahsu.rif.services.concepts.StudyType; import org.sahsu.rif.services.datastorage.common.SQLManager; import org.sahsu.rif.services.system.RIFServiceError; import org.sahsu.rif.services.util.Json5Parse; import javax.sql.rowset.CachedRowSet; /** * * <hr> * The Rapid Inquiry Facility (RIF) is an automated tool devised by SAHSU * that rapidly addresses epidemiological and public health questions using * routinely collected health and population data and generates standardised * rates and relative risks for any given health outcome, for specified age * and year ranges, for any given geographical area. * * Copyright 2017 Imperial College London, developed by the Small Area * Health Statistics Unit. The work of the Small Area Health Statistics Unit * is funded by the Public Health England as part of the MRC-PHE Centre for * Environment and Health. Funding for this project has also been received * from the United States Centers for Disease Control and Prevention. * * <pre> * This file is part of the Rapid Inquiry Facility (RIF) project. * RIF 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 3 of the License, or * (at your option) any later version. * * RIF 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 RIF. If not, see <http://www.gnu.org/licenses/>; or write * to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * </pre> * * <hr> * Peter Hambly * @author phambly */ /* * Code Road Map: * -------------- * Code is organised into the following sections. Wherever possible, * methods are classified based on an order of precedence described in * parentheses (..). For example, if you're trying to find a method * 'getName(...)' that is both an interface method and an accessor * method, the order tells you it should appear under interface. * * Order of * Precedence Section * ========== ====== * (1) Section Constants * (2) Section Properties * (3) Section Construction * (7) Section Accessors and Mutators * (6) Section Errors and Validation * (5) Section Interfaces * (4) Section Override * */ public class RIFMapsParameters { private StudyType studyType = StudyType.DISEASE_MAPPING; /* * RIF map parameter */ public static class RIFMapsParameter { private String mapTitle; private String resultsColumn; private String classifierFunctionName; private String columnName; private String colorbrewerPalette; private int numberOfBreaks; private double breaks[]; private Boolean invert; /** * Constructor. * */ public RIFMapsParameter( final String resultsColumn, final String classifierFunctionName, final String colorbrewerPalette, final int numberOfBreaks, final Boolean invert) throws Exception { this.mapTitle = getMapTitle(resultsColumn); this.resultsColumn = resultsColumn; this.classifierFunctionName = classifierFunctionName; this.columnName = getColumnName(resultsColumn); this.colorbrewerPalette = colorbrewerPalette; this.numberOfBreaks = numberOfBreaks; this.invert = invert; } /** * Constructor. * */ public RIFMapsParameter( final String resultsColumn, final String classifierFunctionName, final String colorbrewerPalette, final double[] breaks, final Boolean invert) throws Exception { this.mapTitle = getMapTitle(resultsColumn); this.resultsColumn = resultsColumn; this.classifierFunctionName = classifierFunctionName; this.columnName = getColumnName(resultsColumn); this.colorbrewerPalette = colorbrewerPalette; this.breaks=breaks; this.numberOfBreaks = (breaks.length-1); this.invert = invert; } /** * Accessors */ public String getMapTitle() { return mapTitle; } public String getResultsColumn() { return resultsColumn; } public RIFStyle getRIFStyle(DefaultFeatureCollection featureCollection) { RIFStyle rifStyle=null; if (breaks != null && breaks.length > 0) { // User defined rifStyle=new RIFStyle( classifierFunctionName, columnName, colorbrewerPalette, breaks, invert, featureCollection); } else { // Pre-defined rifStyle=new RIFStyle( classifierFunctionName, columnName, colorbrewerPalette, numberOfBreaks, invert, featureCollection); } return rifStyle; } /** Log RIF parameter * * @param: String mapName */ protected void parameterLog(final String mapName) { rifLogger.info(this.getClass(), mapName + ": " + "; mapTitle: " + mapTitle + "; resultsColumn: " + resultsColumn + "; classifierFunctionName: " + classifierFunctionName + "; columnName: " + columnName + "; colorbrewerPalette: " + colorbrewerPalette + "; numberOfBreaks: " + numberOfBreaks + "; invert: " + invert); } /** get map title * * @param: String feature * * @returns: String */ private String getMapTitle(final String feature) throws Exception { if (feature.toLowerCase().equals("relative_risk")) { return "Relative Risk"; } else if (feature.toLowerCase().equals("smoothed_smr")) { return "Smoothed SMR"; } else if (feature.toLowerCase().equals("posterior_probability")) { return "Posterior Probability"; } else { throw new Exception("getMapTitle() unsupported fature: " + feature); } } /** get column name * * @param: String feature * * @returns: String */ private String getColumnName(final String feature) throws Exception { if (feature.toLowerCase().equals("relative_risk")) { return "rr"; } else if (feature.toLowerCase().equals("smoothed_smr")) { return "sm_smr"; } else if (feature.toLowerCase().equals("posterior_probability")) { return "post_prob"; } else { throw new Exception("getColumnName() unsupported fature: " + feature); } } } // End of RIFMapsParameter() // ========================================== // Section Constants // ========================================== private static final RIFLogger rifLogger = RIFLogger.getLogger(); private static String lineSeparator = System.getProperty("line.separator"); private static double atlasProbabilityBreaks[] = {0.0, 0.20, 0.81, 1.0}; private static double atlasRelativeRiskBreaks[] = {Double.NEGATIVE_INFINITY, 0.68, 0.76, 0.86, 0.96, 1.07, 1.2, 1.35, 1.51, Double.POSITIVE_INFINITY}; private HashMap<String, RIFMapsParameter> rifMapsParameters = new HashMap<String, RIFMapsParameter>(); // ========================================== // Section Properties // ========================================== // ========================================== // Section Construction // ========================================== /** * Constructor. * */ public RIFMapsParameters(final SQLManager manager, final CachedRowSet rif40Studies) { try { setupDefaultMapParameters(manager, rif40Studies); retrieveFrontEndParameters(manager, rif40Studies); } catch(StackOverflowError stackOverflowError) { rifLogger.warning(this.getClass(), "Comment remover caused StackOverflowError", stackOverflowError); throw new NullPointerException(); } catch(Exception exception) { rifLogger.warning(this.getClass(), "Error in RIFMapsParameters() constructor", exception); throw new NullPointerException(); } } /** Accessor: get RIFMapsParameter for key * * @param: String key * * @returns: RIFMapsParameter */ public RIFMapsParameter getRIFMapsParameter(String key) { return rifMapsParameters.get(key); } /** Accessor: get key set * * @returns: Set<String> */ public Set<String> getKeySet() { Set<String> keySet = rifMapsParameters.keySet(); return keySet; } /** * Setup default map parameters */ private void setupDefaultMapParameters(final SQLManager manager, final CachedRowSet rif40Studies) throws Exception { String studyID=manager.getColumnFromResultSet(rif40Studies, "study_id"); String selectStateText=manager.getColumnFromResultSet(rif40Studies, "select_state", true /* allowNulls */, false /* allowNoRows */); if (selectStateText != null) { JSONObject selectStateJson = new JSONObject(selectStateText); // Check it parses OK String studyTypeStr = selectStateJson.optString("studyType"); if (studyTypeStr != null && studyTypeStr.equals(StudyType.RISK_ANALYSIS.type())) { rifLogger.info(getClass(), "rif40_studies.study_id: " + studyID + "; use database select state study type: risk analysis"); this.studyType = StudyType.RISK_ANALYSIS; } else if (studyType != null && studyType.equals(StudyType.DISEASE_MAPPING.type())) { rifLogger.info(getClass(), "rif40_studies.study_id: " + studyID + "; use database select state study type: disease mapping"); this.studyType = StudyType.DISEASE_MAPPING; } else { rifLogger.info(getClass(), "rif40_studies.study_id: " + studyID + "; no database select state study type, assume: disease_mapping;" + lineSeparator + "; selectStateJson: " + selectStateJson.toString(2)); } } else { rifLogger.info(getClass(), "rif40_studies.study_id: " + studyID + "; no database select state, assume study type: disease_mapping"); } RIFMapsParameter rifMapsParameter1 = new RIFMapsParameter( "relative_risk" /* resultsColumn */, "quantile" /* Classifier function name */, "PuOr" /* colorbrewer palette: http://colorbrewer2.org/#type=diverging&scheme=PuOr&n=8 */, 9 /* numberOfBreaks */, true /* invert */); rifMapsParameters.put("viewermap", rifMapsParameter1); if (this.studyType == StudyType.DISEASE_MAPPING) { // No Bayesian smoothing in risk analysis studies RIFMapsParameter rifMapsParameter2 = new RIFMapsParameter( "smoothed_smr" /* resultsColumn */, "quantile" /* Classifier function name */, "PuOr" /* colorbrewer palette: http://colorbrewer2.org/#type=diverging&scheme=PuOr&n=8 */, 9 /* numberOfBreaks */, true /* invert */); rifMapsParameters.put("diseasemap1", rifMapsParameter2); RIFMapsParameter rifMapsParameter3 = new RIFMapsParameter( "posterior_probability" /* resultsColumn */, "AtlasProbability" /* Classifier function name */, "RdYlGn" /* colorbrewer palette: http://colorbrewer2.org/#type=diverging&scheme=PuOr&n=8 */, atlasProbabilityBreaks /* breaks */, false /* invert */); rifMapsParameters.put("diseasemap2", rifMapsParameter3); } } /** * Retrieve front end parameters */ private void retrieveFrontEndParameters(final SQLManager manager, final CachedRowSet rif40Studies) throws Exception { String studyID=manager.getColumnFromResultSet(rif40Studies, "study_id"); String printState=manager.getColumnFromResultSet(rif40Studies, "print_state", true /* allowNulls */, false /* allowNoRows */); BufferedReader reader = AppFile.getServicesInstance(AppFile.FRONT_END_PARAMETERS_FILE).reader(); Json5Parse frontEndJson5Parse = new Json5Parse(reader); JSONObject frontEndJson = frontEndJson5Parse.toJson(); // Check it parses OK JSONObject parametersJson = frontEndJson.optJSONObject("parameters"); JSONObject printStateJson = null; // rifLogger.info(getClass(), "Retrieve FrontEnd Parameters: " + frontEndJson.toString(2)); if (parametersJson == null) { throw new RIFServiceException( RIFServiceError.JSON_PARSE_ERROR, "retrieveFrontEndParameters json parse error: missing \"parameters\" key for rif40_studies.study_id: " + studyID + " update"); } printStateJson = parametersJson.optJSONObject("mappingDefaults"); if (printStateJson == null) { throw new RIFServiceException( RIFServiceError.JSON_PARSE_ERROR, "retrieveFrontEndParameters json parse error: missing \"mappingDefaults\" key for rif40_studies.study_id: " + studyID + " update"); } if (printState != null) { printStateJson = new JSONObject(printState); // Check it parses OK if (printStateJson == null) { throw new RIFServiceException( RIFServiceError.JSON_PARSE_ERROR, "retrieveFrontEndParameters json parse error unable to pare print_state for rif40_studies.study_id: " + studyID + " update" + "; print_state: " + printState); } rifLogger.info(getClass(), "rif40_studies.study_id: " + studyID + "; use database print state: " + printStateJson.toString(2)); } else { rifLogger.info(getClass(), "rif40_studies.study_id: " + studyID + "; use FrontEnd Parameters print state: " + printStateJson.toString(2)); } parseJson(printStateJson, studyID); // Call internal RIF parser } /** * Parse JSON from frontEndParameters/database print_state JSON5 file * * @param: JSONObject json * * Expecting three keys: viewermap, diseasemap1, diseasemap2 */ private void parseJson(final JSONObject printStateJson, final String studyID) { Iterator<String> keys = printStateJson.keys(); while (keys.hasNext()) { String mapName = keys.next(); JSONObject mapOptions = printStateJson.optJSONObject(mapName); /* 'diseasemap1': { method: 'quantile', feature: 'smoothed_smr', intervals: 9, invert: true, brewerName: "PuOr" } */ if (mapOptions != null) { String method=mapOptions.optString("method"); String feature=mapOptions.optString("feature"); int intervals=(int)mapOptions.optLong("intervals"); String invertString=mapOptions.optString("invert"); boolean invert=false; if (invertString.toUpperCase().equals("TRUE")) { invert=true; } String brewerName=mapOptions.optString("brewerName"); JSONArray breaksArray = mapOptions.optJSONArray("breaks"); if ((studyType == StudyType.RISK_ANALYSIS && feature.equals("relative_risk")) || (studyType == StudyType.DISEASE_MAPPING)) { if (breaksArray != null) { // User defined intervals=(breaksArray.length()-1); double[] breaks = new double[intervals+1]; for (int i = 0; i < breaksArray.length(); i++) { breaks[i]=breaksArray.getDouble(i); } try { RIFMapsParameter rifMapsParameter = new RIFMapsParameter( feature /* resultsColumn */, method /* User style name */, brewerName /* colorbrewer palette: http://colorbrewer2.org/#type=diverging&scheme=PuOr&n=8 */, breaks /* Breaks */, invert /* invert */); rifMapsParameters.put(mapName, rifMapsParameter); rifMapsParameter.parameterLog(mapName); } catch (Exception exception) { rifLogger.warning(this.getClass(), "Unable to parse user defined mapOptions from: " + mapOptions.toString(2)); } } else { // Predefined try { RIFMapsParameter rifMapsParameter = new RIFMapsParameter( feature /* resultsColumn */, method /* Classifier function name */, brewerName /* colorbrewer palette: http://colorbrewer2.org/#type=diverging&scheme=PuOr&n=8 */, intervals /* numberOfBreaks */, invert /* invert */); rifMapsParameters.put(mapName, rifMapsParameter); rifMapsParameter.parameterLog(mapName); } catch (Exception exception) { rifLogger.warning(this.getClass(), "Unable to parse predefined mapOptions from: " + mapOptions.toString(2) + "; for rif40_studies.study_id: " + studyID); } } } else { rifLogger.info(this.getClass(), "Risk Analysis feature disabled: " + feature); } } } } }
lgpl-3.0
learn-postspectacular/processing-paris-2010
src/memorytree/day1/ContentLoader.java
2325
/* * This file is part of The Memory Tree/ProcessingParis project. * * Copyright 2010 Karsten Schmidt (PostSpectacular Ltd.) * * MemoryTree 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. * * MemoryTree 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 MemoryTree. If not, see <http://www.gnu.org/licenses/>. */ package memorytree.day1; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import processing.core.PApplet; import processing.core.PImage; import toxi.data.feeds.AtomEntry; import toxi.data.feeds.AtomFeed; import toxi.data.feeds.AtomLink; public class ContentLoader extends Thread { private String feedURL; private PApplet app; private List<ContentListener> listeners = new ArrayList<ContentListener>(); public ContentLoader(PApplet app, String url) { this.app = app; this.feedURL = url; } public void addListener(ContentListener l) { listeners.add(l); } @Override public void run() { AtomFeed feed = AtomFeed.newFromURL(feedURL); if (feed != null) { Iterator<AtomEntry> iterator = feed.iterator(); while (true) { if (!iterator.hasNext()) { iterator = feed.iterator(); } AtomEntry entry = iterator.next(); List<AtomLink> enclosures = entry.getEnclosuresForType("image/jpeg"); if (enclosures != null) { PImage img = app.loadImage(enclosures.get(0).href); if (img != null) { // notify all listeners about new image for (ContentListener l : listeners) { l.newImageLoaded(img); } } } } } } }
lgpl-3.0
dnacreative/records-management
rm-server/source/java/org/alfresco/module/org_alfresco_module_rm/classification/SecurityClearanceServiceImpl.java
10710
/* * Copyright (C) 2005-2015 Alfresco Software Limited. * * This file is part of Alfresco * * Alfresco 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 3 of the License, or * (at your option) any later version. * * Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>. */ package org.alfresco.module.org_alfresco_module_rm.classification; import static org.alfresco.module.org_alfresco_module_rm.classification.ClearanceLevelManager.NO_CLEARANCE; import static org.alfresco.module.org_alfresco_module_rm.classification.model.ClassifiedContentModel.ASPECT_SECURITY_CLEARANCE; import static org.alfresco.module.org_alfresco_module_rm.classification.model.ClassifiedContentModel.PROP_CLEARANCE_LEVEL; import static org.alfresco.module.org_alfresco_module_rm.util.RMParameterCheck.checkNotBlank; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.alfresco.module.org_alfresco_module_rm.classification.ClassificationException.LevelIdNotFound; import org.alfresco.module.org_alfresco_module_rm.util.ServiceBaseImpl; import org.alfresco.query.PagingRequest; import org.alfresco.query.PagingResults; import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.security.PersonService; import org.alfresco.service.cmr.security.PersonService.PersonInfo; import org.alfresco.util.Pair; import org.alfresco.util.ParameterCheck; /** * @author Neil Mc Erlean * @author David Webster * @since 3.0.a */ public class SecurityClearanceServiceImpl extends ServiceBaseImpl implements SecurityClearanceService { /** The clearance levels currently configured in this server. */ private ClearanceLevelManager clearanceManager; /** The object containing the {@link ClassificationLevel}s in the system. */ private ClassificationLevelManager classificationLevelManager; private PersonService personService; private ClassificationServiceBootstrap classificationServiceBootstrap; private ClassificationLevelComparator classificationLevelComparator; public void setClearanceManager(ClearanceLevelManager clearanceManager) { this.clearanceManager = clearanceManager; } public void setClassificationLevelManager(ClassificationLevelManager classificationLevelManager) { this.classificationLevelManager = classificationLevelManager; } public void setPersonService(PersonService service) { this.personService = service; } public void setClassificationServiceBootstrap(ClassificationServiceBootstrap classificationServiceBootstrap) { this.classificationServiceBootstrap = classificationServiceBootstrap; } public void setClassificationLevelComparator(ClassificationLevelComparator classificationLevelComparator) { this.classificationLevelComparator = classificationLevelComparator; } /** Store the references to the classification and clearance level managers in this class. */ public void init() { this.classificationLevelManager = classificationServiceBootstrap.getClassificationLevelManager(); this.clearanceManager = classificationServiceBootstrap.getClearanceLevelManager(); classificationLevelComparator = new ClassificationLevelComparator(classificationLevelManager); } @Override public SecurityClearance getUserSecurityClearance() { if (authenticationUtil.isRunAsUserTheSystemUser()) { return new SecurityClearance(null, clearanceManager.getMostSecureLevel()); } final String currentUser = authenticationUtil.getRunAsUser(); ParameterCheck.mandatoryString("currentUser", currentUser); return getUserSecurityClearance(currentUser); } /** * Gets the user's security clearance. * * @param userName user name * @return {@link SecurityClearance} provides information about the user and their clearance level */ private SecurityClearance getUserSecurityClearance(final String userName) { final NodeRef personNode = personService.getPerson(userName, false); final PersonInfo personInfo = personService.getPerson(personNode); ClearanceLevel clearanceLevel = ClearanceLevelManager.NO_CLEARANCE; if (nodeService.hasAspect(personNode, ASPECT_SECURITY_CLEARANCE)) { final String clearanceLevelId = (String)nodeService.getProperty(personNode, PROP_CLEARANCE_LEVEL); clearanceLevel = (clearanceLevelId == null ? ClearanceLevelManager.NO_CLEARANCE : clearanceManager.findLevelByClassificationLevelId(clearanceLevelId)); } return new SecurityClearance(personInfo, clearanceLevel); } @Override public PagingResults<SecurityClearance> getUsersSecurityClearance(UserQueryParams queryParams) { final PagingRequest pagingRequest = new PagingRequest(queryParams.getSkipCount(), queryParams.getMaxItems()); // We want an accurate count of how many users there are in the system (in this query). // Else paging in the UI won't work properly. pagingRequest.setRequestTotalCountMax(Integer.MAX_VALUE); final PagingResults<PersonInfo> p = personService.getPeople(queryParams.getSearchTerm(), queryParams.getFilterProps(), queryParams.getSortProps(), pagingRequest); return new PagingResults<SecurityClearance>() { @Override public List<SecurityClearance> getPage() { List<SecurityClearance> pcPage= new ArrayList<>(p.getPage().size()); for (PersonInfo pi : p.getPage()) { pcPage.add(getUserSecurityClearance(pi.getUserName())); } return pcPage; } @Override public boolean hasMoreItems() { return p.hasMoreItems(); } @Override public Pair<Integer, Integer> getTotalResultCount() { return p.getTotalResultCount(); } @Override public String getQueryExecutionId() { return p.getQueryExecutionId(); } }; } @Override public boolean isCurrentUserClearedForClassification(String classificationId) { // Get the current user's security clearance. SecurityClearance securityClearance = getUserSecurityClearance(); ClassificationLevel suppliedLevel; try { suppliedLevel = classificationLevelManager.findLevelById(classificationId); } catch(LevelIdNotFound e) { // Return false to make "Level not found" indistinguishable from "Not cleared". return false; } ClassificationLevel usersHighestLevel = securityClearance.getClearanceLevel().getHighestClassificationLevel(); int comparison = classificationLevelComparator.compare(usersHighestLevel, suppliedLevel); return (comparison >= 0); } @Override public SecurityClearance setUserSecurityClearance(String userName, String clearanceId) { ParameterCheck.mandatoryString("userName", userName); ParameterCheck.mandatoryString("clearanceId", clearanceId); final NodeRef personNode = personService.getPerson(userName, false); // Check the current user has clearance to see the specified level. if (!isCurrentUserClearedForClassification(clearanceId)) { throw new LevelIdNotFound(clearanceId); } nodeService.setProperty(personNode, PROP_CLEARANCE_LEVEL, clearanceId); return getUserSecurityClearance(userName); } @Override public List<ClearanceLevel> getClearanceLevels() { if (clearanceManager == null) { return Collections.emptyList(); } // FIXME Currently assume user has highest security clearance, this should be fixed as part of RM-2112. ClearanceLevel usersLevel = clearanceManager.getMostSecureLevel(); return restrictList(clearanceManager.getClearanceLevels(), usersLevel); } /** * Create a list containing all clearance levels up to and including the supplied level. * * @param allLevels The list of all the clearance levels starting with the highest security. * @param targetLevel The highest security clearance level that should be returned. If this is not found then * an empty list will be returned. * @return an immutable list of the levels that a user at the target level can see. */ private List<ClearanceLevel> restrictList(List<ClearanceLevel> allLevels, ClearanceLevel targetLevel) { int targetIndex = allLevels.indexOf(targetLevel); if (targetIndex == -1) { return Collections.emptyList(); } List<ClearanceLevel> subList = allLevels.subList(targetIndex, allLevels.size()); return Collections.unmodifiableList(subList); } /** * @see org.alfresco.module.org_alfresco_module_rm.classification.SecurityClearanceService#hasCurrentUserClearance() */ @Override public boolean hasCurrentUserClearance() { return hasUserClearance(authenticationUtil.getRunAsUser()); } /** * @see org.alfresco.module.org_alfresco_module_rm.classification.SecurityClearanceService#hasUserClearance(java.lang.String) */ @Override public boolean hasUserClearance(String userId) { checkNotBlank("userId", userId); boolean hasUserClearance = false; ClearanceLevel userCleranceLevel = getUserSecurityClearance(userId).getClearanceLevel(); if (userCleranceLevel != null && userCleranceLevel != NO_CLEARANCE) { hasUserClearance = true; } return hasUserClearance; } }
lgpl-3.0
Predictly/axel
shs/shs-broker/shs-agreement-mongodb/src/test/java/se/inera/axel/shs/broker/agreement/mongo/MongoAgreementServiceIT.java
2575
/** * Copyright (C) 2013 Inera AB (http://www.inera.se) * * This file is part of Inera Axel (http://code.google.com/p/inera-axel). * * Inera Axel 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 3 of the License, or * (at your option) any later version. * * Inera Axel 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 program. If not, see <http://www.gnu.org/licenses/> */ package se.inera.axel.shs.broker.agreement.mongo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.util.ReflectionTestUtils; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import se.inera.axel.shs.xml.agreement.ObjectFactory; import se.inera.axel.shs.xml.agreement.ShsAgreement; @ContextConfiguration(classes = MongoDBTestContextConfig.class) public class MongoAgreementServiceIT extends AbstractAgreementIT { @Autowired private MongoShsAgreementRepository repository; @Autowired private AgreementAssembler assembler; private MongoAgreementAdminService agreementAdminService; @Test(enabled=true) public void testMongoAgreementService() { ShsAgreement agreement = agreementAdminService.findOne("123456789"); Assert.assertEquals(agreement.getUuid(), "123456789"); } @BeforeMethod public void beforeMethod() { } @AfterMethod public void afterMethod() { } @BeforeClass public void beforeClass() { ObjectFactory objectFactory = new ObjectFactory(); ShsAgreement agreement = objectFactory.createShsAgreement(); agreement.setUuid("123456789"); repository.save(assembler.assembleMongoShsAgreement(agreement)); agreementAdminService = new MongoAgreementAdminService(); Assert.assertNotNull(repository); ReflectionTestUtils.setField(agreementAdminService, "mongoShsAgreementRepository", repository); ReflectionTestUtils.setField(agreementAdminService, "assembler", assembler); } @AfterClass public void afterClass() { } }
lgpl-3.0
wax911/AniTrendApp
app/src/main/java/com/mxt/anitrend/model/entity/anilist/meta/FormatStats.java
1012
package com.mxt.anitrend.model.entity.anilist.meta; import android.os.Parcel; import android.os.Parcelable; @Deprecated public class FormatStats implements Parcelable { private String format; private int amount; protected FormatStats(Parcel in) { format = in.readString(); amount = in.readInt(); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(format); dest.writeInt(amount); } @Override public int describeContents() { return 0; } public static final Creator<FormatStats> CREATOR = new Creator<FormatStats>() { @Override public FormatStats createFromParcel(Parcel in) { return new FormatStats(in); } @Override public FormatStats[] newArray(int size) { return new FormatStats[size]; } }; public String getFormat() { return format; } public int getAmount() { return amount; } }
lgpl-3.0
sporniket/game
core/src/main/java/com/sporniket/libre/game/input/KeyboardEventPhysical.java
386
/** * */ package com.sporniket.libre.game.input; /** * {@link KeyboardEvent} for a physical event (physical key press/release). * * @author dsporn * */ public class KeyboardEventPhysical extends KeyboardEvent { final Key myKey; public KeyboardEventPhysical(InputTranslator source, Key key) { super(source); myKey = key; } public Key getKey() { return myKey; } }
lgpl-3.0
BtoBastian/Javacord
javacord-api/src/main/java/org/javacord/api/listener/server/ServerChangeRulesChannelListener.java
671
package org.javacord.api.listener.server; import org.javacord.api.event.server.ServerChangeRulesChannelEvent; import org.javacord.api.listener.GloballyAttachableListener; import org.javacord.api.listener.ObjectAttachableListener; /** * This listener listens to server rules channel changes. */ @FunctionalInterface public interface ServerChangeRulesChannelListener extends ServerAttachableListener, GloballyAttachableListener, ObjectAttachableListener { /** * This method is called every time a server's rules channel changed. * * @param event The event. */ void onServerChangeRulesChannel(ServerChangeRulesChannelEvent event); }
lgpl-3.0
cismet/cids-custom-wrrl-db-mv
src/main/java/de/cismet/cids/gaeb/xsd/types/Tgspan.java
2770
/*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.11.23 at 11:39:14 AM CET // package de.cismet.cids.gaeb.xsd.types; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * Teilabschnitt in formatiertem Text. * * <p>Java class for tgspan complex type.</p> * * <p>The following schema fragment specifies the expected content contained within this class.</p> * * <pre> &lt;complexType name="tgspan"> &lt;simpleContent> &lt;extension base="&lt;http://www.gaeb.de/GAEB_DA_XML/200407>tgNormalizedString"> &lt;attribute name="style" type="{http://www.gaeb.de/GAEB_DA_XML/200407}tgAttStyle" /> &lt;/extension> &lt;/simpleContent> &lt;/complexType> * </pre> * * @version $Revision$, $Date$ */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType( name = "tgspan", propOrder = { "value" } ) public class Tgspan { //~ Instance fields -------------------------------------------------------- @XmlValue @XmlJavaTypeAdapter(NormalizedStringAdapter.class) protected String value; @XmlAttribute(name = "style") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) protected String style; //~ Methods ---------------------------------------------------------------- /** * Einzeilige Zeichenkette ohne Längenbegrenzung. * * @return possible object is {@link String } */ public String getValue() { return value; } /** * Sets the value of the value property. * * @param value allowed object is {@link String } */ public void setValue(final String value) { this.value = value; } /** * Gets the value of the style property. * * @return possible object is {@link String } */ public String getStyle() { return style; } /** * Sets the value of the style property. * * @param value allowed object is {@link String } */ public void setStyle(final String value) { this.style = value; } }
lgpl-3.0
STAMP-project/dspot
dspot/src/main/java/eu/stamp_project/dspot/common/configuration/options/AutomaticBuilderEnum.java
951
package eu.stamp_project.dspot.common.configuration.options; import eu.stamp_project.dspot.common.automaticbuilder.AutomaticBuilder; import eu.stamp_project.dspot.common.automaticbuilder.gradle.GradleAutomaticBuilder; import eu.stamp_project.dspot.common.automaticbuilder.maven.MavenAutomaticBuilder; import eu.stamp_project.dspot.common.configuration.UserInput; /** * Created by Benjamin DANGLOT * benjamin.danglot@inria.fr * on 03/10/19 */ public enum AutomaticBuilderEnum { Maven() { @Override public AutomaticBuilder getAutomaticBuilder(UserInput configuration) { return new MavenAutomaticBuilder(configuration); } }, Gradle() { @Override public AutomaticBuilder getAutomaticBuilder(UserInput configuration) { return new GradleAutomaticBuilder(configuration); } }; public abstract AutomaticBuilder getAutomaticBuilder(UserInput configuration); }
lgpl-3.0
sing-group/bicycle
src/main/java/es/cnio/bioinfo/bicycle/gatk/ListerFilter.java
15483
/* Copyright 2012 Daniel Gonzalez Peña, Osvaldo Graña This file is part of the bicycle Project. bicycle Project is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. bicycle Project 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 Public License for more details. You should have received a copy of the GNU Lesser Public License along with bicycle Project. If not, see <http://www.gnu.org/licenses/>. */ package es.cnio.bioinfo.bicycle.gatk; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.broadinstitute.sting.commandline.Argument; import org.broadinstitute.sting.gatk.GenomeAnalysisEngine; import org.broadinstitute.sting.gatk.filters.ReadFilter; import org.broadinstitute.sting.utils.pileup.PileupElement; import org.broadinstitute.sting.utils.pileup.PileupElementFilter; import org.broadinstitute.sting.utils.pileup.ReadBackedPileup; import net.sf.samtools.CigarElement; import net.sf.samtools.CigarOperator; import net.sf.samtools.SAMRecord; import net.sf.samtools.TextCigarCodec; public class ListerFilter extends ReadFilter { @Argument(doc = "control genome for error computation", required = false) public int trimUntil = 4; public static boolean trim = false; @Argument(doc = "remove bad bisulfited", required = false) public boolean removeBad = false; @Argument(doc = "remove ambigous read using tagged reads with ZA flag", required = false) public boolean removeAmbiguous = false; @Argument(doc = "keep only reads with more than one alignment", required = false) public boolean onlyWithOneAlignment = false; public static char TRIMMED_BASE = 'X'; public Pattern watson = Pattern.compile(".*[Cc][^Gg].*[Cc][^Gg].*[Cc][^Gg].*[Cc][^Gg].*"); public Pattern crick = Pattern.compile(".*[^Cc][Gg].*[^Cc][Gg].*[^Cc][Gg].*[^Cc][Gg].*"); private GenomeAnalysisEngine engine; @Argument(doc = "ignore bases with less depth of coverage") public static int mindepth = 1; // counters private long unmmapedReadsCounter = 0; private long withMoreThanOneAlignmentCounter = 0; private long ambiguousReadCounter = 0; private long trimmedCounter = 0; private long badBisulfitedCounter = 0; private long processedReadsCounter = 0; private ThreadLocal<Boolean> freezeCountersInThread = new ThreadLocal<>(); public void freezeCountersInThread() { this.freezeCountersInThread.set(true); } public void unfreezeCountersInThread() { this.freezeCountersInThread.set(false); } public void resetCounters() { this.processedReadsCounter = 0; this.unmmapedReadsCounter = 0; this.withMoreThanOneAlignmentCounter = 0; this.ambiguousReadCounter = 0; this.trimmedCounter = 0; this.badBisulfitedCounter = 0; } public long getUnmmapedReadsCounter() { return unmmapedReadsCounter; } public long getWithMoreThanOneAlignmentCounter() { return withMoreThanOneAlignmentCounter; } public long getAmbiguousReadCounter() { return ambiguousReadCounter; } public long getBadBisulfitedCounter() { return badBisulfitedCounter; } public long getProcessedReadsCounter() { return processedReadsCounter; } public long getTrimmedCounter() { return trimmedCounter; } @Override public void initialize(GenomeAnalysisEngine engine) { this.engine = engine; } private Set<List<StackTraceElement>> stackTraces = new HashSet<>(); @Override public boolean filterOut(SAMRecord record) { if (this.freezeCountersInThread.get() == null) { this.freezeCountersInThread.set(false); } //remove reads with two or more alignments if (this.freezeCountersInThread.get() == false) this.processedReadsCounter ++; if (record.getReadUnmappedFlag()) { if (this.freezeCountersInThread.get() == false) this.unmmapedReadsCounter++; System.err.println("UNMAPPED READ!"); System.exit(1); return false; } if (onlyWithOneAlignment) { // bowtie 1 if (record.getHeader().getProgramRecord("Bowtie") != null) { if (record.getAttribute("XM") != null && ((Integer) record.getAttribute("XM")) > 1) { if (this.freezeCountersInThread.get() == false) this.withMoreThanOneAlignmentCounter++; return true; } } // bowtie 2 if (record.getHeader().getProgramRecord("bowtie2") != null) { if (record.getAttribute("XS") != null) { if (this.freezeCountersInThread.get() == false) this.withMoreThanOneAlignmentCounter++; return true; } } } //remove ambiguous if (removeAmbiguous) { if (record.getAttribute("ZA") != null && record.getAttribute("ZA").toString().equals("Y")) { if (this.freezeCountersInThread.get() == false) this.ambiguousReadCounter++; return true; } } //trim to x mismatch (trim must be before bad bisulfited) if (trim) { boolean trimmed = trim(record, trimUntil); if (trimmed && this.freezeCountersInThread.get() == false) this.trimmedCounter++; } //bad bisulfited filter if (removeBad) { if (record.getReadGroup().getId().equals("WATSON") && watson.matcher(record.getReadString()).find() || record.getReadGroup().getId().equals("CRICK") && crick.matcher(record.getReadString()).find()) { if (this.freezeCountersInThread.get() == false) this.badBisulfitedCounter++; return true; } } return false; } public static ReadBackedPileup applyFilters(ReadBackedPileup pileup) { if (pileup == null) { return null; } ReadBackedPileup toret = pileup.getFilteredPileup(new PileupElementFilter() { @Override public boolean allow(PileupElement arg0) { for (PileupElementFilter filter : pileupfilters) { if (!filter.allow(arg0)) { return false; } } return true; } }); if (toret.getBases().length < mindepth) { return null; } return toret; } static List<PileupElementFilter> pileupfilters; static { pileupfilters = new LinkedList<PileupElementFilter>(); pileupfilters.add(new PileupElementFilter() { @Override public boolean allow(PileupElement arg0) { if (trim) { if (arg0.getBase() == ListerFilter.TRIMMED_BASE) { return false; } } return true; } }); } private boolean trim(SAMRecord record, int trimMismatches) { record.setAttribute("XT", "true"); String sequenceCT = record.getReadString(); int mismatches = (Integer) record.getAttribute("NM"); if (mismatches >= trimMismatches) { boolean isReverse = record.getReadNegativeStrandFlag(); int currentMismatches = 0; int trimPoint = isReverse ? sequenceCT.length() : 0; CigarIterator cigarIterator = new CigarIterator(record.getCigarString(), isReverse); MDTagIterator mdIterator = new MDTagIterator((String) record.getAttribute("MD"), isReverse); CigarOperator lastCigarOperator = null; while (cigarIterator.hasNext() && currentMismatches < trimMismatches) { CigarOperator operator = cigarIterator.next(); switch (operator) { case M: MDTagOperator mdOperator = mdIterator.next(); if (mdOperator == MDTagOperator.VARIANT) { currentMismatches++; if (currentMismatches < trimMismatches) { trimPoint = trimPoint + (isReverse ? -1 : 1); } } else if (mdOperator == MDTagOperator.SEQUENCE_MATCH) { // do nothing trimPoint = trimPoint + (isReverse ? -1 : 1); } else { //should not happen return false; // do not trim } break; case I: currentMismatches++; if (currentMismatches < trimMismatches) { trimPoint = trimPoint + (isReverse ? -1 : 1); } break; case D: currentMismatches++; mdIterator.next(); break; default: return false; //do not trim this read, since it has non-supported CIGAR operations } lastCigarOperator = operator; } if (currentMismatches >= trimMismatches) { if (isReverse) { //trimPoint ++; //trim the last mismatch record.setReadString(record.getReadString().substring(0, trimPoint).replaceAll(".", "" + TRIMMED_BASE) + record.getReadString().substring(trimPoint)); } else { //trimPoint --; //trim the last mismatch record.setReadString(record.getReadString().substring(0, trimPoint) + record.getReadString() .substring (trimPoint).replaceAll(".", "" + TRIMMED_BASE)); } return true; } } return false; } @Override public String toString() { double ambiguousRatio = (double)this.getAmbiguousReadCounter()/(double)this.getProcessedReadsCounter(); double onlyWithOneAlignmentRatio = (double)this.getWithMoreThanOneAlignmentCounter()/(double)this.getProcessedReadsCounter(); double badBisulfitedRatio = (double)this.getBadBisulfitedCounter()/(double)this .getProcessedReadsCounter(); double trimmedRatio = (double)this.getTrimmedCounter()/(double)this.getProcessedReadsCounter(); return "Mapped reads processed: "+this.getProcessedReadsCounter()+"" + ", remove ambiguous reads: " + this.removeAmbiguous + (this.removeAmbiguous ? " (" + this.getAmbiguousReadCounter() + " removed " + "("+asPercent(ambiguousRatio)+"))" : "") + ", remove with more than one alignment: " + this.onlyWithOneAlignment + (this.onlyWithOneAlignment ? " (" + this.getWithMoreThanOneAlignmentCounter() + " removed " + "("+asPercent(onlyWithOneAlignmentRatio)+"))" : "") + ", remove non-correctly bisulfite-converted reads: " + this.removeBad + (this.removeBad ? " (" + this.getBadBisulfitedCounter() + " removed " + "("+asPercent(badBisulfitedRatio)+"))" : "") + ", trim to 'x' mismatch: " + this.trim + (this.trim ? " x=" + this.trimUntil + " " + this.getTrimmedCounter() + " trimmed " + "("+asPercent(trimmedRatio)+")" :""); } private String asPercent(double decimal) { DecimalFormat fmt = new DecimalFormat("0.00"); return fmt.format(decimal * 100d) + "%"; } protected static class CigarIterator implements Iterator<CigarOperator> { private final boolean reverse; private List<CigarElement> cigarElements; private int currentCigarElementsPos; private int repetitionsOfCurrentOperation = 0; private CigarOperator currentOperator = null; public CigarIterator(String cigar, boolean reverse) { this.cigarElements = new ArrayList(TextCigarCodec.getSingleton().decode(cigar).getCigarElements()); this.reverse = reverse; this.currentCigarElementsPos = this.reverse ? cigarElements.size() : -1; this.advanceCigarElement(); } @Override public boolean hasNext() { return repetitionsOfCurrentOperation > 0 || (this.currentCigarElementsPos >= 0 && this.currentCigarElementsPos < this.cigarElements.size()); } @Override public CigarOperator next() { CigarOperator result = this.currentOperator; this.repetitionsOfCurrentOperation--; if (repetitionsOfCurrentOperation == 0 && (this.currentCigarElementsPos >= 0 && this .currentCigarElementsPos < this.cigarElements.size())) { advanceCigarElement(); } return result; } private void advanceCigarElement() { this.currentCigarElementsPos = this.currentCigarElementsPos + (this.reverse ? -1 : 1); if (this.currentCigarElementsPos >= 0 && this.currentCigarElementsPos < this.cigarElements.size()) { CigarElement element = this.cigarElements.get(this.currentCigarElementsPos); this.repetitionsOfCurrentOperation = element.getLength(); this.currentOperator = element.getOperator(); } } } protected enum MDTagOperator { DELETION, SEQUENCE_MATCH, VARIANT } protected static abstract class MDTagOperation { public abstract int getLength(); public abstract MDTagOperator getOperator(); } protected static class SequenceMatchOperation extends MDTagOperation { int length; public SequenceMatchOperation(int length) { this.length = length; } @Override public int getLength() { return length; } @Override public MDTagOperator getOperator() { return MDTagOperator.SEQUENCE_MATCH; } } protected static class SequenceVariantOperation extends MDTagOperation { private char allele; public SequenceVariantOperation(char alelle) { this.allele = allele; } @Override public int getLength() { return 1; } @Override public MDTagOperator getOperator() { return MDTagOperator.VARIANT; } } protected static class DeletionOperation extends MDTagOperation { private String deletedBases; public DeletionOperation(String deletedBases) { this.deletedBases = deletedBases; } public String getDeletedBases() { return deletedBases; } @Override public int getLength() { return deletedBases.length(); } @Override public MDTagOperator getOperator() { return MDTagOperator.DELETION; } } protected static class MDTagIterator implements Iterator<MDTagOperator> { static final Pattern mdPat = Pattern.compile("\\G(?:([0-9]+)|([ACTGNactgn])|(\\^[ACTGNactgn]+))"); private final boolean reverse; private List<MDTagOperation> mdOperations; private int currentMDOperationsPos; private int repetitionsOfCurrentOperation = 0; private MDTagOperator currentOperator = null; private List<MDTagOperation> decodeMDTag(String mdString) { Matcher matcher = mdPat.matcher(mdString); ArrayList result = new ArrayList<>(); while (matcher.find()) { if (matcher.group(1) != null) { // match int length = Integer.parseInt(matcher.group(1)); if (length > 0) { result.add(new SequenceMatchOperation(Integer.parseInt(matcher.group(1)))); } } else if (matcher.group(2) != null) { // variant result.add(new SequenceVariantOperation(matcher.group(2).charAt(0))); } else if (matcher.group(3) != null) { // deletion result.add(new DeletionOperation(matcher.group(3).substring(1))); } } return result; } public MDTagIterator(String mdString, boolean reverse) { this.mdOperations = decodeMDTag(mdString); this.reverse = reverse; this.currentMDOperationsPos = this.reverse ? mdOperations.size() : -1; this.advanceMDOperation(); } @Override public boolean hasNext() { return repetitionsOfCurrentOperation > 0 || (this.currentMDOperationsPos >= 0 && this.currentMDOperationsPos < this.mdOperations.size()); } @Override public MDTagOperator next() { MDTagOperator result = this.currentOperator; this.repetitionsOfCurrentOperation--; if (repetitionsOfCurrentOperation == 0 && (this.currentMDOperationsPos >= 0 && this .currentMDOperationsPos < this.mdOperations.size())) { advanceMDOperation(); } return result; } private void advanceMDOperation() { this.currentMDOperationsPos = this.currentMDOperationsPos + (this.reverse ? -1 : 1); if (this.currentMDOperationsPos >= 0 && this.currentMDOperationsPos < this.mdOperations.size()) { MDTagOperation element = this.mdOperations.get(this.currentMDOperationsPos); this.repetitionsOfCurrentOperation = element.getLength(); this.currentOperator = element.getOperator(); } } } }
lgpl-3.0
ArticulatedSocialAgentsPlatform/HmiCore
HmiNeurophysics/src/hmi/neurophysics/EyeSaturation.java
3556
/******************************************************************************* * Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands * * This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer). * * ASAPRealizer is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License (LGPL) as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ASAPRealizer 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 Lesser General Public License * along with ASAPRealizer. If not, see http://www.gnu.org/licenses/. ******************************************************************************/ package hmi.neurophysics; import hmi.math.Quat4f; import hmi.math.Vec4f; /** * Ensures that the eye stays within its rotation bounds. Theoretical background:<br> * Tweed, D. (1997). Three-dimensional model of the human eye-head saccadic system. <br> * The Journal of Neurophysiology, 77 (2), pp. 654-666.<br> * @author Herwin van Welbergen */ public final class EyeSaturation { private EyeSaturation() { } private static final float RADIUS = 0.12f; public static boolean isSaturized(float[] q) { float alpha = q[Quat4f.x] * q[Quat4f.x] + q[Quat4f.y] * q[Quat4f.y]; float maxTorsion = 0.25f * (float) Math.sqrt(0.15f - alpha); return (alpha < RADIUS * RADIUS && Math.abs(q[Quat4f.z]) < maxTorsion); } /** * Saturizes eye position * * @param qCurDes current desired eye position * @param qDes desired end position of the eye (after the head is moved as well), assumed to be saturized * @param result saturized eye pos */ public static void sat(float[] qCurDes, float[] qDes, float[] result) { float alpha = qCurDes[Quat4f.x] * qCurDes[Quat4f.x] + qCurDes[Quat4f.y] * qCurDes[Quat4f.y]; Quat4f.set(result, qCurDes); if (alpha > RADIUS * RADIUS) { float beta = qCurDes[Quat4f.x] * qDes[Quat4f.x] + qCurDes[Quat4f.y] * qDes[Quat4f.y]; float gamma = qDes[Quat4f.x] * qDes[Quat4f.x] + qDes[Quat4f.y] * qDes[Quat4f.y]; float a = alpha - 2 * beta + gamma; float b = 2 * (alpha - beta); float c = alpha - (RADIUS * RADIUS); float D = b * b - 4 * a * c; if (D < 0) D = 0; float x = (-b + (float) Math.sqrt(D)) / (2 * a); result[Quat4f.x] -= qDes[Quat4f.x]; result[Quat4f.y] -= qDes[Quat4f.y]; result[Quat4f.z] -= qDes[Quat4f.z]; Vec4f.scale(x, result); Quat4f.add(result, qCurDes); alpha = RADIUS * RADIUS; } float maxTorsion = 0.25f * (float) Math.sqrt(0.15f - alpha); if (Math.abs(result[Quat4f.z]) > maxTorsion) { result[Quat4f.z] = Math.signum(result[Quat4f.z]) * maxTorsion; } // normalize result[Quat4f.s] = (float) Math.sqrt(1 - (result[Quat4f.x] * result[Quat4f.x] + result[Quat4f.y] * result[Quat4f.y] + result[Quat4f.z] * result[Quat4f.z])); } }
lgpl-3.0
AuScope/IGSN
src/main/java/org/csiro/igsn/entity/postgres2_0/Sample.java
13851
package org.csiro.igsn.entity.postgres2_0; // Generated 27/10/2015 10:58:13 AM by Hibernate Tools 4.3.1 import java.io.Serializable; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.UniqueConstraint; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; import org.hibernate.annotations.Type; import com.fasterxml.jackson.annotation.JsonIgnore; import com.vividsolutions.jts.geom.Geometry; /** * Sample generated by hbm2java */ @Entity @Table(name = "sample") @NamedQueries({ @NamedQuery( name="Sample.search", query="SELECT s FROM Sample s where s.igsn = :igsn" ), @NamedQuery( name="Sample.searchpublic", query="SELECT s FROM Sample s where s.ispublic = true and s.igsn = :igsn" ) }) public class Sample implements java.io.Serializable { private int sampleid; private CvSamplingmethod cvSamplingmethod; private Registrant registrant; private Status statusByPhysicalsamplestatus; private Status statusByRegistrationstatus; private String samplename; private String othername; private String igsn; private String landingpage; private String classification; private String classificationidentifier; private String purpose; private Geometry samplinglocgeom; private String samplinglocsrs; private String elevation; private String verticaldatum; private String locality; private Date samplingstart; private Date samplingend; private String samplingcampaign; private String comment; private Date created; private Date modified; private Boolean ispublic; private String elevationUnits; private String samplinglocNilreason; private String samplingtimeNilreason; private Set<CvSampletype> cvSampletypes = new HashSet<CvSampletype>(0); private Set<Samplecuration> samplecurations = new HashSet<Samplecuration>(0); private Set<Samplingfeatures> samplingfeatures = new HashSet<Samplingfeatures>( 0); private Set<SampleCollector> sampleCollectors = new HashSet<SampleCollector>( 0); private Set<Sampleresources> sampleresourceses = new HashSet<Sampleresources>( 0); private Set<CvSamplematerial> cvSamplematerials = new HashSet<CvSamplematerial>( 0); public Sample() { } public Sample(Registrant registrant, String samplename, String igsn, String landingpage, Date created) { this.registrant = registrant; this.samplename = samplename; this.igsn = igsn; this.landingpage = landingpage; this.created = created; } public Sample(CvSamplingmethod cvSamplingmethod, Registrant registrant, Status statusByPhysicalsamplestatus, Status statusByRegistrationstatus, String samplename, String othername, String igsn, String landingpage, String classification, String classificationidentifier, String purpose, Geometry samplinglocgeom, String samplinglocsrs, String elevation, String verticaldatum, String locality, Date samplingstart, Date samplingend, String samplingcampaign, String comment, Date created, Date modified, Boolean ispublic, Set<CvSampletype> cvSampletypes, Set<Samplecuration> samplecurations, Set<Samplingfeatures> samplingfeatures, Set<SampleCollector> sampleCollectors, Set<Sampleresources> sampleresourceses, Set<CvSamplematerial> cvSamplematerials, String elevationUnits) { this.cvSamplingmethod = cvSamplingmethod; this.registrant = registrant; this.statusByPhysicalsamplestatus = statusByPhysicalsamplestatus; this.statusByRegistrationstatus = statusByRegistrationstatus; this.samplename = samplename; this.othername = othername; this.igsn = igsn; this.landingpage = landingpage; this.classification = classification; this.classificationidentifier = classificationidentifier; this.purpose = purpose; this.samplinglocgeom = samplinglocgeom; this.samplinglocsrs = samplinglocsrs; this.elevation = elevation; this.verticaldatum = verticaldatum; this.locality = locality; this.samplingstart = samplingstart; this.samplingend = samplingend; this.samplingcampaign = samplingcampaign; this.comment = comment; this.created = created; this.modified = modified; this.ispublic = ispublic; this.cvSampletypes = cvSampletypes; this.samplecurations = samplecurations; this.samplingfeatures = samplingfeatures; this.sampleCollectors = sampleCollectors; this.sampleresourceses = sampleresourceses; this.cvSamplematerials = cvSamplematerials; this.elevationUnits = elevationUnits; } @Id @Column(name = "sampleid", unique = true, nullable = false) @SequenceGenerator(name="sample_sampleid_seq",sequenceName="sample_sampleid_seq", allocationSize=1) @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="sample_sampleid_seq") public int getSampleid() { return this.sampleid; } public void setSampleid(int sampleid) { this.sampleid = sampleid; } @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "samplingmethod") public CvSamplingmethod getCvSamplingmethod() { return this.cvSamplingmethod; } public void setCvSamplingmethod(CvSamplingmethod cvSamplingmethod) { this.cvSamplingmethod = cvSamplingmethod; } @OneToOne(fetch = FetchType.LAZY) @JoinColumn( name = "registrant", referencedColumnName="registrantid") public Registrant getRegistrant() { return this.registrant; } public void setRegistrant(Registrant registrant) { this.registrant = registrant; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "physicalsamplestatus") public Status getStatusByPhysicalsamplestatus() { return this.statusByPhysicalsamplestatus; } public void setStatusByPhysicalsamplestatus( Status statusByPhysicalsamplestatus) { this.statusByPhysicalsamplestatus = statusByPhysicalsamplestatus; } @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "registrationstatus") public Status getStatusByRegistrationstatus() { return this.statusByRegistrationstatus; } public void setStatusByRegistrationstatus(Status statusByRegistrationstatus) { this.statusByRegistrationstatus = statusByRegistrationstatus; } @Column(name = "samplename", nullable = false) public String getSamplename() { return this.samplename; } public void setSamplename(String samplename) { this.samplename = samplename; } @Column(name = "othername") public String getOthername() { return this.othername; } public void setOthername(String othername) { this.othername = othername; } @Column(name = "igsn", unique = true, nullable = false) public String getIgsn() { return this.igsn; } public void setIgsn(String igsn) { this.igsn = igsn; } @Column(name = "landingpage", nullable = false, length = 250) public String getLandingpage() { return this.landingpage; } public void setLandingpage(String landingpage) { this.landingpage = landingpage; } @Column(name = "classification") public String getClassification() { return this.classification; } public void setClassification(String classification) { this.classification = classification; } @Column(name = "classificationidentifier") public String getClassificationidentifier() { return this.classificationidentifier; } public void setClassificationidentifier(String classificationidentifier) { this.classificationidentifier = classificationidentifier; } @Column(name = "purpose") public String getPurpose() { return this.purpose; } public void setPurpose(String purpose) { this.purpose = purpose; } @Column(name = "samplinglocgeom") @Type(type="org.hibernate.spatial.GeometryType") @JsonIgnore public Geometry getSamplinglocgeom() { return this.samplinglocgeom; } public void setSamplinglocgeom(Geometry samplinglocgeom) { this.samplinglocgeom = samplinglocgeom; } @Column(name = "samplinglocsrs", length = 20) public String getSamplinglocsrs() { return this.samplinglocsrs; } public void setSamplinglocsrs(String samplinglocsrs) { this.samplinglocsrs = samplinglocsrs; } @Column(name = "elevation", length = 30) public String getElevation() { return this.elevation; } public void setElevation(String elevation) { this.elevation = elevation; } @Column(name = "verticaldatum", length = 20) public String getVerticaldatum() { return this.verticaldatum; } public void setVerticaldatum(String verticaldatum) { this.verticaldatum = verticaldatum; } @Column(name = "locality", length = 300) public String getLocality() { return this.locality; } public void setLocality(String locality) { this.locality = locality; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "samplingstart", length = 29) public Date getSamplingstart() { return this.samplingstart; } public void setSamplingstart(Date samplingstart) { this.samplingstart = samplingstart; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "samplingend", length = 29) public Date getSamplingend() { return this.samplingend; } public void setSamplingend(Date samplingend) { this.samplingend = samplingend; } @Column(name = "samplingcampaign") public String getSamplingcampaign() { return this.samplingcampaign; } public void setSamplingcampaign(String samplingcampaign) { this.samplingcampaign = samplingcampaign; } @Column(name = "comment") public String getComment() { return this.comment; } public void setComment(String comment) { this.comment = comment; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "created", nullable = false, length = 29) public Date getCreated() { return this.created; } public void setCreated(Date created) { this.created = created; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "modified", length = 29) public Date getModified() { return this.modified; } public void setModified(Date modified) { this.modified = modified; } @Column(name = "ispublic") public Boolean getIspublic() { return this.ispublic; } public void setIspublic(Boolean ispublic) { this.ispublic = ispublic; } @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "sample_types", joinColumns = { @JoinColumn(name = "sampleid", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "sampletypeid", nullable = false, updatable = false) }) public Set<CvSampletype> getCvSampletypes() { return this.cvSampletypes; } public void setCvSampletypes(Set<CvSampletype> cvSampletypes) { this.cvSampletypes = cvSampletypes; } @OneToMany(fetch = FetchType.EAGER, mappedBy = "sample",cascade={CascadeType.ALL},orphanRemoval=true) public Set<Samplecuration> getSamplecurations() { return this.samplecurations; } public void setSamplecurations(Set<Samplecuration> samplecurations) { this.samplecurations = samplecurations; } @ManyToMany(fetch = FetchType.EAGER, cascade={CascadeType.ALL}) @JoinTable(name = "sample_features_mapping", joinColumns = { @JoinColumn(name = "sampleid", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "featureid", nullable = false, updatable = false) }) public Set<Samplingfeatures> getSamplingfeatures() { return this.samplingfeatures; } public void setSamplingfeatures( Set<Samplingfeatures> samplingfeatures) { this.samplingfeatures = samplingfeatures; } @OneToMany(fetch = FetchType.EAGER, mappedBy = "sample",cascade={CascadeType.ALL}, orphanRemoval=true) public Set<SampleCollector> getSampleCollectors() { return this.sampleCollectors; } public void setSampleCollectors(Set<SampleCollector> sampleCollectors) { this.sampleCollectors = sampleCollectors; } @OneToMany(fetch = FetchType.EAGER, mappedBy = "sample", cascade={CascadeType.ALL}, orphanRemoval=true) public Set<Sampleresources> getSampleresourceses() { return this.sampleresourceses; } public void setSampleresourceses(Set<Sampleresources> sampleresourceses) { this.sampleresourceses = sampleresourceses; } @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "sample_material", joinColumns = { @JoinColumn(name = "sampleid", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "materialid", nullable = false, updatable = false) }) public Set<CvSamplematerial> getCvSamplematerials() { return this.cvSamplematerials; } public void setCvSamplematerials(Set<CvSamplematerial> cvSamplematerials) { this.cvSamplematerials = cvSamplematerials; } @Column(name = "elevation_units", length = 100) public String getElevationUnits() { return this.elevationUnits; } public void setElevationUnits(String elevationUnits) { this.elevationUnits = elevationUnits; } @Column(name = "samplingloc_nilreason", length = 100) public String getSamplinglocNilreason() { return samplinglocNilreason; } public void setSamplinglocNilreason(String samplinglocNilreason) { this.samplinglocNilreason = samplinglocNilreason; } @Column(name = "samplingtime_nilreason", length = 100) public String getSamplingtimeNilreason() { return samplingtimeNilreason; } public void setSamplingtimeNilreason(String samplingtimeNilreason) { this.samplingtimeNilreason = samplingtimeNilreason; } }
lgpl-3.0
iChun/Morph
src/main/java/me/ichun/mods/morph/client/entity/EntityAcquisition.java
21684
package me.ichun.mods.morph.client.entity; import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.vertex.IVertexBuilder; import me.ichun.mods.ichunutil.client.render.RenderHelper; import me.ichun.mods.ichunutil.client.tracker.ClientEntityTracker; import me.ichun.mods.ichunutil.common.entity.util.EntityHelper; import me.ichun.mods.morph.client.render.MorphRenderHandler; import me.ichun.mods.morph.common.Morph; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.model.ModelRenderer; import net.minecraft.client.settings.PointOfView; import net.minecraft.client.world.ClientWorld; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityType; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.nbt.CompoundNBT; import net.minecraft.network.IPacket; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.vector.Vector3d; import net.minecraft.util.math.vector.Vector3f; import net.minecraft.world.World; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.fml.network.NetworkHooks; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; @OnlyIn(Dist.CLIENT) public class EntityAcquisition extends Entity { @Nonnull public LivingEntity livingOrigin; @Nonnull public LivingEntity livingAcquired; public boolean isMorphAcquisition; public ArrayList<Tendril> tendrils = new ArrayList<>(); public int maxRequiredTendrils; public int age; public MorphRenderHandler.ModelRendererCapture acquiredCapture = new MorphRenderHandler.ModelRendererCapture(); public EntityAcquisition(EntityType<?> entityTypeIn, World worldIn) { super(entityTypeIn, worldIn); setInvisible(true); setInvulnerable(true); setEntityId(ClientEntityTracker.getNextEntId()); } public EntityAcquisition setTargets(@Nonnull LivingEntity origin, @Nonnull LivingEntity acquired, boolean isMorphAcquisition) { this.livingOrigin = origin; this.livingAcquired = acquired; this.isMorphAcquisition = isMorphAcquisition; syncWithOriginPosition(); if(isMorphAcquisition) { tendrils.add(new Tendril(null).headTowards(getTargetPos(), false)); } return this; } @Override public void tick() { super.tick(); age++; if(!livingOrigin.isAlive() || !livingOrigin.world.getDimensionKey().equals(world.getDimensionKey())) //parent is "dead" { if(livingOrigin.removed) { remove(); } } else if(age > Morph.configClient.acquisitionTendrilMaxChild * 10 + 100) //probably too long, kill it off { remove(); if(livingOrigin instanceof PlayerEntity) { EntityBiomassAbility ability = Morph.EntityTypes.BIOMASS_ABILITY.create(world).setInfo((PlayerEntity)livingOrigin, 10, 0); ((ClientWorld)world).addEntity(ability.getEntityId(), ability); } } else //parent is "alive" and safe { this.setPosition(livingOrigin.getPosX(), livingOrigin.getPosY() + (livingOrigin.getHeight() / 2D), livingOrigin.getPosZ()); this.setRotation(livingOrigin.rotationYaw, livingOrigin.rotationPitch); boolean allDone = !tendrils.isEmpty(); boolean anyRetracting = false; boolean anyNonRetracting = false; for(Tendril tendril : tendrils) { if(!tendril.isDone()) { allDone = false; tendril.tick(); if(tendril.retract) { anyRetracting = true; } else { anyNonRetracting = true; } } else { anyRetracting = true; } } if(isMorphAcquisition) { if(tendrils.size() < 5 && age % 2 == 0) { tendrils.add(new Tendril(null).headTowards(getTargetPos(), false)); allDone = false;//do not remove, we're not done yet } if(anyRetracting && anyNonRetracting) { for(Tendril tendril : tendrils) { tendril.propagateRetractToChild(); } } } else { if(tendrils.size() < maxRequiredTendrils && !acquiredCapture.infos.isEmpty() && age % 3 == 0) { tendrils.add(new Tendril(null).headTowards(getTargetPos(), true)); allDone = false;//do not remove, we're not done yet } } if(allDone) { remove(); if(livingOrigin instanceof PlayerEntity) { EntityBiomassAbility ability = Morph.EntityTypes.BIOMASS_ABILITY.create(world).setInfo((PlayerEntity)livingOrigin, 10, 0); ((ClientWorld)world).addEntity(ability.getEntityId(), ability); } } } } public Vector3d getTargetPos() { return livingAcquired.getPositionVec().add(0D, livingAcquired.getHeight() / 2D, 0D); } @Override public AxisAlignedBB getRenderBoundingBox() { return livingOrigin.getBoundingBox().union(livingAcquired.getBoundingBox()); } @Override public boolean isInRangeToRenderDist(double distance) { return livingOrigin.isInRangeToRenderDist(distance) || livingAcquired.isInRangeToRenderDist(distance); } @Override public float getBrightness() { return livingOrigin.getBrightness(); } @Override protected void registerData(){} @Override public boolean writeUnlessRemoved(CompoundNBT compound) { return false; } //disable saving of entity @Override protected void readAdditional(CompoundNBT compound){} @Override protected void writeAdditional(CompoundNBT compound){} @Override public IPacket<?> createSpawnPacket() { return NetworkHooks.getEntitySpawningPacket(this); } public void syncWithOriginPosition() { double height = (livingOrigin.getHeight() / 2D); this.setLocationAndAngles(livingOrigin.getPosX(), livingOrigin.getPosY() + height, livingOrigin.getPosZ(), livingOrigin.rotationYaw, livingOrigin.rotationPitch); this.lastTickPosX = livingOrigin.lastTickPosX; this.lastTickPosY = livingOrigin.lastTickPosY + height; this.lastTickPosZ = livingOrigin.lastTickPosZ; this.prevPosX = livingOrigin.prevPosX; this.prevPosY = livingOrigin.prevPosY + height; this.prevPosZ = livingOrigin.prevPosZ; } public class Tendril { @Nullable private Tendril parent; //if null, is the base tendril private Tendril child; private Vector3d offset; private float yaw; private float pitch; private float lastHeight = 1F; private float height = 1F; private float maxGrowth = 7F + (float)rand.nextGaussian() * 2F; private boolean retract; private int retractTime; private float prevRotateSpin; private float rotateSpin; private float spinFactor = (float)rand.nextGaussian() * 15F; public int depth = 0; private MorphRenderHandler.ModelRendererCapture capture; public Tendril(Tendril parent) { this.parent = parent; if(parent != null) { this.offset = parent.getReachOffset().subtract(getVectorForRotation(parent.pitch, parent.yaw).mul(0.025F, 0.025F, 0.025F)); this.depth = parent.depth + 1; } else { this.offset = new Vector3d(0D, 0D, 0D); } } public Tendril headTowards(Vector3d pos, boolean rev) { float randGaus = 5F; if(parent != null) { yaw = parent.yaw; pitch = parent.pitch; Vector3d origin = parent.getReachCoord(); double d0 = pos.getX() - origin.getX(); double d1 = pos.getY() - origin.getY(); double d2 = pos.getZ() - origin.getZ(); float maxChange = isMorphAcquisition ? 30F : 60F; double dist = MathHelper.sqrt(d0 * d0 + d2 * d2); float newYaw = (float)(MathHelper.atan2(d2, d0) * (double)(180F / (float)Math.PI)) - 90.0F; float newPitch = (float)(-(MathHelper.atan2(d1, dist) * (double)(180F / (float)Math.PI))); this.pitch = EntityHelper.updateRotation(this.pitch, newPitch, maxChange); this.yaw = EntityHelper.updateRotation(this.yaw, newYaw, maxChange); } else { yaw = (rev ? (livingOrigin.renderYawOffset + 180F) : livingOrigin.renderYawOffset) % 360F; pitch = 0; if(!isMorphAcquisition) { randGaus = 30F; } yaw += (5F + 25F * rand.nextFloat()) * (rand.nextBoolean() ? 1F : -1F); pitch += (float)rand.nextGaussian() * randGaus; } yaw += (float)rand.nextGaussian() * randGaus; pitch += (float)rand.nextGaussian() * randGaus; return this; } public void tick() { lastHeight = height; if(retract) { retractTime++; } if(child != null) { child.tick(); } else { float distToEnt = livingOrigin.getDistance(livingAcquired); if(!isMorphAcquisition) { distToEnt *= 2F; } if(!retract) { if(height < maxGrowth) { float maxTendrilGrowth = Math.max(0.0625F, distToEnt / Morph.configClient.acquisitionTendrilMaxChild + (float)rand.nextGaussian() * 0.125F); //in blocks height += maxTendrilGrowth * 16F; if(getReachCoord().distanceTo(getTargetPos()) < Math.max(0.3F, maxTendrilGrowth)) //close enough? { if(!isMorphAcquisition && age <= 10) { height -= maxTendrilGrowth * 16F; //wait for age to finish return; } child = new Tendril(this); Vector3d pos = getTargetPos(); Vector3d origin = getReachCoord(); double d0 = pos.getX() - origin.getX(); double d1 = pos.getY() - origin.getY(); double d2 = pos.getZ() - origin.getZ(); double dist = MathHelper.sqrt(d0 * d0 + d2 * d2); child.yaw = (float)(MathHelper.atan2(d2, d0) * (double)(180F / (float)Math.PI)) - 90.0F; child.pitch = (float)(-(MathHelper.atan2(d1, dist) * (double)(180F / (float)Math.PI))); child.lastHeight = child.height = (float)MathHelper.sqrt(d0 * d0 + d1 * d1 + d2 * d2) / 16F; if(isMorphAcquisition) { child.capture = acquiredCapture; acquiredCapture = null; } else if(!acquiredCapture.infos.isEmpty()) { child.capture = new MorphRenderHandler.ModelRendererCapture(); int count = (int)Math.ceil(Math.max(acquiredCapture.infos.size() / 10F, 1)); for(int x = 0; x < count && !acquiredCapture.infos.isEmpty(); x++) { int i = rand.nextInt(acquiredCapture.infos.size()); child.capture.infos.add(acquiredCapture.infos.get(i)); acquiredCapture.infos.remove(i); if(x > 0) { maxRequiredTendrils--; } } } child.propagateRetractToParent(); } if(!isMorphAcquisition && acquiredCapture.infos.isEmpty()) //oops we're out of blocks. retract { propagateRetractToParent(); } } else { child = new Tendril(this).headTowards(getTargetPos(), false); } } else if(retractTime <= 3) { float maxTendrilGrowth = Math.max(0.0625F, distToEnt / Morph.configClient.acquisitionTendrilMaxChild + (float)rand.nextGaussian() * 0.125F); //in blocks if(getReachCoord().distanceTo(getTargetPos()) > Math.max(0.5F, maxTendrilGrowth)) { Vector3d pos = getTargetPos(); Vector3d origin = getReachCoord(); double d0 = pos.getX() - origin.getX(); double d1 = pos.getY() - origin.getY(); double d2 = pos.getZ() - origin.getZ(); double dist = MathHelper.sqrt(d0 * d0 + d2 * d2); yaw = (float)(MathHelper.atan2(d2, d0) * (double)(180F / (float)Math.PI)) - 90.0F; pitch = (float)(-(MathHelper.atan2(d1, dist) * (double)(180F / (float)Math.PI))); height += maxTendrilGrowth * 16F; } } else if(height > 0 && retractTime > 6) { prevRotateSpin = rotateSpin; if(capture != null) { rotateSpin += spinFactor; } float maxTendrilGrowth = Math.max(0.0625F, distToEnt / (Morph.configClient.acquisitionTendrilMaxChild * 2F) + (float)rand.nextGaussian() * 0.125F); //in blocks height -= maxTendrilGrowth * 16F; if(height <= 0) { height = 0; if(parent != null) { parent.child = null; //remove ourselves. if(capture != null) { parent.capture = capture; parent.prevRotateSpin = prevRotateSpin; parent.rotateSpin = rotateSpin; } } } } } } public boolean isDone() { return retract && height <= 0F; } public void propagateRetractToParent() { retract = true; if(parent != null) { parent.propagateRetractToParent(); } } public void propagateRetractToChild() { retract = true; if(child != null) { child.propagateRetractToChild(); } } public Vector3d getReachOffset() { float growth = height / 16F; return offset.add(getVectorForRotation(pitch, yaw).mul(growth, growth, growth)); } public Vector3d getReachCoord() { return EntityAcquisition.this.getPositionVec().add(getReachOffset()); } public float getWidth(float partialTick) { float width = 1F + (0.2F * remainingDepth(partialTick)); if(width > 3.5F) { width = 3.5F; } return width; } public float remainingDepth(float partialTick) { int depth = 0; Tendril aParent = this; Tendril aChild = aParent.child; while(aChild != null) { depth += Math.min((aChild.lastHeight + (aChild.height - aChild.lastHeight) * partialTick) / aChild.maxGrowth, 1F); aParent = aChild; aChild = aParent.child; } return depth; } public void createModelRenderer(ArrayList<ModelRenderer> renderers, float partialTick) { if(child != null) { child.createModelRenderer(renderers, partialTick); } ModelRenderer model = new ModelRenderer(64, 64, rand.nextInt(8), rand.nextInt(8)); float width = getWidth(partialTick); float halfWidth = width / 2F; model.addBox(-halfWidth, -halfWidth, 0F, width, width, lastHeight + (height - lastHeight) * partialTick); model.rotationPointX = (float)(offset.getX() * 16F); model.rotationPointY = (float)(offset.getY() * 16F); model.rotationPointZ = (float)(offset.getZ() * 16F); model.rotateAngleX = (float)Math.toRadians(pitch); model.rotateAngleY = (float)Math.toRadians(-yaw); renderers.add(model); } public void renderCapture(EntityAcquisition acquisition, MatrixStack stack, IVertexBuilder vertexBuilder, int light, int overlay, float partialTick) { if(child != null) { child.renderCapture(acquisition, stack, vertexBuilder, light, overlay, partialTick); } else if(capture != null) //only at tendril endpoints. { float renderHeight = lastHeight + (height - lastHeight) * partialTick; float heightOffset = renderHeight / 16F; Vector3d look = getVectorForRotation(pitch, yaw); Vector3d renderPoint = offset.add(look.mul(heightOffset, heightOffset, heightOffset)); float alpha = 1F; if(acquisition.livingOrigin == Minecraft.getInstance().getRenderViewEntity() && Minecraft.getInstance().gameSettings.getPointOfView() == PointOfView.FIRST_PERSON) { alpha = MathHelper.clamp((depth + 1) / (float)Morph.configClient.acquisitionTendrilPartOpacity, 0F, 1F); } if(alpha > 0F) { float scale; double distToEnt = acquisition.livingOrigin.getDistance(acquisition.livingAcquired); double distToRenderPoint = MathHelper.sqrt(acquisition.getDistanceSq(acquisition.getPositionVec().add(renderPoint))); if(distToEnt > 0D) { scale = (float)(Math.min(distToEnt, (distToRenderPoint + 0.5D)) / distToEnt); //+1 to make the render still show the entity slightly as it's being pulled in. } else { scale = 0F; } stack.push(); stack.translate(renderPoint.getX(), renderPoint.getY(), renderPoint.getZ()); stack.scale(scale, scale, scale); float rot = prevRotateSpin + (rotateSpin - prevRotateSpin) * partialTick; stack.rotate(Vector3f.ZP.rotationDegrees(rot)); stack.rotate(Vector3f.YP.rotationDegrees(rot)); stack.translate(0D, -(acquisition.livingAcquired.getHeight() / 2D), 0D); if(isMorphAcquisition) { capture.render(stack, vertexBuilder, light, overlay, alpha); } else { for(MorphRenderHandler.ModelRendererCapture.CaptureInfo info : capture.infos) { MatrixStack identityStack = new MatrixStack(); stack.push(); MatrixStack.Entry e = RenderHelper.createInterimStackEntry(identityStack.getLast(), info.e, MathHelper.clamp(scale * 3F, 0F, 1F)); MatrixStack.Entry last = stack.getLast(); last.getMatrix().mul(e.getMatrix()); last.getNormal().mul(e.getNormal()); info.createAndRender(stack, vertexBuilder, light, overlay, 1F, 1F, 1F, alpha); stack.pop(); } } stack.pop(); } } } } }
lgpl-3.0
DomeA/Nebula
code/Leo/mappingo/servers/util/mp-security/src/main/java/com/domeastudio/mappingo/servers/util/mpsecurity/MD5SHAHelper.java
2048
package com.domeastudio.mappingo.servers.util.mpsecurity; import com.domeastudio.mappingo.servers.util.mpsecurity.base.Byte2StringHelper; import java.security.MessageDigest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MD5SHAHelper { private static Logger logger = LoggerFactory.getLogger(MD5SHAHelper.class); /** * encode string * * @param algorithm * @param data * @return String */ public static byte[] encrypt(ALGORITHM algorithm, byte[] data) { if (null == data && data.length < 1) { return null; } return encryptCore(algorithm, data); } private static byte[] encryptCore(ALGORITHM algorithm, byte[] data) { try { MessageDigest messageDigest = MessageDigest.getInstance(algorithm.name()); messageDigest.update(data); return messageDigest.digest(); } catch (Exception e) { logger.error("encryption '" + data + "' string error in " + algorithm.name() + " mode:", e); throw new RuntimeException(e); } } /** * MD5加密 * * @param data * @return String */ public static byte[] encryptByMD5(byte[] data) { if (null == data && data.length < 1) { return null; } return encryptCore(ALGORITHM.MD5, data); } // public static void main(String[] args) { System.out.println("空字符串 MD5 :" + Byte2StringHelper.getFormattedText(MD5SHAHelper.encryptByMD5("".getBytes()))); System.out.println("空格 MD5 :" + Byte2StringHelper.getFormattedText(MD5SHAHelper.encrypt(ALGORITHM.MD5, " ".getBytes()))); System.out.println("空字符串 SHA1 :" + Byte2StringHelper.getFormattedText(MD5SHAHelper.encrypt(ALGORITHM.SHA, "".getBytes()))); System.out.println("空格 SHA1 :" + Byte2StringHelper.getFormattedText(MD5SHAHelper.encrypt(ALGORITHM.SHA1, " ".getBytes()))); } }
lgpl-3.0
hunator/Galacticraft
common/micdoodle8/mods/galacticraft/mars/world/gen/dungeon/GCMarsRoomChests.java
4033
package micdoodle8.mods.galacticraft.mars.world.gen.dungeon; import java.util.ArrayList; import java.util.Random; import micdoodle8.mods.galacticraft.core.world.gen.dungeon.GCCoreDungeonBoundingBox; import micdoodle8.mods.galacticraft.core.world.gen.dungeon.GCCoreDungeonRoom; import micdoodle8.mods.galacticraft.core.world.gen.dungeon.GCCoreMapGenDungeon; import net.minecraft.block.Block; import net.minecraft.tileentity.TileEntityChest; import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.WeightedRandomChestContent; import net.minecraftforge.common.ChestGenHooks; import net.minecraftforge.common.ForgeDirection; /** * GCMarsRoomChests.java * * This file is part of the Galacticraft project * * @author micdoodle8 * @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html) * */ public class GCMarsRoomChests extends GCCoreDungeonRoom { int sizeX; int sizeY; int sizeZ; private final ArrayList<ChunkCoordinates> chests = new ArrayList<ChunkCoordinates>(); public GCMarsRoomChests(GCCoreMapGenDungeon dungeon, int posX, int posY, int posZ, ForgeDirection entranceDir) { super(dungeon, posX, posY, posZ, entranceDir); if (this.worldObj != null) { final Random rand = new Random(this.worldObj.getSeed() * posX * posY * 57 * posZ); this.sizeX = rand.nextInt(5) + 6; this.sizeY = rand.nextInt(2) + 7; this.sizeZ = rand.nextInt(5) + 6; } } @Override public void generate(short[] chunk, byte[] meta, int cx, int cz) { for (int i = this.posX - 1; i <= this.posX + this.sizeX; i++) { for (int j = this.posY - 1; j <= this.posY + this.sizeY; j++) { for (int k = this.posZ - 1; k <= this.posZ + this.sizeZ; k++) { if (i == this.posX - 1 || i == this.posX + this.sizeX || j == this.posY - 1 || j == this.posY + this.sizeY || k == this.posZ - 1 || k == this.posZ + this.sizeZ) { this.placeBlock(chunk, meta, i, j, k, cx, cz, this.dungeonInstance.DUNGEON_WALL_ID, this.dungeonInstance.DUNGEON_WALL_META); } else { this.placeBlock(chunk, meta, i, j, k, cx, cz, 0, 0); } } } } final int hx = (this.posX + this.posX + this.sizeX) / 2; final int hz = (this.posZ + this.posZ + this.sizeZ) / 2; if (this.placeBlock(chunk, meta, hx, this.posY, hz, cx, cz, Block.chest.blockID, 0)) { this.chests.add(new ChunkCoordinates(hx, this.posY, hz)); } } @Override public GCCoreDungeonBoundingBox getBoundingBox() { return new GCCoreDungeonBoundingBox(this.posX, this.posZ, this.posX + this.sizeX, this.posZ + this.sizeZ); } @Override protected GCCoreDungeonRoom makeRoom(GCCoreMapGenDungeon dungeon, int x, int y, int z, ForgeDirection dir) { return new GCMarsRoomChests(dungeon, x, y, z, dir); } @Override protected void handleTileEntities(Random rand) { if (!this.chests.isEmpty()) { this.worldObj.setBlock(this.chests.get(0).posX, this.chests.get(0).posY, this.chests.get(0).posZ, Block.chest.blockID, 0, 2); TileEntityChest chest = (TileEntityChest) this.worldObj.getBlockTileEntity(this.chests.get(0).posX, this.chests.get(0).posY, this.chests.get(0).posZ); if (chest != null) { for (int i = 0; i < chest.getSizeInventory(); i++) { chest.setInventorySlotContents(i, null); } ChestGenHooks info = ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST); WeightedRandomChestContent.generateChestContents(rand, info.getItems(rand), chest, info.getCount(rand)); } this.chests.clear(); } } }
lgpl-3.0
Ruthlessbug/CrezyScientist
src/main/java/com/ruthless/crezyscientist/entity/MonsterBase.java
233
package com.ruthless.crezyscientist.entity; import net.minecraft.entity.monster.EntityMob; import net.minecraft.world.World; public class MonsterBase extends EntityMob { public MonsterBase(World worldIn) { super(worldIn); } }
lgpl-3.0
impetus-opensource/jumbune
common/src/main/java/org/jumbune/common/beans/SupportedHadoopDistributions.java
1366
package org.jumbune.common.beans; /*** * constants for hadoop specific versions. */ public enum SupportedHadoopDistributions { /** The default hadoop version for apache 1.2.1 non-yarn */ HADOOP_NON_YARN("Hadoop 1.2"), /** The HADOOP 0_20_02 */ HADOOP_MAPR("Hadoop 1.0.3"), /** The HADOOP 2.4.1 */ HADOOP_YARN("Hadoop 2.4."), /** The CDH Hadoop */ CDH_5("cdh5"), /** The Apache Hadoop 0.2X */ APACHE_02X("Hadoop 0.23."); /** The version. */ private String version; /** The name. */ private SupportedHadoopDistributions name; /** * Instantiates a new supported apache hadoop versions. * * @param version the version */ private SupportedHadoopDistributions(String version) { this.version = version; } /* (non-Javadoc) * @see java.lang.Enum#toString() */ @Override public String toString() { return version; } /** * * * This method used for find out hadoop version constants for. * * @param version version of Hadoop * @return the enum by value */ public static SupportedHadoopDistributions getEnumByValue(String version) { SupportedHadoopDistributions name = null; for (SupportedHadoopDistributions hadoopVersions : values()) { if (version.contains(hadoopVersions.version)) { name = hadoopVersions; return name; } } return SupportedHadoopDistributions.HADOOP_NON_YARN; } }
lgpl-3.0
RWTH-OS/ostfriesentee-examples
app/testsuite/java/testvm/tests/SwitchTest.java
2043
/* * SwitchTest.java * * Copyright (c) 2008-2010 CSIRO, Delft University of Technology. * * This file is part of Darjeeling. * * Darjeeling 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 3 of the License, or * (at your option) any later version. * * Darjeeling 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 Darjeeling. If not, see <http://www.gnu.org/licenses/>. */ package testvm.tests; import javax.ostfriesentee.Ostfriesentee; public class SwitchTest { public static void test(int testBase) { // tableswitch int testNr = testBase; for (int i=-1; i<4; i++) { switch(i) { case 0: Ostfriesentee.assertTrue(testNr, i==0); break; case 1: Ostfriesentee.assertTrue(testNr, i==1); break; case 2: Ostfriesentee.assertTrue(testNr, i==2); break; case 3: Ostfriesentee.assertTrue(testNr, i==3); break; default: Ostfriesentee.assertTrue(testNr, i<0||i>=8); break; } testNr++; } testNr = testBase + 10; for (int i=-100; i<900; i+=100) { switch(i) { case 000: Ostfriesentee.assertTrue(testNr, i==000); break; case 100: Ostfriesentee.assertTrue(testNr, i==100); break; case 200: Ostfriesentee.assertTrue(testNr, i==200); break; case 300: Ostfriesentee.assertTrue(testNr, i==300); break; case 400: Ostfriesentee.assertTrue(testNr, i==400); break; case 500: Ostfriesentee.assertTrue(testNr, i==500); break; case 600: Ostfriesentee.assertTrue(testNr, i==600); break; case 700: Ostfriesentee.assertTrue(testNr, i==700); break; default: Ostfriesentee.assertTrue(testNr, i<0||i>700); break; } testNr++; } } }
lgpl-3.0
daniloqueiroz/no8
src/main/java/no8/application/ApplicationException.java
1336
/** * No8 Copyright (C) 2015 no8.io * * 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 no8.application; public class ApplicationException extends RuntimeException { private static final long serialVersionUID = 6152262024608326132L; public ApplicationException() { super(); } public ApplicationException(String message) { super(message); } public ApplicationException(Throwable cause) { super(cause); } public ApplicationException(String message, Throwable cause) { super(message, cause); } public ApplicationException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
lgpl-3.0
Javlo/javlo
src/main/java/org/javlo/module/ticket/Ticket.java
2509
package org.javlo.module.ticket; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Set; public interface Ticket { public static final String STATUS_NEW = "new"; public static final String STATUS_WORKING = "working"; public static final String STATUS_ONHOLD = "on hold"; public static final String STATUS_REJECTED = "rejected"; public static final String STATUS_DONE = "done"; public static final String STATUS_ARCHIVED = "archived"; public static final String BSTATUS_ASK = "ask"; public static final String BSTATUS_WAIT= "wait"; public static final String BSTATUS_VALIDED = "valided"; public static final String BSTATUS_REJECTED = "rejedcted"; public static final List<String> STATUS = Arrays.asList(new String[] {STATUS_NEW,STATUS_WORKING,STATUS_ONHOLD,STATUS_REJECTED,STATUS_DONE,STATUS_ARCHIVED }); public static final List<String> BSTATUS = Arrays.asList(new String[] {BSTATUS_ASK,BSTATUS_WAIT,BSTATUS_VALIDED,BSTATUS_REJECTED}); String getTitle(); // void setTitle(String title); String getMessage(); public String getHtmlMessage(); // void setMessage(String message); String getContext(); // void setContext(String context); String getUrl(); // void setUrl(String url); int getPriority(); // void setPriority(int priority); String getStatus(); // void setStatus(String status); String getAuthors(); // void setAuthors(String authors); String getId(); // void setId(String id); String getCategory(); // void setCategory(String category); boolean isDebugNote(); Date getCreationDate(); // void setCreationDate(Date creationDate); Date getLastUpdateDate(); // void setLastUpdateDate(Date lastUpdateDate); String getLatestEditor(); // void setLatestEditor(String latestEditor); List<Comment> getComments(); // void setComments(List<Comment> comments); // void addComments(Comment comment); String getCreationDateLabel(); String getLastUpdateDateLabel(); Set<String> getReaders(); // void setReaders(Set<String> readers); boolean isDeleted(); // void setDeleted(boolean deleted); String getShare(); // void setShare(String share); List<String> getUsers(); String getScreenshot(); // void setUsers(List<String> users); void onUpdate(String login); void onRead(String login); /** get price in cent **/ public long getPrice(); public String getBstatus(); }
lgpl-3.0
Godin/sonar
server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileComparison.java
5994
/* * SonarQube * Copyright (C) 2009-2019 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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.sonar.server.qualityprofile; import com.google.common.base.Function; import com.google.common.collect.MapDifference; import com.google.common.collect.Maps; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nonnull; import org.sonar.api.rule.RuleKey; import org.sonar.api.server.ServerSide; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.qualityprofile.ActiveRuleDto; import org.sonar.db.qualityprofile.ActiveRuleParamDto; import org.sonar.db.qualityprofile.OrgActiveRuleDto; import org.sonar.db.qualityprofile.QProfileDto; @ServerSide public class QProfileComparison { private final DbClient dbClient; public QProfileComparison(DbClient dbClient) { this.dbClient = dbClient; } public QProfileComparisonResult compare(DbSession dbSession, QProfileDto left, QProfileDto right) { Map<RuleKey, OrgActiveRuleDto> leftActiveRulesByRuleKey = loadActiveRules(dbSession, left); Map<RuleKey, OrgActiveRuleDto> rightActiveRulesByRuleKey = loadActiveRules(dbSession, right); Set<RuleKey> allRules = new HashSet<>(); allRules.addAll(leftActiveRulesByRuleKey.keySet()); allRules.addAll(rightActiveRulesByRuleKey.keySet()); QProfileComparisonResult result = new QProfileComparisonResult(left, right); for (RuleKey ruleKey : allRules) { if (!leftActiveRulesByRuleKey.containsKey(ruleKey)) { result.inRight.put(ruleKey, rightActiveRulesByRuleKey.get(ruleKey)); } else if (!rightActiveRulesByRuleKey.containsKey(ruleKey)) { result.inLeft.put(ruleKey, leftActiveRulesByRuleKey.get(ruleKey)); } else { compareActivationParams(dbSession, leftActiveRulesByRuleKey.get(ruleKey), rightActiveRulesByRuleKey.get(ruleKey), result); } } return result; } private void compareActivationParams(DbSession session, ActiveRuleDto leftRule, ActiveRuleDto rightRule, QProfileComparisonResult result) { RuleKey key = leftRule.getRuleKey(); Map<String, String> leftParams = paramDtoToMap(dbClient.activeRuleDao().selectParamsByActiveRuleId(session, leftRule.getId())); Map<String, String> rightParams = paramDtoToMap(dbClient.activeRuleDao().selectParamsByActiveRuleId(session, rightRule.getId())); if (leftParams.equals(rightParams) && leftRule.getSeverityString().equals(rightRule.getSeverityString())) { result.same.put(key, leftRule); } else { ActiveRuleDiff diff = new ActiveRuleDiff(); diff.leftSeverity = leftRule.getSeverityString(); diff.rightSeverity = rightRule.getSeverityString(); diff.paramDifference = Maps.difference(leftParams, rightParams); result.modified.put(key, diff); } } private Map<RuleKey, OrgActiveRuleDto> loadActiveRules(DbSession dbSession, QProfileDto profile) { return Maps.uniqueIndex(dbClient.activeRuleDao().selectByProfile(dbSession, profile), ActiveRuleToRuleKey.INSTANCE); } public static class QProfileComparisonResult { private final QProfileDto left; private final QProfileDto right; private final Map<RuleKey, ActiveRuleDto> inLeft = Maps.newHashMap(); private final Map<RuleKey, ActiveRuleDto> inRight = Maps.newHashMap(); private final Map<RuleKey, ActiveRuleDiff> modified = Maps.newHashMap(); private final Map<RuleKey, ActiveRuleDto> same = Maps.newHashMap(); public QProfileComparisonResult(QProfileDto left, QProfileDto right) { this.left = left; this.right = right; } public QProfileDto left() { return left; } public QProfileDto right() { return right; } public Map<RuleKey, ActiveRuleDto> inLeft() { return inLeft; } public Map<RuleKey, ActiveRuleDto> inRight() { return inRight; } public Map<RuleKey, ActiveRuleDiff> modified() { return modified; } public Map<RuleKey, ActiveRuleDto> same() { return same; } public Collection<RuleKey> collectRuleKeys() { Set<RuleKey> keys = new HashSet<>(); keys.addAll(inLeft.keySet()); keys.addAll(inRight.keySet()); keys.addAll(modified.keySet()); keys.addAll(same.keySet()); return keys; } } public static class ActiveRuleDiff { private String leftSeverity; private String rightSeverity; private MapDifference<String, String> paramDifference; public String leftSeverity() { return leftSeverity; } public String rightSeverity() { return rightSeverity; } public MapDifference<String, String> paramDifference() { return paramDifference; } } private enum ActiveRuleToRuleKey implements Function<ActiveRuleDto, RuleKey> { INSTANCE; @Override public RuleKey apply(@Nonnull ActiveRuleDto input) { return input.getRuleKey(); } } private static Map<String, String> paramDtoToMap(List<ActiveRuleParamDto> params) { Map<String, String> map = new HashMap<>(); for (ActiveRuleParamDto dto : params) { map.put(dto.getKey(), dto.getValue()); } return map; } }
lgpl-3.0
WELTEN/dojo-ibl
src/main/java/org/celstec/arlearn2/util/GamesCache.java
2085
/******************************************************************************* * Copyright (C) 2013 Open Universiteit Nederland * * 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 3 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, see <http://www.gnu.org/licenses/>. * * Contributors: Stefaan Ternier ******************************************************************************/ package org.celstec.arlearn2.util; import org.celstec.arlearn2.beans.game.Game; import org.celstec.arlearn2.beans.game.GamesList; import org.celstec.arlearn2.beans.run.User; import org.celstec.arlearn2.jdo.UserLoggedInManager; import net.sf.jsr107cache.Cache; public class GamesCache { private static GamesCache instance; private Cache cache; private GamesCache() { cache = FusionCache.getInstance().getCache(); } public static GamesCache getInstance() { if (instance == null) instance = new GamesCache(); return instance; } private static String GAMES_PREFIX = "Games"; // public void removeGames(String authToken) { // cache.remove(GAMES_PREFIX+authToken); // } // // public GamesList getGames(String authToken) { // return (GamesList) cache.get(GAMES_PREFIX+authToken); // } // // public void putGames(String authToken, GamesList gl) { // cache.put(GAMES_PREFIX+authToken, gl); // } // // public Game getGame(String authToken, long gameId) { // return (Game) cache.get(GAMES_PREFIX+gameId+authToken); // } // // public void putGame(String authToken, long gameId, Game g) { // cache.put(GAMES_PREFIX+gameId+authToken, g); // } }
lgpl-3.0
duckdoom5/RpgEssentials
RpgEssentials/src/com/topcat/npclib/pathing/PathReturn.java
104
package com.topcat.npclib.pathing; public interface PathReturn { public void run(NPCPath path); }
lgpl-3.0
ajiwo/xlfparser-jni
java/ajiwo/xlfparser/XlfMedia.java
249
package ajiwo.xlfparser; import java.util.Map; public class XlfMedia { public String id; public String type; public int duration; public String render; public Map<String, String> options; public Map<String, String> raws; }
lgpl-3.0
minnymin3/Zephyr
Zephyr-Bukkit/src/main/java/com/minnymin/zephyr/bukkit/util/command/Cmd.java
437
package com.minnymin.zephyr.bukkit.util.command; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(value = RetentionPolicy.RUNTIME) public @interface Cmd { public String label(); public String description(); public String usage(); public String[] aliases() default {}; }
lgpl-3.0
teryk/sonarqube
sonar-plugin-api/src/test/java/org/sonar/api/config/CategoryTest.java
1690
/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2014 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube 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 3 of the License, or (at your option) any later version. * * SonarQube 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.api.config; import org.junit.Test; import static org.fest.assertions.Assertions.assertThat; public class CategoryTest { @Test public void category_key_is_case_insentive() { assertThat(new Category("Licenses")).isEqualTo(new Category("licenses")); // Just to raise coverage assertThat(new Category("Licenses")).isNotEqualTo("Licenses"); } @Test public void should_preserve_original_key() { assertThat(new Category("Licenses").originalKey()).isEqualTo("Licenses"); } @Test public void should_normalize_key() throws Exception { assertThat(new Category("Licenses").key()).isEqualTo("licenses"); } @Test public void should_use_original_key() throws Exception { assertThat(new Category("Licenses").toString()).isEqualTo("Licenses"); } }
lgpl-3.0
philjord/jnif
jnif/src/nif/niobject/bs/BSPositionData.java
893
package nif.niobject.bs; import java.io.IOException; import java.nio.ByteBuffer; import nif.ByteConvert; import nif.NifVer; import nif.niobject.NiExtraData; import nif.tools.MiniFloat; public class BSPositionData extends NiExtraData { /* <niobject name="BSPositionData" inherit="NiExtraData"> Fallout 4 Positional Data <add name="Num Data" type="uint" /> <add name="Data" type="hfloat" arr1="Num Data" /> </niobject>non-Javadoc) */ public int NumData; public float[] Data; public boolean readFromStream(ByteBuffer stream, NifVer nifVer) throws IOException { boolean success = super.readFromStream(stream, nifVer); NumData = ByteConvert.readInt(stream); Data = new float[NumData]; for (int i = 0; i < NumData; i++) { Data[i] = MiniFloat.toFloat(ByteConvert.readUnsignedShort(stream)); } return success; } }
lgpl-3.0
iChun/Hats
src/main/java/me/ichun/mods/hats/common/hats/HatPool.java
1039
package me.ichun.mods.hats.common.hats; import me.ichun.mods.hats.common.Hats; import java.util.ArrayList; import java.util.Locale; import java.util.Random; public class HatPool { public final ArrayList<HatInfo> hatsInPool = new ArrayList<>(); private final Random rand = new Random(); //only used for getting a hat, no need to be tied to server rand. public EnumRarity forcedRarity = null; public HatInfo getRandomHat() { if(hatsInPool.size() == 1) { return hatsInPool.get(0); } return hatsInPool.get(rand.nextInt(hatsInPool.size())); } public void addHatToPool(HatInfo s) { if(!hatsInPool.contains(s)) { hatsInPool.add(s); } } public void forceRarity(String s) { try { forcedRarity = EnumRarity.valueOf(s.toUpperCase(Locale.ROOT)); } catch(IllegalArgumentException e) { Hats.LOGGER.error("Cannot find Hat Rarity of {}", s); } } }
lgpl-3.0
git-moss/DrivenByMoss
src/main/java/de/mossgrabers/framework/command/trigger/track/ToggleVUCommand.java
1354
// Written by Jürgen Moßgraber - mossgrabers.de // (c) 2017-2022 // Licensed under LGPLv3 - http://www.gnu.org/licenses/lgpl-3.0.txt package de.mossgrabers.framework.command.trigger.track; import de.mossgrabers.framework.command.core.AbstractTriggerCommand; import de.mossgrabers.framework.configuration.Configuration; import de.mossgrabers.framework.controller.IControlSurface; import de.mossgrabers.framework.daw.IModel; import de.mossgrabers.framework.utils.ButtonEvent; /** * Toggle the VU meter setting. * * @param <S> The type of the control surface * @param <C> The type of the configuration * * @author J&uuml;rgen Mo&szlig;graber */ public class ToggleVUCommand<S extends IControlSurface<C>, C extends Configuration> extends AbstractTriggerCommand<S, C> { /** * Constructor. * * @param model The model * @param surface The surface */ public ToggleVUCommand (final IModel model, final S surface) { super (model, surface); } /** {@inheritDoc} */ @Override public void executeNormal (final ButtonEvent event) { if (event != ButtonEvent.DOWN) return; final C configuration = this.surface.getConfiguration (); configuration.setVUMetersEnabled (!configuration.isEnableVUMeters ()); } }
lgpl-3.0
sones/sones-RemoteTagExample
java/RemoteTagExample/src/com/sones/VertexTypeService.java
55607
package com.sones; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; import com.microsoft.schemas._2003._10.serialization.arrays.ArrayOfstring; import org.datacontract.schemas._2004._07.sones_library_commons.SecurityToken; /** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.5-b04 * Generated source version: 2.2 * */ @WebService(name = "VertexTypeService", targetNamespace = "http://www.sones.com") @XmlSeeAlso({ com.microsoft.schemas._2003._10.serialization.arrays.ObjectFactory.class, com.microsoft.schemas._2003._10.serialization.ObjectFactory.class, com.sones.ObjectFactory.class, org.datacontract.schemas._2004._07.sones_library_commons.ObjectFactory.class, org.datacontract.schemas._2004._07.system.ObjectFactory.class }) public interface VertexTypeService { /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @return * returns com.sones.ArrayOfServiceVertexType */ @WebMethod(operationName = "GetDescendantVertexTypes", action = "http://www.sones.com/VertexTypeService/GetDescendantVertexTypes") @WebResult(name = "GetDescendantVertexTypesResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "GetDescendantVertexTypes", targetNamespace = "http://www.sones.com", className = "com.sones.GetDescendantVertexTypes") @ResponseWrapper(localName = "GetDescendantVertexTypesResponse", targetNamespace = "http://www.sones.com", className = "com.sones.GetDescendantVertexTypesResponse") public ArrayOfServiceVertexType getDescendantVertexTypes( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @return * returns com.sones.ArrayOfServiceVertexType */ @WebMethod(operationName = "GetDescendantVertexTypesAndSelf", action = "http://www.sones.com/VertexTypeService/GetDescendantVertexTypesAndSelf") @WebResult(name = "GetDescendantVertexTypesAndSelfResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "GetDescendantVertexTypesAndSelf", targetNamespace = "http://www.sones.com", className = "com.sones.GetDescendantVertexTypesAndSelf") @ResponseWrapper(localName = "GetDescendantVertexTypesAndSelfResponse", targetNamespace = "http://www.sones.com", className = "com.sones.GetDescendantVertexTypesAndSelfResponse") public ArrayOfServiceVertexType getDescendantVertexTypesAndSelf( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @return * returns com.sones.ArrayOfServiceVertexType */ @WebMethod(operationName = "GetAncestorVertexTypes", action = "http://www.sones.com/VertexTypeService/GetAncestorVertexTypes") @WebResult(name = "GetAncestorVertexTypesResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "GetAncestorVertexTypes", targetNamespace = "http://www.sones.com", className = "com.sones.GetAncestorVertexTypes") @ResponseWrapper(localName = "GetAncestorVertexTypesResponse", targetNamespace = "http://www.sones.com", className = "com.sones.GetAncestorVertexTypesResponse") public ArrayOfServiceVertexType getAncestorVertexTypes( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @return * returns com.sones.ArrayOfServiceVertexType */ @WebMethod(operationName = "GetAncestorVertexTypesAndSelf", action = "http://www.sones.com/VertexTypeService/GetAncestorVertexTypesAndSelf") @WebResult(name = "GetAncestorVertexTypesAndSelfResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "GetAncestorVertexTypesAndSelf", targetNamespace = "http://www.sones.com", className = "com.sones.GetAncestorVertexTypesAndSelf") @ResponseWrapper(localName = "GetAncestorVertexTypesAndSelfResponse", targetNamespace = "http://www.sones.com", className = "com.sones.GetAncestorVertexTypesAndSelfResponse") public ArrayOfServiceVertexType getAncestorVertexTypesAndSelf( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @return * returns com.sones.ArrayOfServiceVertexType */ @WebMethod(operationName = "GetKinsmenVertexTypes", action = "http://www.sones.com/VertexTypeService/GetKinsmenVertexTypes") @WebResult(name = "GetKinsmenVertexTypesResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "GetKinsmenVertexTypes", targetNamespace = "http://www.sones.com", className = "com.sones.GetKinsmenVertexTypes") @ResponseWrapper(localName = "GetKinsmenVertexTypesResponse", targetNamespace = "http://www.sones.com", className = "com.sones.GetKinsmenVertexTypesResponse") public ArrayOfServiceVertexType getKinsmenVertexTypes( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @return * returns com.sones.ArrayOfServiceVertexType */ @WebMethod(operationName = "GetKinsmenVertexTypesAndSelf", action = "http://www.sones.com/VertexTypeService/GetKinsmenVertexTypesAndSelf") @WebResult(name = "GetKinsmenVertexTypesAndSelfResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "GetKinsmenVertexTypesAndSelf", targetNamespace = "http://www.sones.com", className = "com.sones.GetKinsmenVertexTypesAndSelf") @ResponseWrapper(localName = "GetKinsmenVertexTypesAndSelfResponse", targetNamespace = "http://www.sones.com", className = "com.sones.GetKinsmenVertexTypesAndSelfResponse") public ArrayOfServiceVertexType getKinsmenVertexTypesAndSelf( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @return * returns com.sones.ArrayOfServiceVertexType */ @WebMethod(operationName = "ChildrenVertexTypes", action = "http://www.sones.com/VertexTypeService/ChildrenVertexTypes") @WebResult(name = "ChildrenVertexTypesResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "ChildrenVertexTypes", targetNamespace = "http://www.sones.com", className = "com.sones.ChildrenVertexTypes") @ResponseWrapper(localName = "ChildrenVertexTypesResponse", targetNamespace = "http://www.sones.com", className = "com.sones.ChildrenVertexTypesResponse") public ArrayOfServiceVertexType childrenVertexTypes( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @return * returns com.sones.ServiceVertexType */ @WebMethod(operationName = "ParentVertexType", action = "http://www.sones.com/VertexTypeService/ParentVertexType") @WebResult(name = "ParentVertexTypeResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "ParentVertexType", targetNamespace = "http://www.sones.com", className = "com.sones.ParentVertexType") @ResponseWrapper(localName = "ParentVertexTypeResponse", targetNamespace = "http://www.sones.com", className = "com.sones.ParentVertexTypeResponse") public ServiceVertexType parentVertexType( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @return * returns java.lang.Boolean */ @WebMethod(operationName = "IsSealedByVertexType", action = "http://www.sones.com/VertexTypeService/IsSealedByVertexType") @WebResult(name = "IsSealedByVertexTypeResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "IsSealedByVertexType", targetNamespace = "http://www.sones.com", className = "com.sones.IsSealedByVertexType") @ResponseWrapper(localName = "IsSealedByVertexTypeResponse", targetNamespace = "http://www.sones.com", className = "com.sones.IsSealedByVertexTypeResponse") public Boolean isSealedByVertexType( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @return * returns java.lang.Boolean */ @WebMethod(operationName = "HasParentTypeByVertexType", action = "http://www.sones.com/VertexTypeService/HasParentTypeByVertexType") @WebResult(name = "HasParentTypeByVertexTypeResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "HasParentTypeByVertexType", targetNamespace = "http://www.sones.com", className = "com.sones.HasParentTypeByVertexType") @ResponseWrapper(localName = "HasParentTypeByVertexTypeResponse", targetNamespace = "http://www.sones.com", className = "com.sones.HasParentTypeByVertexTypeResponse") public Boolean hasParentTypeByVertexType( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @return * returns java.lang.Boolean */ @WebMethod(operationName = "HasChildTypeByVertexType", action = "http://www.sones.com/VertexTypeService/HasChildTypeByVertexType") @WebResult(name = "HasChildTypeByVertexTypeResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "HasChildTypeByVertexType", targetNamespace = "http://www.sones.com", className = "com.sones.HasChildTypeByVertexType") @ResponseWrapper(localName = "HasChildTypeByVertexTypeResponse", targetNamespace = "http://www.sones.com", className = "com.sones.HasChildTypeByVertexTypeResponse") public Boolean hasChildTypeByVertexType( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType); /** * * @param myOtherType * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @return * returns java.lang.Boolean */ @WebMethod(operationName = "IsAncestorByVertexType", action = "http://www.sones.com/VertexTypeService/IsAncestorByVertexType") @WebResult(name = "IsAncestorByVertexTypeResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "IsAncestorByVertexType", targetNamespace = "http://www.sones.com", className = "com.sones.IsAncestorByVertexType") @ResponseWrapper(localName = "IsAncestorByVertexTypeResponse", targetNamespace = "http://www.sones.com", className = "com.sones.IsAncestorByVertexTypeResponse") public Boolean isAncestorByVertexType( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myOtherType", targetNamespace = "http://www.sones.com") ServiceVertexType myOtherType); /** * * @param myOtherType * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @return * returns java.lang.Boolean */ @WebMethod(operationName = "IsAncestorOrSelfByVertexType", action = "http://www.sones.com/VertexTypeService/IsAncestorOrSelfByVertexType") @WebResult(name = "IsAncestorOrSelfByVertexTypeResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "IsAncestorOrSelfByVertexType", targetNamespace = "http://www.sones.com", className = "com.sones.IsAncestorOrSelfByVertexType") @ResponseWrapper(localName = "IsAncestorOrSelfByVertexTypeResponse", targetNamespace = "http://www.sones.com", className = "com.sones.IsAncestorOrSelfByVertexTypeResponse") public Boolean isAncestorOrSelfByVertexType( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myOtherType", targetNamespace = "http://www.sones.com") ServiceVertexType myOtherType); /** * * @param myOtherType * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @return * returns java.lang.Boolean */ @WebMethod(operationName = "IsDescendantByVertexType", action = "http://www.sones.com/VertexTypeService/IsDescendantByVertexType") @WebResult(name = "IsDescendantByVertexTypeResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "IsDescendantByVertexType", targetNamespace = "http://www.sones.com", className = "com.sones.IsDescendantByVertexType") @ResponseWrapper(localName = "IsDescendantByVertexTypeResponse", targetNamespace = "http://www.sones.com", className = "com.sones.IsDescendantByVertexTypeResponse") public Boolean isDescendantByVertexType( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myOtherType", targetNamespace = "http://www.sones.com") ServiceVertexType myOtherType); /** * * @param myOtherType * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @return * returns java.lang.Boolean */ @WebMethod(operationName = "IsDescendantOrSelfByVertexType", action = "http://www.sones.com/VertexTypeService/IsDescendantOrSelfByVertexType") @WebResult(name = "IsDescendantOrSelfByVertexTypeResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "IsDescendantOrSelfByVertexType", targetNamespace = "http://www.sones.com", className = "com.sones.IsDescendantOrSelfByVertexType") @ResponseWrapper(localName = "IsDescendantOrSelfByVertexTypeResponse", targetNamespace = "http://www.sones.com", className = "com.sones.IsDescendantOrSelfByVertexTypeResponse") public Boolean isDescendantOrSelfByVertexType( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myOtherType", targetNamespace = "http://www.sones.com") ServiceVertexType myOtherType); /** * * @param myTransToken * @param myAttributeName * @param mySecurityToken * @param myServiceVertexType * @return * returns java.lang.Boolean */ @WebMethod(operationName = "HasAttributeByVertexType", action = "http://www.sones.com/VertexTypeService/HasAttributeByVertexType") @WebResult(name = "HasAttributeByVertexTypeResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "HasAttributeByVertexType", targetNamespace = "http://www.sones.com", className = "com.sones.HasAttributeByVertexType") @ResponseWrapper(localName = "HasAttributeByVertexTypeResponse", targetNamespace = "http://www.sones.com", className = "com.sones.HasAttributeByVertexTypeResponse") public Boolean hasAttributeByVertexType( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myAttributeName", targetNamespace = "http://www.sones.com") String myAttributeName); /** * * @param myTransToken * @param myAttributeName * @param mySecurityToken * @param myServiceVertexType * @return * returns com.sones.ServiceAttributeDefinition */ @WebMethod(operationName = "GetAttributeDefinitionByVertexType", action = "http://www.sones.com/VertexTypeService/GetAttributeDefinitionByVertexType") @WebResult(name = "GetAttributeDefinitionByVertexTypeResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "GetAttributeDefinitionByVertexType", targetNamespace = "http://www.sones.com", className = "com.sones.GetAttributeDefinitionByVertexType") @ResponseWrapper(localName = "GetAttributeDefinitionByVertexTypeResponse", targetNamespace = "http://www.sones.com", className = "com.sones.GetAttributeDefinitionByVertexTypeResponse") public ServiceAttributeDefinition getAttributeDefinitionByVertexType( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myAttributeName", targetNamespace = "http://www.sones.com") String myAttributeName); /** * * @param myTransToken * @param myAttributeID * @param mySecurityToken * @param myServiceVertexType * @return * returns com.sones.ServiceAttributeDefinition */ @WebMethod(operationName = "GetAttributeDefinitionByIDByVertexType", action = "http://www.sones.com/VertexTypeService/GetAttributeDefinitionByIDByVertexType") @WebResult(name = "GetAttributeDefinitionByIDByVertexTypeResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "GetAttributeDefinitionByIDByVertexType", targetNamespace = "http://www.sones.com", className = "com.sones.GetAttributeDefinitionByIDByVertexType") @ResponseWrapper(localName = "GetAttributeDefinitionByIDByVertexTypeResponse", targetNamespace = "http://www.sones.com", className = "com.sones.GetAttributeDefinitionByIDByVertexTypeResponse") public ServiceAttributeDefinition getAttributeDefinitionByIDByVertexType( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myAttributeID", targetNamespace = "http://www.sones.com") Long myAttributeID); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @param myIncludeAncestorDefinitions * @return * returns java.lang.Boolean */ @WebMethod(operationName = "HasAttributesByVertexType", action = "http://www.sones.com/VertexTypeService/HasAttributesByVertexType") @WebResult(name = "HasAttributesByVertexTypeResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "HasAttributesByVertexType", targetNamespace = "http://www.sones.com", className = "com.sones.HasAttributesByVertexType") @ResponseWrapper(localName = "HasAttributesByVertexTypeResponse", targetNamespace = "http://www.sones.com", className = "com.sones.HasAttributesByVertexTypeResponse") public Boolean hasAttributesByVertexType( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myIncludeAncestorDefinitions", targetNamespace = "http://www.sones.com") Boolean myIncludeAncestorDefinitions); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @param myIncludeAncestorDefinitions * @return * returns com.sones.ArrayOfServiceAttributeDefinition */ @WebMethod(operationName = "GetAttributeDefinitionsByVertexType", action = "http://www.sones.com/VertexTypeService/GetAttributeDefinitionsByVertexType") @WebResult(name = "GetAttributeDefinitionsByVertexTypeResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "GetAttributeDefinitionsByVertexType", targetNamespace = "http://www.sones.com", className = "com.sones.GetAttributeDefinitionsByVertexType") @ResponseWrapper(localName = "GetAttributeDefinitionsByVertexTypeResponse", targetNamespace = "http://www.sones.com", className = "com.sones.GetAttributeDefinitionsByVertexTypeResponse") public ArrayOfServiceAttributeDefinition getAttributeDefinitionsByVertexType( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myIncludeAncestorDefinitions", targetNamespace = "http://www.sones.com") Boolean myIncludeAncestorDefinitions); /** * * @param myTransToken * @param myAttributeName * @param mySecurityToken * @param myServiceVertexType * @return * returns java.lang.Boolean */ @WebMethod(operationName = "HasPropertyByVertexType", action = "http://www.sones.com/VertexTypeService/HasPropertyByVertexType") @WebResult(name = "HasPropertyByVertexTypeResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "HasPropertyByVertexType", targetNamespace = "http://www.sones.com", className = "com.sones.HasPropertyByVertexType") @ResponseWrapper(localName = "HasPropertyByVertexTypeResponse", targetNamespace = "http://www.sones.com", className = "com.sones.HasPropertyByVertexTypeResponse") public Boolean hasPropertyByVertexType( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myAttributeName", targetNamespace = "http://www.sones.com") String myAttributeName); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexTypeName * @param myPropertyName * @return * returns com.sones.ServicePropertyDefinition */ @WebMethod(operationName = "GetPropertyDefinitionByVertexType", action = "http://www.sones.com/VertexTypeService/GetPropertyDefinitionByVertexType") @WebResult(name = "GetPropertyDefinitionByVertexTypeResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "GetPropertyDefinitionByVertexType", targetNamespace = "http://www.sones.com", className = "com.sones.GetPropertyDefinitionByVertexType") @ResponseWrapper(localName = "GetPropertyDefinitionByVertexTypeResponse", targetNamespace = "http://www.sones.com", className = "com.sones.GetPropertyDefinitionByVertexTypeResponse") public ServicePropertyDefinition getPropertyDefinitionByVertexType( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexTypeName", targetNamespace = "http://www.sones.com") String myServiceVertexTypeName, @WebParam(name = "myPropertyName", targetNamespace = "http://www.sones.com") String myPropertyName); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexTypeName * @param myPropertyID * @return * returns com.sones.ServicePropertyDefinition */ @WebMethod(operationName = "GetPropertyDefinitionByIDByVertexType", action = "http://www.sones.com/VertexTypeService/GetPropertyDefinitionByIDByVertexType") @WebResult(name = "GetPropertyDefinitionByIDByVertexTypeResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "GetPropertyDefinitionByIDByVertexType", targetNamespace = "http://www.sones.com", className = "com.sones.GetPropertyDefinitionByIDByVertexType") @ResponseWrapper(localName = "GetPropertyDefinitionByIDByVertexTypeResponse", targetNamespace = "http://www.sones.com", className = "com.sones.GetPropertyDefinitionByIDByVertexTypeResponse") public ServicePropertyDefinition getPropertyDefinitionByIDByVertexType( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexTypeName", targetNamespace = "http://www.sones.com") String myServiceVertexTypeName, @WebParam(name = "myPropertyID", targetNamespace = "http://www.sones.com") Long myPropertyID); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @param myIncludeAncestorDefinitions * @return * returns java.lang.Boolean */ @WebMethod(operationName = "HasPropertiesByVertexType", action = "http://www.sones.com/VertexTypeService/HasPropertiesByVertexType") @WebResult(name = "HasPropertiesByVertexTypeResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "HasPropertiesByVertexType", targetNamespace = "http://www.sones.com", className = "com.sones.HasPropertiesByVertexType") @ResponseWrapper(localName = "HasPropertiesByVertexTypeResponse", targetNamespace = "http://www.sones.com", className = "com.sones.HasPropertiesByVertexTypeResponse") public Boolean hasPropertiesByVertexType( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myIncludeAncestorDefinitions", targetNamespace = "http://www.sones.com") Boolean myIncludeAncestorDefinitions); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexTypeName * @param myIncludeAncestorDefinitions * @return * returns com.sones.ArrayOfServicePropertyDefinition */ @WebMethod(operationName = "GetPropertyDefinitionsByVertexType", action = "http://www.sones.com/VertexTypeService/GetPropertyDefinitionsByVertexType") @WebResult(name = "GetPropertyDefinitionsByVertexTypeResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "GetPropertyDefinitionsByVertexType", targetNamespace = "http://www.sones.com", className = "com.sones.GetPropertyDefinitionsByVertexType") @ResponseWrapper(localName = "GetPropertyDefinitionsByVertexTypeResponse", targetNamespace = "http://www.sones.com", className = "com.sones.GetPropertyDefinitionsByVertexTypeResponse") public ArrayOfServicePropertyDefinition getPropertyDefinitionsByVertexType( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexTypeName", targetNamespace = "http://www.sones.com") String myServiceVertexTypeName, @WebParam(name = "myIncludeAncestorDefinitions", targetNamespace = "http://www.sones.com") Boolean myIncludeAncestorDefinitions); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexTypeName * @param myPropertyNames * @return * returns com.sones.ArrayOfServicePropertyDefinition */ @WebMethod(operationName = "GetPropertyDefinitionsByNameListByVertexType", action = "http://www.sones.com/VertexTypeService/GetPropertyDefinitionsByNameListByVertexType") @WebResult(name = "GetPropertyDefinitionsByNameListByVertexTypeResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "GetPropertyDefinitionsByNameListByVertexType", targetNamespace = "http://www.sones.com", className = "com.sones.GetPropertyDefinitionsByNameListByVertexType") @ResponseWrapper(localName = "GetPropertyDefinitionsByNameListByVertexTypeResponse", targetNamespace = "http://www.sones.com", className = "com.sones.GetPropertyDefinitionsByNameListByVertexTypeResponse") public ArrayOfServicePropertyDefinition getPropertyDefinitionsByNameListByVertexType( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexTypeName", targetNamespace = "http://www.sones.com") String myServiceVertexTypeName, @WebParam(name = "myPropertyNames", targetNamespace = "http://www.sones.com") ArrayOfstring myPropertyNames); /** * * @param myTransToken * @param mySecurityToken * @param myPropertyName * @param myServiceVertexType * @return * returns java.lang.Boolean */ @WebMethod(operationName = "HasBinaryProperty", action = "http://www.sones.com/VertexTypeService/HasBinaryProperty") @WebResult(name = "HasBinaryPropertyResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "HasBinaryProperty", targetNamespace = "http://www.sones.com", className = "com.sones.HasBinaryProperty") @ResponseWrapper(localName = "HasBinaryPropertyResponse", targetNamespace = "http://www.sones.com", className = "com.sones.HasBinaryPropertyResponse") public Boolean hasBinaryProperty( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myPropertyName", targetNamespace = "http://www.sones.com") String myPropertyName); /** * * @param myTransToken * @param mySecurityToken * @param myPropertyName * @param myServiceVertexType * @return * returns com.sones.ServiceBinaryPropertyDefinition */ @WebMethod(operationName = "GetBinaryPropertyDefinition", action = "http://www.sones.com/VertexTypeService/GetBinaryPropertyDefinition") @WebResult(name = "GetBinaryPropertyDefinitionResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "GetBinaryPropertyDefinition", targetNamespace = "http://www.sones.com", className = "com.sones.GetBinaryPropertyDefinition") @ResponseWrapper(localName = "GetBinaryPropertyDefinitionResponse", targetNamespace = "http://www.sones.com", className = "com.sones.GetBinaryPropertyDefinitionResponse") public ServiceBinaryPropertyDefinition getBinaryPropertyDefinition( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myPropertyName", targetNamespace = "http://www.sones.com") String myPropertyName); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @param myIncludeAncestorDefinitions * @return * returns java.lang.Boolean */ @WebMethod(operationName = "HasBinaryProperties", action = "http://www.sones.com/VertexTypeService/HasBinaryProperties") @WebResult(name = "HasBinaryPropertiesResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "HasBinaryProperties", targetNamespace = "http://www.sones.com", className = "com.sones.HasBinaryProperties") @ResponseWrapper(localName = "HasBinaryPropertiesResponse", targetNamespace = "http://www.sones.com", className = "com.sones.HasBinaryPropertiesResponse") public Boolean hasBinaryProperties( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myIncludeAncestorDefinitions", targetNamespace = "http://www.sones.com") Boolean myIncludeAncestorDefinitions); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @param myIncludeAncestorDefinitions * @return * returns com.sones.ArrayOfServiceBinaryPropertyDefinition */ @WebMethod(operationName = "GetBinaryPropertyDefinitions", action = "http://www.sones.com/VertexTypeService/GetBinaryPropertyDefinitions") @WebResult(name = "GetBinaryPropertyDefinitionsResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "GetBinaryPropertyDefinitions", targetNamespace = "http://www.sones.com", className = "com.sones.GetBinaryPropertyDefinitions") @ResponseWrapper(localName = "GetBinaryPropertyDefinitionsResponse", targetNamespace = "http://www.sones.com", className = "com.sones.GetBinaryPropertyDefinitionsResponse") public ArrayOfServiceBinaryPropertyDefinition getBinaryPropertyDefinitions( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myIncludeAncestorDefinitions", targetNamespace = "http://www.sones.com") Boolean myIncludeAncestorDefinitions); /** * * @param myTransToken * @param mySecurityToken * @param myEdgeName * @param myServiceVertexType * @return * returns java.lang.Boolean */ @WebMethod(operationName = "HasIncomingEdge", action = "http://www.sones.com/VertexTypeService/HasIncomingEdge") @WebResult(name = "HasIncomingEdgeResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "HasIncomingEdge", targetNamespace = "http://www.sones.com", className = "com.sones.HasIncomingEdge") @ResponseWrapper(localName = "HasIncomingEdgeResponse", targetNamespace = "http://www.sones.com", className = "com.sones.HasIncomingEdgeResponse") public Boolean hasIncomingEdge( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myEdgeName", targetNamespace = "http://www.sones.com") String myEdgeName); /** * * @param myTransToken * @param mySecurityToken * @param myEdgeName * @param myServiceVertexType * @return * returns com.sones.ServiceIncomingEdgeDefinition */ @WebMethod(operationName = "GetIncomingEdgeDefinition", action = "http://www.sones.com/VertexTypeService/GetIncomingEdgeDefinition") @WebResult(name = "GetIncomingEdgeDefinitionResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "GetIncomingEdgeDefinition", targetNamespace = "http://www.sones.com", className = "com.sones.GetIncomingEdgeDefinition") @ResponseWrapper(localName = "GetIncomingEdgeDefinitionResponse", targetNamespace = "http://www.sones.com", className = "com.sones.GetIncomingEdgeDefinitionResponse") public ServiceIncomingEdgeDefinition getIncomingEdgeDefinition( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myEdgeName", targetNamespace = "http://www.sones.com") String myEdgeName); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @param myIncludeAncestorDefinitions * @return * returns java.lang.Boolean */ @WebMethod(operationName = "HasIncomingEdges", action = "http://www.sones.com/VertexTypeService/HasIncomingEdges") @WebResult(name = "HasIncomingEdgesResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "HasIncomingEdges", targetNamespace = "http://www.sones.com", className = "com.sones.HasIncomingEdges") @ResponseWrapper(localName = "HasIncomingEdgesResponse", targetNamespace = "http://www.sones.com", className = "com.sones.HasIncomingEdgesResponse") public Boolean hasIncomingEdges( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myIncludeAncestorDefinitions", targetNamespace = "http://www.sones.com") Boolean myIncludeAncestorDefinitions); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @param myIncludeAncestorDefinitions * @return * returns com.sones.ArrayOfServiceIncomingEdgeDefinition */ @WebMethod(operationName = "GetIncomingEdgeDefinitions", action = "http://www.sones.com/VertexTypeService/GetIncomingEdgeDefinitions") @WebResult(name = "GetIncomingEdgeDefinitionsResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "GetIncomingEdgeDefinitions", targetNamespace = "http://www.sones.com", className = "com.sones.GetIncomingEdgeDefinitions") @ResponseWrapper(localName = "GetIncomingEdgeDefinitionsResponse", targetNamespace = "http://www.sones.com", className = "com.sones.GetIncomingEdgeDefinitionsResponse") public ArrayOfServiceIncomingEdgeDefinition getIncomingEdgeDefinitions( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myIncludeAncestorDefinitions", targetNamespace = "http://www.sones.com") Boolean myIncludeAncestorDefinitions); /** * * @param myTransToken * @param mySecurityToken * @param myEdgeName * @param myServiceVertexType * @return * returns java.lang.Boolean */ @WebMethod(operationName = "HasOutgoingEdgeByVertexType", action = "http://www.sones.com/VertexTypeService/HasOutgoingEdgeByVertexType") @WebResult(name = "HasOutgoingEdgeByVertexTypeResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "HasOutgoingEdgeByVertexType", targetNamespace = "http://www.sones.com", className = "com.sones.HasOutgoingEdgeByVertexType") @ResponseWrapper(localName = "HasOutgoingEdgeByVertexTypeResponse", targetNamespace = "http://www.sones.com", className = "com.sones.HasOutgoingEdgeByVertexTypeResponse") public Boolean hasOutgoingEdgeByVertexType( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myEdgeName", targetNamespace = "http://www.sones.com") String myEdgeName); /** * * @param myTransToken * @param mySecurityToken * @param myEdgeName * @param myServiceVertexType * @return * returns com.sones.ServiceOutgoingEdgeDefinition */ @WebMethod(operationName = "GetOutgoingEdgeDefinitionByVertexType", action = "http://www.sones.com/VertexTypeService/GetOutgoingEdgeDefinitionByVertexType") @WebResult(name = "GetOutgoingEdgeDefinitionByVertexTypeResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "GetOutgoingEdgeDefinitionByVertexType", targetNamespace = "http://www.sones.com", className = "com.sones.GetOutgoingEdgeDefinitionByVertexType") @ResponseWrapper(localName = "GetOutgoingEdgeDefinitionByVertexTypeResponse", targetNamespace = "http://www.sones.com", className = "com.sones.GetOutgoingEdgeDefinitionByVertexTypeResponse") public ServiceOutgoingEdgeDefinition getOutgoingEdgeDefinitionByVertexType( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myEdgeName", targetNamespace = "http://www.sones.com") String myEdgeName); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @param myIncludeAncestorDefinitions * @return * returns java.lang.Boolean */ @WebMethod(operationName = "HasOutgoingEdgesByVertexType", action = "http://www.sones.com/VertexTypeService/HasOutgoingEdgesByVertexType") @WebResult(name = "HasOutgoingEdgesByVertexTypeResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "HasOutgoingEdgesByVertexType", targetNamespace = "http://www.sones.com", className = "com.sones.HasOutgoingEdgesByVertexType") @ResponseWrapper(localName = "HasOutgoingEdgesByVertexTypeResponse", targetNamespace = "http://www.sones.com", className = "com.sones.HasOutgoingEdgesByVertexTypeResponse") public Boolean hasOutgoingEdgesByVertexType( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myIncludeAncestorDefinitions", targetNamespace = "http://www.sones.com") Boolean myIncludeAncestorDefinitions); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @param myIncludeAncestorDefinitions * @return * returns com.sones.ArrayOfServiceOutgoingEdgeDefinition */ @WebMethod(operationName = "GetOutgoingEdgeDefinitionsByVertexType", action = "http://www.sones.com/VertexTypeService/GetOutgoingEdgeDefinitionsByVertexType") @WebResult(name = "GetOutgoingEdgeDefinitionsByVertexTypeResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "GetOutgoingEdgeDefinitionsByVertexType", targetNamespace = "http://www.sones.com", className = "com.sones.GetOutgoingEdgeDefinitionsByVertexType") @ResponseWrapper(localName = "GetOutgoingEdgeDefinitionsByVertexTypeResponse", targetNamespace = "http://www.sones.com", className = "com.sones.GetOutgoingEdgeDefinitionsByVertexTypeResponse") public ArrayOfServiceOutgoingEdgeDefinition getOutgoingEdgeDefinitionsByVertexType( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myIncludeAncestorDefinitions", targetNamespace = "http://www.sones.com") Boolean myIncludeAncestorDefinitions); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @param myIncludeAncestorDefinitions * @return * returns java.lang.Boolean */ @WebMethod(operationName = "HasUniqueDefinitions", action = "http://www.sones.com/VertexTypeService/HasUniqueDefinitions") @WebResult(name = "HasUniqueDefinitionsResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "HasUniqueDefinitions", targetNamespace = "http://www.sones.com", className = "com.sones.HasUniqueDefinitions") @ResponseWrapper(localName = "HasUniqueDefinitionsResponse", targetNamespace = "http://www.sones.com", className = "com.sones.HasUniqueDefinitionsResponse") public Boolean hasUniqueDefinitions( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myIncludeAncestorDefinitions", targetNamespace = "http://www.sones.com") Boolean myIncludeAncestorDefinitions); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @param myIncludeAncestorDefinitions * @return * returns com.sones.ArrayOfServiceUniqueDefinition */ @WebMethod(operationName = "GetUniqueDefinitions", action = "http://www.sones.com/VertexTypeService/GetUniqueDefinitions") @WebResult(name = "GetUniqueDefinitionsResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "GetUniqueDefinitions", targetNamespace = "http://www.sones.com", className = "com.sones.GetUniqueDefinitions") @ResponseWrapper(localName = "GetUniqueDefinitionsResponse", targetNamespace = "http://www.sones.com", className = "com.sones.GetUniqueDefinitionsResponse") public ArrayOfServiceUniqueDefinition getUniqueDefinitions( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myIncludeAncestorDefinitions", targetNamespace = "http://www.sones.com") Boolean myIncludeAncestorDefinitions); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @param myIncludeAncestorDefinitions * @return * returns java.lang.Boolean */ @WebMethod(operationName = "HasIndexDefinitions", action = "http://www.sones.com/VertexTypeService/HasIndexDefinitions") @WebResult(name = "HasIndexDefinitionsResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "HasIndexDefinitions", targetNamespace = "http://www.sones.com", className = "com.sones.HasIndexDefinitions") @ResponseWrapper(localName = "HasIndexDefinitionsResponse", targetNamespace = "http://www.sones.com", className = "com.sones.HasIndexDefinitionsResponse") public Boolean hasIndexDefinitions( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myIncludeAncestorDefinitions", targetNamespace = "http://www.sones.com") Boolean myIncludeAncestorDefinitions); /** * * @param myTransToken * @param mySecurityToken * @param myServiceVertexType * @param myIncludeAncestorDefinitions * @return * returns com.sones.ArrayOfServiceIndexDefinition */ @WebMethod(operationName = "GetIndexDefinitions", action = "http://www.sones.com/VertexTypeService/GetIndexDefinitions") @WebResult(name = "GetIndexDefinitionsResult", targetNamespace = "http://www.sones.com") @RequestWrapper(localName = "GetIndexDefinitions", targetNamespace = "http://www.sones.com", className = "com.sones.GetIndexDefinitions") @ResponseWrapper(localName = "GetIndexDefinitionsResponse", targetNamespace = "http://www.sones.com", className = "com.sones.GetIndexDefinitionsResponse") public ArrayOfServiceIndexDefinition getIndexDefinitions( @WebParam(name = "mySecurityToken", targetNamespace = "http://www.sones.com") SecurityToken mySecurityToken, @WebParam(name = "myTransToken", targetNamespace = "http://www.sones.com") Long myTransToken, @WebParam(name = "myServiceVertexType", targetNamespace = "http://www.sones.com") ServiceVertexType myServiceVertexType, @WebParam(name = "myIncludeAncestorDefinitions", targetNamespace = "http://www.sones.com") Boolean myIncludeAncestorDefinitions); }
lgpl-3.0
xinghuangxu/xinghuangxu.sonarqube
sonar-batch/src/main/java/org/sonar/batch/issue/ignore/pattern/PatternMatcher.java
2354
/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2013 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube 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 3 of the License, or (at your option) any later version. * * SonarQube 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.batch.issue.ignore.pattern; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Multimap; import org.sonar.api.issue.Issue; import java.util.Collection; import java.util.Iterator; import java.util.Set; public class PatternMatcher { private Multimap<String, IssuePattern> patternByComponent = LinkedHashMultimap.create(); public IssuePattern getMatchingPattern(Issue issue) { IssuePattern matchingPattern = null; Iterator<IssuePattern> patternIterator = getPatternsForComponent(issue.componentKey()).iterator(); while(matchingPattern == null && patternIterator.hasNext()) { IssuePattern nextPattern = patternIterator.next(); if (nextPattern.match(issue)) { matchingPattern = nextPattern; } } return matchingPattern; } public Collection<IssuePattern> getPatternsForComponent(String componentKey) { return patternByComponent.get(componentKey); } public void addPatternForComponent(String component, IssuePattern pattern) { patternByComponent.put(component, pattern.forResource(component)); } public void addPatternToExcludeResource(String resource) { addPatternForComponent(resource, new IssuePattern(resource, "*").setCheckLines(false)); } public void addPatternToExcludeLines(String resource, Set<LineRange> lineRanges) { addPatternForComponent(resource, new IssuePattern(resource, "*", lineRanges).setCheckLines(true)); } }
lgpl-3.0
rilian-la-te/vala-panel-appmenu
subprojects/jayatana/java/core/Feature.java
1380
/* * Copyright (c) 2014 Jared Gonzalez * * Permission is hereby granted, free of charge, to any * person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the * Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the * Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice * shall be included in all copies or substantial portions of * the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY * KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.jarego.jayatana; /** * This interface allows you to control the deployment of different * characteristics * * @author Jared Gonzalez */ public interface Feature { /** * Deploy characteristic */ public void deploy(); }
lgpl-3.0
anthavio/wotan
wotan-client/src/main/java/net/anthavio/wotan/client/WotanClient.java
6153
package net.anthavio.wotan.client; import java.io.Closeable; import java.lang.reflect.Array; import net.anthavio.cache.CacheBase; import net.anthavio.httl.HttlBuilderVisitor; import net.anthavio.httl.HttlParameterSetter.ConfigurableParamSetter; import net.anthavio.httl.HttlRequestBuilders.HttlRequestBuilder; import net.anthavio.httl.HttlSender; import net.anthavio.httl.HttlSender.Multival; import net.anthavio.httl.SenderConfigurer; import net.anthavio.httl.api.HttlApiBuilder; import net.anthavio.httl.cache.CachedResponse; import net.anthavio.httl.cache.CachingSender; import net.anthavio.httl.marshall.Jackson2Unmarshaller; import net.anthavio.httl.transport.HttpUrlConfig; import net.anthavio.wotan.client.auth.AuthHelper; import net.anthavio.wotan.client.clan.ClanGroup; import net.anthavio.wotan.client.encyclopedia.EncyclopediaGroup; import net.anthavio.wotan.client.ratings.RatingsGroup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; /** * http://eu.wargaming.net/developers/ * * http://eu.wargaming.net/developers/api_reference/wot/ * * @author martin.vanek * */ public class WotanClient implements Closeable { private static final Logger logger = LoggerFactory.getLogger(WotanClient.class); private final WotanSettings settings; private final HttlSender sender; private final CachingSender cachingSender; private final ObjectMapper mapper; private final ApiAccounts accountsApi; public WotanClient(WotanSettings settings) { this(settings, new HttpUrlConfig(settings.getServerUrl()).sender(), null); } public WotanClient(WotanSettings settings, SenderConfigurer config) { this(settings, config, null); } public WotanClient(WotanSettings settings, CacheBase<CachedResponse> cache) { this(settings, new HttpUrlConfig(settings.getServerUrl()).sender(), cache); } public WotanClient(final WotanSettings settings, SenderConfigurer config, CacheBase<CachedResponse> cache) { if (settings == null) { throw new IllegalArgumentException("Null settings"); } this.settings = settings; if (config == null) { throw new IllegalArgumentException("Null config"); } config.setParamSetter(new ConfigurableParamSetter("yyyy-MM-dd HH:mm:ss.SSS")); //2010-06-01 12:21:47.000 config.addBuilderVisitor(new HttlBuilderVisitor() { @Override public void visit(HttlRequestBuilder<?> builder) { builder.param("application_id", settings.getApplicationId()); } }); /* config.addExecutionFilter(new HttlExecutionFilter() { @Override public HttlResponse filter(HttlRequest request, HttlExecutionChain chain) throws IOException { HttlResponse response = chain.next(request); if (response.getHttpStatusCode() != 200) { Disqus.throwException(response, mapper); } return response; } }); */ this.mapper = new ObjectMapper().setVisibility(PropertyAccessor.FIELD, Visibility.ANY); this.mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); //SimpleModule testModule = new SimpleModule("MyModule", new Version(1, 0, 0, null)).addDeserializer(MyType.class, // new MyTypeDeserializer()); Jackson2Unmarshaller jackson = new Jackson2Unmarshaller(mapper); config.setUnmarshaller(jackson); //WOT uses comma sparated string for multiple values config.setParamSetter(new ConfigurableParamSetter() { @Override protected void array(Multival<String> parameters, boolean reset, String paramName, Object array) { int length = Array.getLength(array); if (length != 0) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { Object element = Array.get(array, i); sb.append(element); sb.append(","); } parameters.set(paramName, sb.toString()); } } }); this.sender = config.build(); this.accountsApi = HttlApiBuilder.build(ApiAccounts.class, sender); if (cache != null) { cachingSender = new CachingSender(sender, cache); } else { cachingSender = null; } } public CacheBase<CachedResponse> getCache() { if (cachingSender != null) { return cachingSender.getCache(); } else { return null; } } public void close() { if (cachingSender != null) { cachingSender.close(); } else { sender.close(); } } public WotanSettings getSettings() { return settings; } public ApiAccounts accounts() { return accountsApi; } public AuthHelper authentication() { return new AuthHelper(this); } public ClanGroup clan() { return new ClanGroup(this); } public EncyclopediaGroup encyclopedia() { return new EncyclopediaGroup(this); } public RatingsGroup ratings() { return new RatingsGroup(this); } /* public <T extends WotanResponse> T execute(WotanRequest<?, T> request) { SenderRequest sr = request.buildRequest(); sr.addParameter("application_id", settings.getApplicationId()); if (request.getLanguage() == null && settings.getLanguage() != null) { sr.addParameter("language", settings.getLanguage().getCode()); } SenderResponse response; if (cachingSender != null) { Long cacheSeconds = request.getCacheSeconds(); if (cacheSeconds == null) { cacheSeconds = settings.getCacheSeconds(); } if (cacheSeconds == null) { cacheSeconds = 10 * 60l; } response = this.cachingSender.from(sr).evictTtl(cacheSeconds, TimeUnit.SECONDS).execute(); } else { if (request.getCacheSeconds() != null || settings.getCacheSeconds() != null) { logger.warn("Cache is not configured, setting cache time is futile."); } response = this.sender.execute(sr); } try { T value = mapper.readValue(response.getReader(), request.getConfig().getResponseClass()); if (value.getStatus() == Status.error) { throw new WotanException(value.getError()); } return value; } catch (IOException iox) { throw new WotanException(iox); } } */ }
lgpl-3.0
bigorc/orchestra
src/main/java/org/ini4j/Ini.java
5718
/* * Copyright 2005,2009 Ivan SZKIBA * * 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.ini4j; import org.ini4j.spi.IniBuilder; import org.ini4j.spi.IniFormatter; import org.ini4j.spi.IniHandler; import org.ini4j.spi.IniParser; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.net.URL; public class Ini extends BasicProfile implements Persistable, Configurable { private static final long serialVersionUID = -6029486578113700585L; private Config _config; private File _file; protected IniParser parser; protected IniHandler handler; public Ini() { _config = Config.getGlobal(); } public Ini(Reader input) throws IOException, InvalidFileFormatException { this(); // getConfig().setGlobalSection(true); load(input); } public Ini(InputStream input) throws IOException, InvalidFileFormatException { this(); load(input); } public Ini(URL input) throws IOException, InvalidFileFormatException { this(); load(input); } public Ini(File input) throws IOException, InvalidFileFormatException { this(); _file = input; parser = IniParser.newInstance(getConfig()); handler = newBuilder(); parser.set_operators(":="); handler.setOperator('='); parser.set_comments(";#"); handler.setComment('#'); load(); } public Ini(File input, String operators, char operator) throws IOException, InvalidFileFormatException { this(); _file = input; parser = IniParser.newInstance(getConfig()); parser.set_operators(operators); handler = newBuilder(); handler.setOperator(operator); load(); } public Ini(File input, String operators, char operator, String comments, char comment) throws IOException, InvalidFileFormatException { this(); _file = input; parser = IniParser.newInstance(getConfig()); parser.set_operators(operators); parser.set_comments(comments); handler = newBuilder(); handler.setComment(comment); handler.setOperator(operator); load(); } @Override public Config getConfig() { return _config; } @Override public void setConfig(Config value) { _config = value; } @Override public File getFile() { return _file; } @Override public void setFile(File value) { _file = value; } @Override public void load() throws IOException, InvalidFileFormatException { if (_file == null) { throw new FileNotFoundException(); } load(_file); } @Override public void load(InputStream input) throws IOException, InvalidFileFormatException { load(new InputStreamReader(input, getConfig().getFileEncoding())); } @Override public void load(Reader input) throws IOException, InvalidFileFormatException { IniParser.newInstance(getConfig()).parse(input, newBuilder()); } @Override public void load(File input) throws IOException, InvalidFileFormatException { load(input.toURI().toURL()); } @Override public void load(URL input) throws IOException, InvalidFileFormatException { parser.parse(input, handler); } @Override public void store() throws IOException { if (_file == null) { throw new FileNotFoundException(); } store(_file); } @Override public void store(OutputStream output) throws IOException { store(new OutputStreamWriter(output, getConfig().getFileEncoding())); } @Override public void store(Writer output) throws IOException { store(IniFormatter.newInstance(output, getConfig())); } @Override public void store(File output) throws IOException { OutputStream stream = new FileOutputStream(output); store(stream); stream.close(); } protected IniHandler newBuilder() { return IniBuilder.newInstance(this); } @Override protected void store(IniHandler formatter, Profile.Section section) { if (getConfig().isEmptySection() || (section.size() != 0)) { super.store(formatter, section); } } @Override protected void store(IniHandler formatter, Profile.Section section, String option, int index) { if (getConfig().isMultiOption() || (index == (section.length(option) - 1))) { super.store(formatter, section, option, index); } } @Override boolean isTreeMode() { return getConfig().isTree(); } @Override char getPathSeparator() { return getConfig().getPathSeparator(); } @Override boolean isPropertyFirstUpper() { return getConfig().isPropertyFirstUpper(); } }
lgpl-3.0
jsteenbeeke/andalite
java/src/main/java/com/jeroensteenbeeke/andalite/java/transformation/template/EnumConstantTemplate.java
2258
package com.jeroensteenbeeke.andalite.java.transformation.template; import com.google.common.collect.ImmutableList; import com.jeroensteenbeeke.andalite.java.transformation.EnumScopeOperationBuilder; import com.jeroensteenbeeke.andalite.java.transformation.HasEnumConstantBuilder; import com.jeroensteenbeeke.andalite.java.transformation.JavaRecipeBuilder; import org.jetbrains.annotations.NotNull; public class EnumConstantTemplate implements EnumElementTemplate { private final String name; private final ImmutableList<String> parameterExpressions; private final ImmutableList<EnumConstantElementTemplate> templates; EnumConstantTemplate(String name) { this.name = name; this.parameterExpressions = ImmutableList.of(); this.templates = ImmutableList.of(); } private EnumConstantTemplate(String name, ImmutableList<String> parameterExpressions, ImmutableList<EnumConstantElementTemplate> templates) { this.name = name; this.parameterExpressions = parameterExpressions; this.templates = templates; } public EnumConstantTemplate withParameterExpression(@NotNull String expression) { return new EnumConstantTemplate(name, ImmutableList.<String>builder().addAll(parameterExpressions) .add(expression).build(), templates); } public EnumConstantTemplate withStringParameterExpression(@NotNull String expression) { return new EnumConstantTemplate(name, ImmutableList.<String>builder().addAll(parameterExpressions) .add(String.format("\"%s\"", expression)).build(), templates); } public EnumConstantTemplate with(EnumConstantElementTemplate... templates) { return new EnumConstantTemplate(name, parameterExpressions, ImmutableList.<EnumConstantElementTemplate>builder() .addAll(this.templates) .addAll(ImmutableList.copyOf(templates)) .build()); } @Override public void onEnum(JavaRecipeBuilder builder, EnumScopeOperationBuilder enumBuilder) { HasEnumConstantBuilder enumConstantBuilder = enumBuilder .ensureEnumConstant(); for (String parameter : parameterExpressions) { enumConstantBuilder = enumConstantBuilder.withParameterExpression(parameter); } enumConstantBuilder.named(name); templates.forEach(t -> t.onEnumConstant(builder, enumBuilder.forConstant(name))); } }
lgpl-3.0
sikachu/jasperreports
src/net/sf/jasperreports/data/cache/NumberToBigIntegerOffsetTransformer.java
1844
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2013 Jaspersoft Corporation. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports 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 3 of the License, or * (at your option) any later version. * * JasperReports 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 JasperReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.jasperreports.data.cache; import java.io.Serializable; import java.math.BigInteger; import net.sf.jasperreports.engine.JRConstants; /** * @author Lucian Chirita (lucianc@users.sourceforge.net) * @version $Id: NumberToBigIntegerOffsetTransformer.java 5878 2013-01-07 20:23:13Z teodord $ */ public final class NumberToBigIntegerOffsetTransformer implements ValueTransformer, Serializable { //FIXME lucianc serialized these as Ids private static final long serialVersionUID = JRConstants.SERIAL_VERSION_UID; private final BigInteger offset; public NumberToBigIntegerOffsetTransformer(BigInteger offset) { this.offset = offset; } @Override public Class<?> getResultType() { return BigInteger.class; } public Object get(Object value) { return BigInteger.valueOf(((Number) value).longValue()).add(offset); } }
lgpl-3.0
shawnmckinney/fortressdemo1
src/main/java/com/mycompany/LaunchPage.java
1058
/* * This is free and unencumbered software released into the public domain. */ package com.mycompany; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.request.http.handler.RedirectRequestHandler; import javax.servlet.http.HttpServletRequest; import java.security.Principal; /** * @author Shawn McKinney * @version $Rev$ */ public class LaunchPage extends MyBasePage { public LaunchPage() { HttpServletRequest servletReq = (HttpServletRequest)getRequest().getContainerRequest(); Principal principal = servletReq.getUserPrincipal(); // needed anytime container security checker allows requests in with old cookie (perhaps after server/app restart):: if(principal == null) { // invalidate the session and force the user to log back on: servletReq.getSession().invalidate(); getSession().invalidate(); setResponsePage( LoginPage.class ); } add(new Label("label1", "You have access to the link(s) above.")); } }
unlicense
devacfr/spring-restlet
restlet.ext.xstream/src/test/java/com/pmi/restlet/ext/xstream/impl/AnnotedCustomer.java
2481
package com.pmi.restlet.ext.xstream.impl; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamAsAttribute; import com.thoughtworks.xstream.annotations.XStreamImplicit; @XStreamAlias("customer") public class AnnotedCustomer implements ICustomer { @XStreamAlias("firstName") @XStreamAsAttribute private String firstName; @XStreamAlias("lastName") @XStreamAsAttribute private String lastName; @XStreamImplicit(itemFieldName="city") private List<String> addresses; @XStreamAlias("modificationDate") private Date modificationDate; @Override public boolean equals(Object obj) { return EqualsBuilder.reflectionEquals(this, obj); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } public Date getModificationDate() { return modificationDate; } public void setModificationDate(Date modificationDate) { this.modificationDate = modificationDate; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public List<String> getAddresses() { return addresses; } /* (non-Javadoc) * @see com.pmi.restlet.serialization.ICustomer#setAddresses(java.util.List) */ public void setAddresses(List<String> addresses) { this.addresses = addresses; } @SuppressWarnings("deprecation") public static ICustomer createCustomer() { ICustomer customer = new AnnotedCustomer(); customer.setFirstName("Bernard"); customer.setLastName("Lefevre"); customer.setModificationDate(new Date(2010,2,10)); customer.setAddresses(new ArrayList<String>()); customer.getAddresses().addAll(Arrays.asList("Lyon", "Paris", "Marseille")); return customer; } public static final ICustomer customer = createCustomer(); }
unlicense
kyorohiro/HetimaUtil
test_util/net/hetimatan/net/http/HttpServer3xx.java
2366
package net.hetimatan.net.http; import java.io.IOException; import net.hetimatan.io.file.KyoroFile; import net.hetimatan.io.filen.ByteKyoroFile; import net.hetimatan.util.event.net.io.KyoroSocket; import net.hetimatan.util.http.HttpRequestHeader; import net.hetimatan.util.http.HttpRequest; import net.hetimatan.util.http.HttpResponse; import net.hetimatan.util.io.ByteArrayBuilder; import net.hetimatan.util.log.Log; public class HttpServer3xx extends HttpServerTemplate { private static HttpServer3xx server = null; public static void main(String[] args) { server = new HttpServer3xx(); server.setPort(18080); server.startServer(null); } @Override public KyoroFile createResponse(HttpServerFront front, KyoroSocket socket, HttpRequest uri) throws IOException { HttpHistory.get().pushMessage(sId+"#createResponse:"+front.sId+"\n"); String path = uri.getLine().getRequestURI().getPath(); int index = 0; if(path.startsWith("http://")) { index = path.indexOf("/", "http://".length()); } String address = uri.getValue("mv"); path = path.substring(index); if(path.startsWith("/301")) { return createHeader(HttpResponse.STATUS_CODE_301_MOVE_PERMANENTLY, address); } if(path.startsWith("/302")) { return createHeader(HttpResponse.STATUS_CODE_302_Found, address); } if(path.startsWith("/303")) { return createHeader(HttpResponse.STATUS_CODE_303_SEE_OTHER, address); } if(path.startsWith("/307")) { return createHeader(HttpResponse.STATUS_CODE_307_TEMPORARY_REDIRECT, address); } return super.createResponse(front, socket, uri); } public KyoroFile createHeader(String responce, String location) throws IOException { if(Log.ON){Log.v(TAG, "HttpServer#createHeader");} KyoroFile builder = new ByteKyoroFile(); try { builder.addChunk(("HTTP/1.1 "+responce+"\r\n").getBytes()); builder.addChunk(("Content-Length: "+0+"\r\n").getBytes()); builder.addChunk(("Content-Type: text/plain\r\n").getBytes()); builder.addChunk(("Connection: close\r\n").getBytes()); if(location != null) { builder.addChunk((HttpRequestHeader.HEADER_LOCATION +" :"+location+"\r\n").getBytes()); } builder.addChunk(("\r\n").getBytes()); return builder; } finally { if(Log.ON){Log.v(TAG, "/HttpServer#createHeader");} } } }
unlicense
thucoldwind/ucore_mips
Decaf/src/decaf/backend/RegisterAllocator.java
5291
package decaf.backend; import java.util.HashSet; import java.util.Random; import decaf.Driver; import decaf.dataflow.BasicBlock; import decaf.machdesc.Register; import decaf.tac.Tac; import decaf.tac.Temp; public class RegisterAllocator { private BasicBlock bb; private MipsFrameManager frameManager; private Register[] regs; private Temp fp; public RegisterAllocator(Temp fp, MipsFrameManager frameManager, Register[] regs) { this.fp = fp; this.frameManager = frameManager; this.regs = regs; } public void reset() { frameManager.reset(); } public void alloc(BasicBlock bb) { this.bb = bb; clear(); Tac tail = null; for (Tac tac = bb.tacList; tac != null; tail = tac, tac = tac.next) { switch (tac.opc) { case ADD: case SUB: case MUL: case DIV: case MOD: case LAND: case LOR: case GTR: case GEQ: case EQU: case NEQ: case LEQ: case LES: findRegForRead(tac, tac.op1); findRegForRead(tac, tac.op2); findRegForWrite(tac, tac.op0); break; case NEG: case LNOT: case ASSIGN: findRegForRead(tac, tac.op1); findRegForWrite(tac, tac.op0); break; case LOAD_VTBL: case LOAD_IMM4: case LOAD_STR_CONST: findRegForWrite(tac, tac.op0); break; case INDIRECT_CALL: findRegForRead(tac, tac.op1); case DIRECT_CALL: if (tac.op0 != null) { findRegForWrite(tac, tac.op0); } frameManager.finishActual(); tac.saves = new HashSet<Temp>(); for (Temp t : tac.liveOut) { if (t.reg != null && t.equals(t.reg.var) && !t.equals(tac.op0)) { frameManager.findSlot(t); tac.saves.add(t); } } break; case PARM: findRegForRead(tac, tac.op0); int offset = frameManager.addActual(tac.op0); tac.op1 = Temp.createConstTemp(offset); break; case LOAD: findRegForRead(tac, tac.op1); findRegForWrite(tac, tac.op0); break; case STORE: findRegForRead(tac, tac.op1); findRegForRead(tac, tac.op0); break; case BRANCH: case BEQZ: case BNEZ: case RETURN: throw new IllegalArgumentException(); } } bb.saves = new HashSet<Temp>(); for (Temp t : bb.liveOut) { if (t.reg != null && t.equals(t.reg.var)) { frameManager.findSlot(t); bb.saves.add(t); } } switch (bb.endKind) { case BY_RETURN: case BY_BEQZ: case BY_BNEZ: if (bb.var != null) { if (bb.var.reg != null && bb.var.equals(bb.var.reg.var)) { bb.varReg = bb.var.reg; return; } else { // all live temps have been spilled out, so use any reg is valid bb.var.reg = regs[0]; if (!bb.var.isOffsetFixed()) { Driver .getDriver() .getOption() .getErr() .println( bb.var + " may used before define during register allocation"); frameManager.findSlot(bb.var); } Tac load = Tac.genLoad(bb.var, fp, Temp .createConstTemp(bb.var.offset)); bb.insertAfter(load, tail); bb.varReg = regs[0]; } } } } private Random random = new Random(); private void clear() { for (Register reg : regs) { if (reg.var != null) { reg.var = null; } } } private void bind(Register reg, Temp temp) { reg.var = temp; temp.reg = reg; } private void findReg(Tac tac, Temp temp, boolean read) { // already in reg if (temp.reg != null) { if (temp.equals(temp.reg.var)) { return; } } // find a reg do not need to spill for (Register reg : regs) { if (reg.var == null || !isAlive(tac, reg.var)) { bind(reg, temp); if (read) { load(tac, temp); } return; } } // find a reg which var's offset already fixed to spill for (Register reg : regs) { if (reg.var.isOffsetFixed()) { spill(tac, reg.var); bind(reg, temp); if (read) { load(tac, temp); } return; } } // random select a reg to spill Register reg = regs[random.nextInt(regs.length)]; frameManager.findSlot(reg.var); spill(tac, reg.var); bind(reg, temp); if (read) { load(tac, temp); } } private void findRegForRead(Tac tac, Temp temp) { findReg(tac, temp, true); } private void spill(Tac tac, Temp temp) { Tac spill = Tac.genStore(temp, fp, Temp.createConstTemp(temp.offset)); bb.insertBefore(spill, tac); } private void load(Tac tac, Temp temp) { if (!temp.isOffsetFixed()) { Driver .getDriver() .getOption() .getErr() .println( temp + " may used before define during register allocation"); frameManager.findSlot(temp); } Tac load = Tac.genLoad(temp, fp, Temp.createConstTemp(temp.offset)); bb.insertBefore(load, tac); } private boolean isAlive(Tac tac, Temp temp) { if (tac != null && tac.prev != null) { tac = tac.prev; while (tac != null && tac.liveOut == null) { tac = tac.prev; } if (tac != null) { return tac.liveOut.contains(temp); } } return bb.liveIn.contains(temp); } private void findRegForWrite(Tac tac, Temp temp) { findReg(tac, temp, false); } }
unlicense
caleron/dis2017
src/com/dis/model/References.java
5018
package com.dis.model; import com.dis.data.DB2ConnectionManager; import java.math.BigDecimal; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import java.util.Map; public class References { public Map<Integer, Article> articles = new HashMap<>(); public Map<Integer, City> cities = new HashMap<>(); public Map<Integer, Country> countries = new HashMap<>(); public Map<Integer, ProductCategory> productCategories = new HashMap<>(); public Map<Integer, ProductFamily> productFamilies = new HashMap<>(); public Map<Integer, ProductGroup> productGroups = new HashMap<>(); public Map<Integer, Region> regions = new HashMap<>(); public Map<Integer, Shop> shops = new HashMap<>(); private static References instance; public static References getInstance() { if (instance == null) { try { instance = new References(); } catch (SQLException e) { e.printStackTrace(); System.exit(88); } } return instance; } private References() throws SQLException { Connection connection = DB2ConnectionManager.getInstance().getConnection(); Statement stmt = connection.createStatement(); System.out.print("loading reference data..."); // load countries ResultSet resultSet = stmt.executeQuery("SELECT * FROM DB2INST1.LANDID"); while (resultSet.next()) { Country country = new Country(); country.name = resultSet.getString("NAME"); countries.put(resultSet.getInt("LANDID"), country); } resultSet.close(); // load regions resultSet = stmt.executeQuery("SELECT * FROM DB2INST1.REGIONID"); while (resultSet.next()) { Region region = new Region(); region.name = resultSet.getString("NAME"); region.country = countries.get(resultSet.getInt("LANDID")); region.id = resultSet.getInt("REGIONID"); regions.put(region.id, region); } resultSet.close(); // load cities resultSet = stmt.executeQuery("SELECT * FROM DB2INST1.STADTID"); while (resultSet.next()) { City city = new City(); city.name = resultSet.getString("NAME"); city.region = regions.get(resultSet.getInt("REGIONID")); city.id = resultSet.getInt("STADTID"); cities.put(city.id, city); } resultSet.close(); // load shops resultSet = stmt.executeQuery("SELECT * FROM DB2INST1.SHOPID"); while (resultSet.next()) { Shop shop = new Shop(); shop.name = resultSet.getString("NAME"); shop.city = cities.get(resultSet.getInt("STADTID")); shop.id = resultSet.getInt("SHOPID"); shops.put(shop.id, shop); } resultSet.close(); // load product categories resultSet = stmt.executeQuery("SELECT * FROM DB2INST1.PRODUCTCATEGORYID"); while (resultSet.next()) { ProductCategory category = new ProductCategory(); category.name = resultSet.getString("NAME"); category.id = resultSet.getInt("PRODUCTCATEGORYID"); productCategories.put(category.id, category); } resultSet.close(); // load product families resultSet = stmt.executeQuery("SELECT * FROM DB2INST1.PRODUCTFAMILYID"); while (resultSet.next()) { ProductFamily family = new ProductFamily(); family.name = resultSet.getString("NAME"); family.id = resultSet.getInt("PRODUCTFAMILYID"); family.category = productCategories.get(resultSet.getInt("PRODUCTCATEGORYID")); productFamilies.put(family.id, family); } resultSet.close(); // load product groups resultSet = stmt.executeQuery("SELECT * FROM DB2INST1.PRODUCTGROUPID"); while (resultSet.next()) { ProductGroup group = new ProductGroup(); group.name = resultSet.getString("NAME"); group.id = resultSet.getInt("PRODUCTGROUPID"); group.family = productFamilies.get(resultSet.getInt("PRODUCTFAMILYID")); productGroups.put(group.id, group); } resultSet.close(); // load articles resultSet = stmt.executeQuery("SELECT * FROM DB2INST1.ARTICLEID"); while (resultSet.next()) { Article article = new Article(); article.name = resultSet.getString("NAME"); article.price = resultSet.getBigDecimal("PREIS"); article.id = resultSet.getInt("ARTICLEID"); article.productGroup = productGroups.get(resultSet.getInt("PRODUCTGROUPID")); articles.put(article.id, article); } resultSet.close(); System.out.println("done"); } public static class Article { public String name; public BigDecimal price; public int id; public ProductGroup productGroup; } public class Country { public int id; public String name; } public class ProductCategory { public int id; public String name; } public class ProductFamily { public int id; public String name; public ProductCategory category; } public class ProductGroup { public int id; public String name; public ProductFamily family; } public class Region { public int id; public String name; public Country country; } public class City { public int id; public String name; public Region region; } public class Shop { public int id; public String name; public City city; } }
unlicense
Hajdulord/My.CardGame.Project-akci--reakci-
Card-Game.Main/src/my/cardgame/main/Run.java
123
package my.cardgame.main; public class Run { public static void main(String[] args) { Login.login(); } }
unlicense
sergio-alves/SSME
src/main/java/ch/santosalves/ssme/states/GenericState.java
509
package ch.santosalves.ssme.states; public class GenericState implements IState{ private int id; private String name; public GenericState(int id, String name) { this.id = id; this.name = name; } @Override public int getId() { return this.id; } @Override public String getName() { return this.name; } @Override public Boolean equals(IState actual) { return (actual.getId() == this.id) ; } @Override public String toString() { return "State(" + id + ", " + name + ")"; } }
unlicense
fjamores3/appMies
src/org/mies/censo/pojo/ProvinciaMiesBean.java
1335
package org.mies.censo.pojo; import java.io.Serializable; public class ProvinciaMiesBean implements Serializable{ private static final long serialVersionUID = -5912752878210288198L; private int idProvincia; private String nombre; private PaisMiesBean pais; private long vinculados; private long aspirantes; private long simpatizantes; public ProvinciaMiesBean(){ } public ProvinciaMiesBean(String nombreProv){ this.nombre = nombreProv; } public int getIdProvincia() { return idProvincia; } public void setIdProvincia(int idProvincia) { this.idProvincia = idProvincia; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public PaisMiesBean getPais() { return pais; } public void setPais(PaisMiesBean pais) { this.pais = pais; } public long getVinculados() { return vinculados; } public void setVinculados(long vinculados) { this.vinculados = vinculados; } public long getAspirantes() { return aspirantes; } public void setAspirantes(long aspirantes) { this.aspirantes = aspirantes; } public long getSimpatizantes() { return simpatizantes; } public void setSimpatizantes(long simpatizantes) { this.simpatizantes = simpatizantes; } public String toString(){ return nombre; } }
unlicense
AlgoAnalysis/Algo
MT4Processor/src/com/algotrado/mt4/impl/Pattern.java
1981
package com.algotrado.mt4.impl; import java.io.Serializable; import com.algotrado.mt4.tal.strategy.check.pattern.SingleCandleBarData; public abstract class Pattern implements Serializable { protected int timeFrame; public Pattern () { timeFrame = 15; } public abstract boolean isBullishReversalPattern(SingleCandleBarData[] previousCandles, int index, double pipsValue); public abstract boolean isBearishReversalPattern(SingleCandleBarData[] previousCandles, int index, double pipsValue); public abstract double getPatternHigh(SingleCandleBarData[] previousCandles, int index, double pipsValue); public abstract double getPatternLow(SingleCandleBarData[] previousCandles, int index, double pipsValue); public abstract double getPatternApprovalPoint(SingleCandleBarData[] previousCandles, int index, double pipsValue); public int getNumOfCandlesInPattern() { return 2; } public boolean isReversalPattern(SingleCandleBarData[] previousCandles, int index, double pipsValue) { return isBearishReversalPattern(previousCandles, index, pipsValue) || isBullishReversalPattern(previousCandles, index, pipsValue); } public double getRisk(SingleCandleBarData[] previousCandles, int index, double pipsValue) { if (isBullishReversalPattern(previousCandles, index, pipsValue)) { return getPatternApprovalPoint(previousCandles, index, pipsValue) - getPatternLow(previousCandles, index, pipsValue); } else if (isBearishReversalPattern(previousCandles, index, pipsValue)) { return getPatternHigh(previousCandles, index, pipsValue) - getPatternApprovalPoint(previousCandles, index, pipsValue); } return -1; } public boolean isAbsoluteGAPBetween2Candles(SingleCandleBarData candle1, SingleCandleBarData candle2) { return (candle1.getHigh() < candle2.getLow()) || (candle2.getHigh() < candle1.getLow()); } public int getTimeFrame() { return timeFrame; } public void setTimeFrame(int timeFrame) { this.timeFrame = timeFrame; } }
unlicense
GHJGHJJHG/CTYJava
Pair of Dice/src/DiceDriver.java
462
public class DiceDriver { public static void main(String args[]) { PairOfDice dice = new PairOfDice(); for (int i=0; i<5; i++) { System.out.println(dice.toString()); System.out.println("Dice total: "+ dice.getValue()); if (dice.hasAOne()) System.out.println("This roll has a one"); if (dice.isSnakeEyes()) System.out.println("This roll is Snake Eyes"); dice.roll(); System.out.println(); if (dice.isSnakeEyes()) break; } } }
unlicense
sebhoss/annotated-contracts
contract-frameworks/contract-spring/contract-spring-defaults/src/main/java/com/github/sebhoss/contract/verifier/impl/ErrorMessageConfiguration.java
1944
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org> */ package com.github.sebhoss.contract.verifier.impl; import java.util.Locale; import ch.qos.cal10n.IMessageConveyor; import ch.qos.cal10n.MessageConveyor; import com.github.sebhoss.warnings.CompilerWarnings; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * Configuration for the {@link IMessageConveyor}. */ @Configuration public class ErrorMessageConfiguration { /** * @return English error messages */ @Bean @SuppressWarnings(CompilerWarnings.STATIC_METHOD) public IMessageConveyor english() { return new MessageConveyor(Locale.ENGLISH); } }
unlicense
will-gilbert/SmartGWT-Mobile
mobile/src/main/java/com/smartgwt/mobile/client/types/DateItemSelectorFormat.java
460
package com.smartgwt.mobile.client.types; public enum DateItemSelectorFormat implements ValueEnum { DAY_MONTH_YEAR("DMY"), MONTH_DAY_YEAR("MDY"), YEAR_MONTH_DAY("YMD"), DAY_MONTH("DM"), MONTH_DAY("MD"), YEAR_MONTH("YM"), MONTH_YEAR("MY"); private final String value; private DateItemSelectorFormat(String value) { this.value = value; } public final String getValue() { return this.value; } }
unlicense
clilystudio/NetBook
allsrc/com/ushaqi/zhuishushenqi/model/NotificationRoot.java
577
package com.ushaqi.zhuishushenqi.model; public class NotificationRoot extends Root { private NotificationItem[] notifications = new NotificationItem[0]; public NotificationItem[] getNotifications() { return this.notifications; } public void setNotifications(NotificationItem[] paramArrayOfNotificationItem) { this.notifications = paramArrayOfNotificationItem; } } /* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar * Qualified Name: com.ushaqi.zhuishushenqi.model.NotificationRoot * JD-Core Version: 0.6.0 */
unlicense
temi4hik/StoryApp
app/src/main/java/com/temi4hik/interactivestory/model/Choice.java
393
package com.temi4hik.interactivestory.model; /** * Created by Artem on 19.04.15. */ public class Choice { private String mText; private int mNextPage; public Choice(String text, int nextPage) { mText = text; mNextPage = nextPage; } public String getText() { return mText; } public int getNextPage() { return mNextPage; } }
unlicense
mbucknell/WQP-WQX-Services
src/test/java/gov/usgs/wma/wqp/validation/BBoxValidatorTest.java
2865
package gov.usgs.wma.wqp.validation; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import javax.validation.ConstraintValidatorContext; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import gov.usgs.wma.wqp.BaseTest; import gov.usgs.wma.wqp.parameter.BoundingBox; public class BBoxValidatorTest extends BaseTest { @Mock protected ConstraintValidatorContext context; protected BBoxValidator validator; @BeforeEach public void setUp() { MockitoAnnotations.initMocks(this); validator = new BBoxValidator(); } @Test public void testBbox_allValuesWithinBounds() { BoundingBox bbox = new BoundingBox("-88,43,-86,45"); assertTrue(validator.isValid(bbox, context)); } @Test public void testBbox_NaN() { BoundingBox bbox = new BoundingBox("a,b,c,d"); assertFalse(validator.isValid(bbox, context)); } @Test public void testBbox_firstLatTooLarge() { BoundingBox bbox = new BoundingBox("200,43,-86,45"); assertFalse(validator.isValid(bbox, context)); } @Test public void testBbox_firstLatTooSmall() { BoundingBox bbox = new BoundingBox("-200,43,-86,45"); assertFalse(validator.isValid(bbox, context)); } @Test public void testBbox_firstLongTooLarge() { BoundingBox bbox = new BoundingBox("-88,143,-86,45"); assertFalse(validator.isValid(bbox, context)); } @Test public void testBbox_firstLongTooSmall() { BoundingBox bbox = new BoundingBox("-88,-143,-86,45"); assertFalse(validator.isValid(bbox, context)); } @Test public void testBbox_secondLatTooLarge() { BoundingBox bbox = new BoundingBox("-88,43,200,45"); assertFalse(validator.isValid(bbox, context)); } @Test public void testBbox_secondLarTooSmall() { BoundingBox bbox = new BoundingBox("-88,43,-200,45"); assertFalse(validator.isValid(bbox, context)); } @Test public void testBbox_secondLongTooLarge() { BoundingBox bbox = new BoundingBox("-88,43,-86,145"); assertFalse(validator.isValid(bbox, context)); } @Test public void testBbox_secondLongTooSmall() { BoundingBox bbox = new BoundingBox("-88,43,-86,-145"); assertFalse(validator.isValid(bbox, context)); } @Test public void testBbox_minLatLargerThanMax() { BoundingBox bbox = new BoundingBox("88,43,86,45"); assertFalse(validator.isValid(bbox, context)); } @Test public void testBbox_minLongLagerThanMax() { BoundingBox bbox = new BoundingBox("-88,45,-86,43"); assertFalse(validator.isValid(bbox, context)); } @Test public void testBbox_null() { BoundingBox bbox = new BoundingBox(null); assertTrue(validator.isValid(bbox, context)); } @Test public void testBbox_emptyString() { BoundingBox bbox = new BoundingBox(""); assertTrue(validator.isValid(bbox, context)); } }
unlicense
charlesmadere/that-lil-hummingbird
project/app/src/main/java/com/charlesmadere/hummingbird/views/RatioViewHelper.java
3935
package com.charlesmadere.hummingbird.views; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.View; import com.charlesmadere.hummingbird.R; public final class RatioViewHelper { private static final int FIXED_SIDE_HEIGHT = 0; private static final int FIXED_SIDE_WIDTH = 1; private static final int UNDEFINED = -1; private final int fixedSide; private final int heightRatio; private final int widthRatio; public static RatioViewHelper create(final View view, final AttributeSet attrs) { final Context context = view.getContext(); final TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.View); final RatioViewHelper fixedSide = create(ta); ta.recycle(); return fixedSide; } public static RatioViewHelper create(final TypedArray ta) { final int fixedSide = ta.getInt(R.styleable.View_fixed_side, UNDEFINED); final int heightRatio = ta.getInt(R.styleable.View_height_ratio, UNDEFINED); final int widthRatio = ta.getInt(R.styleable.View_width_ratio, UNDEFINED); if (fixedSide == UNDEFINED || heightRatio == UNDEFINED || widthRatio == UNDEFINED) { throw new IllegalArgumentException("fixed_side, height_ratio, and width_ratio" + " must all be set"); } return new RatioViewHelper(fixedSide, heightRatio, widthRatio); } private RatioViewHelper(final int fixedSide, final int heightRatio, final int widthRatio) { this.fixedSide = fixedSide; this.heightRatio = heightRatio; this.widthRatio = widthRatio; } public int getHeightRatio() { return heightRatio; } public int getWidthRatio() { return widthRatio; } public boolean isFixedSideHeight() { return fixedSide == FIXED_SIDE_HEIGHT; } public boolean isFixedSideWidth() { return fixedSide == FIXED_SIDE_WIDTH; } /** * To be called from your view's {@link View#onMeasure(int, int)} method and then supplied * to its {@link View#setMeasuredDimension(int, int)} method. * * @return * An int array where [0] is the width and [1] is the height. These values should be passed * in as the parameters to {@link View#setMeasuredDimension(int, int)}. */ public int[] measureDimensions(final int widthMeasureSpec, final int heightMeasureSpec) { final int width, height; switch (fixedSide) { case FIXED_SIDE_HEIGHT: height = View.MeasureSpec.getSize(heightMeasureSpec); width = (int) ((float) (height * widthRatio) / (float) heightRatio); break; case FIXED_SIDE_WIDTH: width = View.MeasureSpec.getSize(widthMeasureSpec); height = (int) ((float) (width * heightRatio) / (float) widthRatio); break; default: // this should never happen throw new RuntimeException("unknown fixedSide: " + fixedSide); } return new int[] { width, height }; } /** * to be called from your ViewGroup's {@link android.view.ViewGroup#onMeasure(int, int)} * method * * @return * An int array where [0] is the width measure spec and [1] is the height. These values * should be passed in as the parameters to {@link android.view.ViewGroup#onMeasure(int, int)}. */ public int[] measureSpecDimensions(final int widthMeasureSpec, final int heightMeasureSpec) { final int[] dimensions = measureDimensions(widthMeasureSpec, heightMeasureSpec); dimensions[0] = View.MeasureSpec.makeMeasureSpec(dimensions[0], View.MeasureSpec.EXACTLY); dimensions[1] = View.MeasureSpec.makeMeasureSpec(dimensions[1], View.MeasureSpec.EXACTLY); return dimensions; } }
unlicense
cc14514/hq6
hq-web/src/main/java/org/hyperic/hq/ui/util/minitab/SubMiniTab.java
2754
/* * NOTE: This copyright does *not* cover user programs that use HQ * program services by normal system calls through the application * program interfaces provided as part of the Hyperic Plug-in Development * Kit or the Hyperic Client Development Kit - this is merely considered * normal use of the program, and does *not* fall under the heading of * "derived work". * * Copyright (C) [2004, 2005, 2006], Hyperic, Inc. * This file is part of HQ. * * HQ is free software; you can redistribute it and/or modify * it under the terms version 2 of the GNU General Public License as * published by the Free Software Foundation. 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA. */ package org.hyperic.hq.ui.util.minitab; /** * A simple bean that represents a subminitab in the monitor * subsection. */ public class SubMiniTab { //-------------------------------------instance variables private String count; private String id; private String key; private String name; private String param; private Boolean selected; //-------------------------------------constructors public SubMiniTab() { super(); } //-------------------------------------public methods public String getCount() { return count; } public void setCount(String s) { count = s; } public String getId() { return id; } public void setId(String s) { id = s; } public String getKey() { return key; } public void setKey(String s) { key = s; } public String getName() { return name; } public void setName(String s) { name = s; } public String getParam() { return param; } public void setParam(String s) { param = s; } public Boolean getSelected() { return selected; } public void setSelected(Boolean b) { selected = b; } public String toString() { StringBuffer b = new StringBuffer("{"); b.append("name=").append(name); b.append(" id=").append(id); b.append(" count=").append(count); b.append(" key=").append(key); b.append(" param=").append(param); b.append(" selected=").append(selected); return b.append("}").toString(); } }
unlicense
jonestimd/subsets
src/main/java/io/github/jonestimd/subset/SubsetSearch.java
4137
package io.github.jonestimd.subset; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * This class finds subsets of a collection that match some criteria. The criteria are specified by an implementation * of {@link SubsetPredicate}. The {@code static} factory methods can be used to create an instance of this class based * on the category (uniform sign or mixed sign) of the collection. * * <p>The subsets are searched by adding and removing items to a working subset and notifying the predicate. When an * item is added to the working subset,the predicate returns a {@link SubsetPredicateResult} indicating if the current * subset matches the criteria. When an item is removed from the working subset, the predicate is notified so that * it can update its state. For subsets that do not meet the criteria, the predicate can return one of 3 values, * to indicate how the search should proceed. The first 2 values should be used for uniform sign collections and * the last value should be used for mixed sign collections. * <ul> * <li>{@link SubsetPredicateResult#TOO_FEW} - items should be added to the subset to move toward the goal</li> * <li>{@link SubsetPredicateResult#TOO_MANY} - items should be removed from the subset to move toward the goal</li> * <li>{@link SubsetPredicateResult#NO_MATCH} - it is unknown if items should be added or removed</li> * </ul> * * <p><strong>Note:</strong> This class is not thread safe and each instance should only be accessed by a single thread. */ public abstract class SubsetSearch<T> { private SubsetPredicate<T> criteria; private List<List<T>> matches = new ArrayList<>(); private CombinationVisitor<T> accumulator = new CombinationVisitor<T>() { public boolean itemAdded(List<T> subset, T item) { SubsetPredicateResult result = criteria.apply(item); if (result == SubsetPredicateResult.MATCH) { matches.add(subset); } return ! isEndNode(result); } public void itemRemoved(T item) { criteria.remove(item); } }; protected SubsetSearch(SubsetPredicate<T> criteria) { this.criteria = criteria; } /** * Perform the search for subsets matching the criteria. * @return the matching subsets */ public List<List<T>> findSubSets(Collection<T> items) { return findSubSets(new ArrayList<>(items)); } /** * Perform the search for subsets matching the criteria. * @return the matching subsets */ public List<List<T>> findSubSets(List<T> items) { criteria.reset(); matches.clear(); Combinations.visitCombinations(items, accumulator); return matches; } /** * @return true if the result indicates that supersets of the current set will not match. */ protected abstract boolean isEndNode(SubsetPredicateResult result); /** * Create a {@link SubsetSearch} for use on a collection having uniform sign (e.g. all positive or negative numbers with no zeros). * The returned instance will not consider supersets of a subset for which the predicate returns * {@link SubsetPredicateResult#MATCH} or {@link SubsetPredicateResult#TOO_MANY}. */ public static <T> SubsetSearch<T> uniformSign(SubsetPredicate<T> criteria) { return new SubsetSearch<T>(criteria) { protected boolean isEndNode(SubsetPredicateResult result) { return result == SubsetPredicateResult.MATCH || result == SubsetPredicateResult.TOO_MANY; } }; } /** * Create a {@link SubsetSearch} for use on a collection having mixed sign (e.g. a mix of positive numbers, * negative numbers and zeros). The returned instance will consider all possible subsets. */ public static <T> SubsetSearch<T> mixedSign(SubsetPredicate<T> criteria) { return new SubsetSearch<T>(criteria) { protected boolean isEndNode(SubsetPredicateResult result) { return false; } }; } }
unlicense
lizij/Leetcode
src/Monotone_Increasing_Digits/Solution.java
2455
package Monotone_Increasing_Digits; import java.util.ArrayList; import java.util.List; public class Solution { public int monotoneIncreasingDigits(int N) { /** * Greedy solution * If N in [0, 9]: return N * Get every digits of N, for digits[i]: * If digits[i] > digits[i + 1]: we need to digits[i]--, then set digits[(i+1)...] as 9. * But if digits[i - 1] > digits[i] after digits[i]-- * we need to find the most front i which won't have this problem before setting. * 22ms */ // [0, 9], return itself // if (N <= 9) { // return N; // } // // List<Integer> digits = getDigits(N); // get all digits // for (int i = 0; i < digits.size() - 1; i++) { // if (digits.get(i) > digits.get(i + 1)) { // // if digits[i] > digits[i + 1]: digits[i]--, digits[(i+1)...] = 9 // digits.set(i, digits.get(i) - 1); // while (i - 1 >= 0 && digits.get(i) < digits.get(i - 1)) { // digits.set(i - 1, digits.get(i - 1) - 1); // i--; // } // // for (int j = i + 1; j < digits.size(); j++) { // digits.set(j, 9); // } // break; // } // } // // int res = 0; // for (int i = 0; i < digits.size(); i++) { // res = res * 10 + digits.get(i); // } // // return res; /** * Use string to get digits and do the same thing, more faster * */ char[] S = String.valueOf(N).toCharArray(); int i = 1; while (i < S.length && S[i-1] <= S[i]) i++; while (0 < i && i < S.length && S[i-1] > S[i]) S[--i]--; for (int j = i+1; j < S.length; ++j) S[j] = '9'; return Integer.parseInt(String.valueOf(S)); } private List<Integer> getDigits(int n) { List<Integer> digits = new ArrayList<>(); while (n > 0) { digits.add(0, n % 10); n /= 10; } return digits; } public static void main(String[] args) { Solution s = new Solution(); System.out.println(s.monotoneIncreasingDigits(10)); // 9 System.out.println(s.monotoneIncreasingDigits(1234)); // 1234 System.out.println(s.monotoneIncreasingDigits(332)); // 299 System.out.println(s.monotoneIncreasingDigits(33425)); // 33399 } }
unlicense
TheGoodlike13/goodlike-utils
src/main/java/eu/goodlike/libraries/jooq/CommandsManyImpl.java
2686
package eu.goodlike.libraries.jooq; import eu.goodlike.neat.Null; import org.jooq.*; import java.util.Collection; import java.util.function.Supplier; public final class CommandsManyImpl<R extends Record, Left, Right> extends SQL implements CommandsMany<Left, Right> { @Override public void setUniversalCondition(Supplier<Condition> universalCondition) { throw new UnsupportedOperationException("Many-to-many tables are intended to be simple, without " + "any overhead; write your own code for complex scenarios!"); } @Override public int create(Collection<Left> leftValues, Collection<Right> rightValues) { Null.checkCollection(leftValues).ifAny("Left values cannot be null"); if (leftValues.isEmpty()) throw new IllegalArgumentException("At least one value should be provided"); Null.checkCollection(rightValues).ifAny("Right values cannot be null"); if (rightValues.isEmpty()) throw new IllegalArgumentException("At least one value should be provided"); InsertValuesStep2<R, Left, Right> step = sql.insertInto(table, leftField, rightField); for (Left left : leftValues) for (Right right : rightValues) step = step.values(left, right); return step.execute(); } @Override public int deleteLeft(Collection<Left> leftValues) { Null.checkCollection(leftValues).ifAny("Left values cannot be null"); if (leftValues.isEmpty()) throw new IllegalArgumentException("At least one value should be provided"); return sql.deleteFrom(table) .where(condition(leftValues, leftField)) .execute(); } @Override public int deleteRight(Collection<Right> rightValues) { Null.checkCollection(rightValues).ifAny("Right values cannot be null"); if (rightValues.isEmpty()) throw new IllegalArgumentException("At least one value should be provided"); return sql.deleteFrom(table) .where(condition(rightValues, rightField)) .execute(); } // CONSTRUCTORS public CommandsManyImpl(DSLContext sql, Table<R> table, TableField<R, Left> leftField, TableField<R, Right> rightField) { Null.check(sql, table, leftField, rightField).ifAny("DSLContext, table, leftField and rightField cannot be null"); this.sql = sql; this.table = table; this.leftField = leftField; this.rightField = rightField; } // PRIVATE private final DSLContext sql; private final Table<R> table; private final TableField<R, Left> leftField; private final TableField<R, Right> rightField; }
unlicense
RedTriplane/RedTriplane
r3-box2d-jf/src/org/jbox2d/f/collision/Manifold.java
4119
/******************************************************************************* * Copyright (c) 2013, Daniel Murphy * 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. * * 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 HOLDER 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.jbox2d.f.collision; import org.jbox2d.f.common.Settings; import org.jbox2d.f.common.Vector2; /** * A manifold for two touching convex shapes. Box2D supports multiple types of contact: * <ul> * <li>clip point versus plane with radius</li> * <li>point versus point with radius (circles)</li> * </ul> * The local point usage depends on the manifold type: * <ul> * <li>e_circles: the local center of circleA</li> * <li>e_faceA: the center of faceA</li> * <li>e_faceB: the center of faceB</li> * </ul> * Similarly the local normal usage: * <ul> * <li>e_circles: not used</li> * <li>e_faceA: the normal on polygonA</li> * <li>e_faceB: the normal on polygonB</li> * </ul> * We store contacts in this way so that position correction can account for movement, which is * critical for continuous physics. All contact scenarios must be expressed in one of these types. * This structure is stored across time steps, so we keep it small. */ public class Manifold { public static enum ManifoldType { CIRCLES, FACE_A, FACE_B } /** The points of contact. */ public final ManifoldPoint[] points; /** not use for Type::e_points */ public final Vector2 localNormal; /** usage depends on manifold type */ public final Vector2 localPoint; public ManifoldType type; /** The number of manifold points. */ public int pointCount; /** * creates a manifold with 0 points, with it's points array full of instantiated ManifoldPoints. */ public Manifold() { points = new ManifoldPoint[Settings.maxManifoldPoints]; for (int i = 0; i < Settings.maxManifoldPoints; i++) { points[i] = new ManifoldPoint(); } localNormal = new Vector2(); localPoint = new Vector2(); pointCount = 0; } /** * Creates this manifold as a copy of the other * * @param other */ public Manifold(Manifold other) { points = new ManifoldPoint[Settings.maxManifoldPoints]; localNormal = other.localNormal.clone(); localPoint = other.localPoint.clone(); pointCount = other.pointCount; type = other.type; // djm: this is correct now for (int i = 0; i < Settings.maxManifoldPoints; i++) { points[i] = new ManifoldPoint(other.points[i]); } } /** * copies this manifold from the given one * * @param cp manifold to copy from */ public void set(Manifold cp) { for (int i = 0; i < cp.pointCount; i++) { points[i].set(cp.points[i]); } type = cp.type; localNormal.set(cp.localNormal); localPoint.set(cp.localPoint); pointCount = cp.pointCount; } }
unlicense
lucasPereira/estoria
java/br/ufsc/ine/leb/projetos/estoria/EspiaoDeEscolta.java
2061
package br.ufsc.ine.leb.projetos.estoria; import java.util.LinkedList; import java.util.List; import org.junit.runner.Description; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; public final class EspiaoDeEscolta extends RunListener { private List<Notificacao> notificacoes; public EspiaoDeEscolta() { notificacoes = new LinkedList<>(); } @Override public void testRunStarted(Description descricao) throws Exception { super.testRunStarted(descricao); Notificacao notificacao = new Notificacao(TipoDeNotificacao.TESTES_INICIADOS, descricao); notificacoes.add(notificacao); } @Override public void testStarted(Description descricao) throws Exception { super.testStarted(descricao); Notificacao notificacao = new Notificacao(TipoDeNotificacao.TESTE_INICIADO, descricao); notificacoes.add(notificacao); } @Override public void testFinished(Description descricao) throws Exception { super.testFinished(descricao); Notificacao notificacao = new Notificacao(TipoDeNotificacao.TESTE_FINALIZADO, descricao); notificacoes.add(notificacao); } @Override public void testIgnored(Description descricao) throws Exception { super.testIgnored(descricao); Notificacao notificacao = new Notificacao(TipoDeNotificacao.TESTE_IGNORADO, descricao); notificacoes.add(notificacao); } @Override public void testFailure(Failure falha) throws Exception { super.testFailure(falha); Notificacao notificacao = new Notificacao(TipoDeNotificacao.TESTE_FALHA, falha); notificacoes.add(notificacao); } @Override public void testRunFinished(Result resultado) throws Exception { super.testRunFinished(resultado); Notificacao notificacao = new Notificacao(TipoDeNotificacao.TESTES_FINALIZADOS, resultado); notificacoes.add(notificacao); } @Override public void testAssumptionFailure(Failure falha) { super.testAssumptionFailure(falha); notificacoes.add(null); } public List<Notificacao> obterNotificacoes() { return notificacoes; } }
unlicense
katjahahn/PortEx
src/main/java/com/github/katjahahn/parser/sections/debug/package-info.java
863
/******************************************************************************* * Copyright 2014 Katja Hahn * * 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. ******************************************************************************/ /** * Debug section parser. * * @author Katja Hahn * */ package com.github.katjahahn.parser.sections.debug;
apache-2.0
spring-projects/spring-framework
spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockMvcWebClientBuilderTests.java
6242
/* * Copyright 2002-2020 the original author or authors. * * 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 * * https://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.springframework.test.web.servlet.htmlunit; import java.io.IOException; import java.net.URL; import com.gargoylesoftware.htmlunit.HttpMethod; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.WebRequest; import com.gargoylesoftware.htmlunit.WebResponse; import com.gargoylesoftware.htmlunit.util.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Integration tests for {@link MockMvcWebClientBuilder}. * * @author Rob Winch * @author Sam Brannen * @author Rossen Stoyanchev * @since 4.2 */ @SpringJUnitWebConfig class MockMvcWebClientBuilderTests { private MockMvc mockMvc; MockMvcWebClientBuilderTests(WebApplicationContext wac) { this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); } @Test void mockMvcSetupNull() { assertThatIllegalArgumentException().isThrownBy(() -> MockMvcWebClientBuilder.mockMvcSetup(null)); } @Test void webAppContextSetupNull() { assertThatIllegalArgumentException().isThrownBy(() -> MockMvcWebClientBuilder.webAppContextSetup(null)); } @Test void mockMvcSetupWithDefaultWebClientDelegate() throws Exception { WebClient client = MockMvcWebClientBuilder.mockMvcSetup(this.mockMvc).build(); assertMockMvcUsed(client, "http://localhost/test"); } @Test void mockMvcSetupWithCustomWebClientDelegate() throws Exception { WebClient otherClient = new WebClient(); WebClient client = MockMvcWebClientBuilder.mockMvcSetup(this.mockMvc).withDelegate(otherClient).build(); assertMockMvcUsed(client, "http://localhost/test"); } @Test // SPR-14066 void cookieManagerShared() throws Exception { this.mockMvc = MockMvcBuilders.standaloneSetup(new CookieController()).build(); WebClient client = MockMvcWebClientBuilder.mockMvcSetup(this.mockMvc).build(); assertThat(getResponse(client, "http://localhost/").getContentAsString()).isEqualTo("NA"); client.getCookieManager().addCookie(new Cookie("localhost", "cookie", "cookieManagerShared")); assertThat(getResponse(client, "http://localhost/").getContentAsString()).isEqualTo("cookieManagerShared"); } @Test // SPR-14265 void cookiesAreManaged() throws Exception { this.mockMvc = MockMvcBuilders.standaloneSetup(new CookieController()).build(); WebClient client = MockMvcWebClientBuilder.mockMvcSetup(this.mockMvc).build(); assertThat(getResponse(client, "http://localhost/").getContentAsString()).isEqualTo("NA"); assertThat(postResponse(client, "http://localhost/?cookie=foo").getContentAsString()).isEqualTo("Set"); assertThat(getResponse(client, "http://localhost/").getContentAsString()).isEqualTo("foo"); assertThat(deleteResponse(client, "http://localhost/").getContentAsString()).isEqualTo("Delete"); assertThat(getResponse(client, "http://localhost/").getContentAsString()).isEqualTo("NA"); } private void assertMockMvcUsed(WebClient client, String url) throws Exception { assertThat(getResponse(client, url).getContentAsString()).isEqualTo("mvc"); } private WebResponse getResponse(WebClient client, String url) throws IOException { return createResponse(client, new WebRequest(new URL(url))); } private WebResponse postResponse(WebClient client, String url) throws IOException { return createResponse(client, new WebRequest(new URL(url), HttpMethod.POST)); } private WebResponse deleteResponse(WebClient client, String url) throws IOException { return createResponse(client, new WebRequest(new URL(url), HttpMethod.DELETE)); } private WebResponse createResponse(WebClient client, WebRequest request) throws IOException { return client.getWebConnection().getResponse(request); } @Configuration @EnableWebMvc static class Config { @RestController static class ContextPathController { @RequestMapping("/test") String contextPath(HttpServletRequest request) { return "mvc"; } } } @RestController static class CookieController { static final String COOKIE_NAME = "cookie"; @RequestMapping(path = "/", produces = "text/plain") String cookie(@CookieValue(name = COOKIE_NAME, defaultValue = "NA") String cookie) { return cookie; } @PostMapping(path = "/", produces = "text/plain") String setCookie(@RequestParam String cookie, HttpServletResponse response) { response.addCookie(new jakarta.servlet.http.Cookie(COOKIE_NAME, cookie)); return "Set"; } @DeleteMapping(path = "/", produces = "text/plain") String deleteCookie(HttpServletResponse response) { jakarta.servlet.http.Cookie cookie = new jakarta.servlet.http.Cookie(COOKIE_NAME, ""); cookie.setMaxAge(0); response.addCookie(cookie); return "Delete"; } } }
apache-2.0
hectorlarios/turtle-blog
src/com/csc/web/tags/CscGet.java
3864
package com.csc.web.tags; import java.io.IOException; import java.util.Hashtable; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.TagSupport; /** * @author Hector * @date Aug 8, 2011 */ //com.csc.turtleblog.tags.HistoryTagSupport public class CscGet extends TagSupport { //------------------------- //numbers //------------------------- private static final long serialVersionUID = 1L; //------------------------- //strings //------------------------- final protected static String SIMPLE_TAG_SUPPORT = "simpleTagSupport"; //**************************************************************************************************** //Begin - Constructor //**************************************************************************************************** public CscGet() { } //**************************************************************************************************** //End - Constructor //**************************************************************************************************** //**************************************************************************************************** //Begin - Get/Set Methods //**************************************************************************************************** protected String _name; public void setName(String value) {_name=value;} protected String _id; public void setId(String value) {_id=value;} protected String _length; public void setLength(String value) {_length=value;} protected String _default; public void setDefault(String value) {_default=value;} //**************************************************************************************************** //End - Get/Set Methods //**************************************************************************************************** //**************************************************************************************************** //Begin - Private Methods //**************************************************************************************************** protected Hashtable<String, String> getProperties() { @SuppressWarnings("unchecked") Hashtable<String, String> _value = (Hashtable<String, String>)pageContext.getAttribute(SIMPLE_TAG_SUPPORT,PageContext.REQUEST_SCOPE); if(_value==null) { _value = new Hashtable<String, String>(); pageContext.setAttribute(SIMPLE_TAG_SUPPORT,_value,PageContext.REQUEST_SCOPE); } return _value; } //**************************************************************************************************** //End - Private Methods //**************************************************************************************************** //**************************************************************************************************** //Begin - Public Methods //**************************************************************************************************** public int doStartTag() { Hashtable<String, String> _properties = getProperties(); String _value = null; if(_id!=null) { _value = _properties.get(_id); try {pageContext.include(_value);} catch(Exception ex){} } else { JspWriter _out = pageContext.getOut(); _value = _properties.get(_name); if(_value==null)_value=_default!=null?_default:"";//_name+": ValueIsNull"; try { _out.println(_value); } catch (IOException e){} } return SKIP_BODY; } //**************************************************************************************************** //End - Public Methods //**************************************************************************************************** }
apache-2.0
dremio/dremio-oss
sabot/kernel/src/main/java/com/dremio/exec/planner/logical/EnumerableRule.java
1448
/* * Copyright (C) 2017-2019 Dremio Corporation * * 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.dremio.exec.planner.logical; import org.apache.calcite.adapter.enumerable.EnumerableConvention; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.convert.ConverterRule; /** * Rule that converts any Dremio relational expression to enumerable format by adding a {@link ScreenRelBase}. */ public class EnumerableRule extends ConverterRule { public static EnumerableRule INSTANCE = new EnumerableRule(); private EnumerableRule() { super(RelNode.class, Rel.LOGICAL, EnumerableConvention.INSTANCE, "EnumerableRule."); } @Override public boolean isGuaranteed() { return true; } @Override public RelNode convert(RelNode rel) { assert rel.getTraitSet().contains(Rel.LOGICAL); return new ScreenRel(rel.getCluster(), rel.getTraitSet().replace(getOutConvention()), rel); } }
apache-2.0
DariusX/camel
components/camel-coap/src/main/java/org/apache/camel/coap/CoAPEndpoint.java
16113
/* * 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.camel.coap; import java.io.IOException; import java.net.InetSocketAddress; import java.net.URI; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import org.apache.camel.Category; import org.apache.camel.Consumer; import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.spi.UriEndpoint; import org.apache.camel.spi.UriParam; import org.apache.camel.spi.UriPath; import org.apache.camel.support.DefaultEndpoint; import org.apache.camel.support.jsse.ClientAuthentication; import org.apache.camel.support.jsse.KeyManagersParameters; import org.apache.camel.support.jsse.SSLContextParameters; import org.eclipse.californium.core.CoapServer; import org.eclipse.californium.scandium.DTLSConnector; import org.eclipse.californium.scandium.config.DtlsConnectorConfig; import org.eclipse.californium.scandium.dtls.CertificateType; import org.eclipse.californium.scandium.dtls.pskstore.PskStore; import org.eclipse.californium.scandium.dtls.rpkstore.TrustedRpkStore; /** * Send and receive messages to/from COAP capable devices. */ @UriEndpoint(firstVersion = "2.16.0", scheme = "coap,coaps,coap+tcp,coaps+tcp", title = "CoAP", syntax = "coap:uri", category = {Category.IOT}) public class CoAPEndpoint extends DefaultEndpoint { @UriPath private URI uri; @UriParam(label = "consumer") private String coapMethodRestrict; @UriParam private PrivateKey privateKey; @UriParam private PublicKey publicKey; @UriParam private TrustedRpkStore trustedRpkStore; @UriParam private PskStore pskStore; @UriParam private String cipherSuites; private String[] configuredCipherSuites; @UriParam private String clientAuthentication; @UriParam private String alias; @UriParam private SSLContextParameters sslContextParameters; @UriParam(defaultValue = "true") private boolean recommendedCipherSuitesOnly = true; private CoAPComponent component; public CoAPEndpoint(String uri, CoAPComponent component) { super(uri, component); try { this.uri = new URI(uri); } catch (java.net.URISyntaxException use) { this.uri = null; } this.component = component; } public void setCoapMethodRestrict(String coapMethodRestrict) { this.coapMethodRestrict = coapMethodRestrict; } /** * Comma separated list of methods that the CoAP consumer will bind to. The * default is to bind to all methods (DELETE, GET, POST, PUT). */ public String getCoapMethodRestrict() { return this.coapMethodRestrict; } @Override public Producer createProducer() throws Exception { return new CoAPProducer(this); } @Override public Consumer createConsumer(Processor processor) throws Exception { return new CoAPConsumer(this, processor); } public void setUri(URI u) { uri = u; } /** * The URI for the CoAP endpoint */ public URI getUri() { return uri; } public CoapServer getCoapServer() throws IOException, GeneralSecurityException { return component.getServer(getUri().getPort(), this); } /** * Gets the alias used to query the KeyStore for the private key and * certificate. This parameter is used when we are enabling TLS with * certificates on the service side, and similarly on the client side when * TLS is used with certificates and client authentication. If the parameter * is not specified then the default behavior is to use the first alias in * the keystore that contains a key entry. This configuration parameter does * not apply to configuring TLS via a Raw Public Key or a Pre-Shared Key. */ public String getAlias() { return alias; } /** * Sets the alias used to query the KeyStore for the private key and * certificate. This parameter is used when we are enabling TLS with * certificates on the service side, and similarly on the client side when * TLS is used with certificates and client authentication. If the parameter * is not specified then the default behavior is to use the first alias in * the keystore that contains a key entry. This configuration parameter does * not apply to configuring TLS via a Raw Public Key or a Pre-Shared Key. */ public void setAlias(String alias) { this.alias = alias; } /** * Get the SSLContextParameters object for setting up TLS. This is required * for coaps+tcp, and for coaps when we are using certificates for TLS (as * opposed to RPK or PKS). */ public SSLContextParameters getSslContextParameters() { return sslContextParameters; } /** * Set the SSLContextParameters object for setting up TLS. This is required * for coaps+tcp, and for coaps when we are using certificates for TLS (as * opposed to RPK or PKS). */ public void setSslContextParameters(SSLContextParameters sslContextParameters) { this.sslContextParameters = sslContextParameters; } /** * Get the TrustedRpkStore to use to determine trust in raw public keys. */ public TrustedRpkStore getTrustedRpkStore() { return trustedRpkStore; } /** * Set the TrustedRpkStore to use to determine trust in raw public keys. */ public void setTrustedRpkStore(TrustedRpkStore trustedRpkStore) { this.trustedRpkStore = trustedRpkStore; } /** * Get the PskStore to use for pre-shared key. */ public PskStore getPskStore() { return pskStore; } /** * Set the PskStore to use for pre-shared key. */ public void setPskStore(PskStore pskStore) { this.pskStore = pskStore; } /** * Get the configured private key for use with Raw Public Key. */ public PrivateKey getPrivateKey() { return privateKey; } /** * Set the configured private key for use with Raw Public Key. */ public void setPrivateKey(PrivateKey privateKey) { this.privateKey = privateKey; } /** * Get the configured public key for use with Raw Public Key. */ public PublicKey getPublicKey() { return publicKey; } /** * Set the configured public key for use with Raw Public Key. */ public void setPublicKey(PublicKey publicKey) { this.publicKey = publicKey; } /** * Gets the cipherSuites String. This is a comma separated String of * ciphersuites to configure. If it is not specified, then it falls back to * getting the ciphersuites from the sslContextParameters object. */ public String getCipherSuites() { return cipherSuites; } /** * Sets the cipherSuites String. This is a comma separated String of * ciphersuites to configure. If it is not specified, then it falls back to * getting the ciphersuites from the sslContextParameters object. */ public void setCipherSuites(String cipherSuites) { this.cipherSuites = cipherSuites; if (cipherSuites != null) { configuredCipherSuites = cipherSuites.split(","); } } private String[] getConfiguredCipherSuites() { if (configuredCipherSuites != null) { return configuredCipherSuites; } else if (sslContextParameters != null && sslContextParameters.getCipherSuites() != null) { return sslContextParameters.getCipherSuites().getCipherSuite().toArray(new String[0]); } return null; } /** * Gets the configuration options for server-side client-authentication * requirements. The value is either null or one of NONE, WANT, REQUIRE. If * this value is not specified, then it falls back to checking the * sslContextParameters.getServerParameters().getClientAuthentication() * value. */ public String getClientAuthentication() { return clientAuthentication; } /** * Sets the configuration options for server-side client-authentication * requirements. The value must be one of NONE, WANT, REQUIRE. If this value * is not specified, then it falls back to checking the * sslContextParameters.getServerParameters().getClientAuthentication() * value. */ public void setClientAuthentication(String clientAuthentication) { this.clientAuthentication = clientAuthentication; } public boolean isRecommendedCipherSuitesOnly() { return recommendedCipherSuitesOnly; } /** * The CBC cipher suites are not recommended. If you want to use them, you * first need to set the recommendedCipherSuitesOnly option to false. */ public void setRecommendedCipherSuitesOnly(boolean recommendedCipherSuitesOnly) { this.recommendedCipherSuitesOnly = recommendedCipherSuitesOnly; } public boolean isClientAuthenticationRequired() { String clientAuth = clientAuthentication; if (clientAuth == null && sslContextParameters != null && sslContextParameters.getServerParameters() != null) { clientAuth = sslContextParameters.getServerParameters().getClientAuthentication(); } return clientAuth != null && ClientAuthentication.valueOf(clientAuth) == ClientAuthentication.REQUIRE; } public boolean isClientAuthenticationWanted() { String clientAuth = clientAuthentication; if (clientAuth == null && sslContextParameters != null && sslContextParameters.getServerParameters() != null) { clientAuth = sslContextParameters.getServerParameters().getClientAuthentication(); } return clientAuth != null && ClientAuthentication.valueOf(clientAuth) == ClientAuthentication.WANT; } /** * Get all the certificates contained in the sslContextParameters truststore */ private Certificate[] getTrustedCerts() throws GeneralSecurityException, IOException { if (sslContextParameters != null && sslContextParameters.getTrustManagers() != null) { KeyStore trustStore = sslContextParameters.getTrustManagers().getKeyStore().createKeyStore(); Enumeration<String> aliases = trustStore.aliases(); List<Certificate> trustCerts = new ArrayList<>(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); X509Certificate cert = (X509Certificate)trustStore.getCertificate(alias); if (cert != null) { trustCerts.add(cert); } } return trustCerts.toArray(new Certificate[0]); } return new Certificate[0]; } public static boolean enableDTLS(URI uri) { return "coaps".equals(uri.getScheme()); } public static boolean enableTCP(URI uri) { return uri.getScheme().endsWith("+tcp"); } public DTLSConnector createDTLSConnector(InetSocketAddress address, boolean client) throws IOException { DtlsConnectorConfig.Builder builder = new DtlsConnectorConfig.Builder(); if (client) { if (trustedRpkStore == null && sslContextParameters == null && pskStore == null) { throw new IllegalStateException("Either a trustedRpkStore, sslContextParameters or pskStore object " + "must be configured for a TLS client"); } builder.setRecommendedCipherSuitesOnly(isRecommendedCipherSuitesOnly()); builder.setClientOnly(); } else { if (privateKey == null && sslContextParameters == null && pskStore == null) { throw new IllegalStateException("Either a privateKey, sslContextParameters or pskStore object " + "must be configured for a TLS service"); } if (privateKey != null && publicKey == null) { throw new IllegalStateException("A public key must be configured to use a Raw Public Key with TLS"); } if ((isClientAuthenticationRequired() || isClientAuthenticationWanted()) && (sslContextParameters == null || sslContextParameters.getTrustManagers() == null) && publicKey == null) { throw new IllegalStateException("A truststore must be configured to support TLS client authentication"); } builder.setAddress(address); builder.setClientAuthenticationRequired(isClientAuthenticationRequired()); builder.setClientAuthenticationWanted(isClientAuthenticationWanted()); builder.setRecommendedCipherSuitesOnly(isRecommendedCipherSuitesOnly()); } try { // Configure the identity if the sslContextParameters or privateKey // parameter is specified if (sslContextParameters != null && sslContextParameters.getKeyManagers() != null) { KeyManagersParameters keyManagers = sslContextParameters.getKeyManagers(); KeyStore keyStore = keyManagers.getKeyStore().createKeyStore(); // Use the configured alias or fall back to the first alias in // the keystore that contains a key String alias = getAlias(); if (alias == null) { Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String ksAlias = aliases.nextElement(); if (keyStore.isKeyEntry(ksAlias)) { alias = ksAlias; break; } } } if (alias == null) { throw new IllegalStateException("The sslContextParameters keystore must contain a key entry"); } PrivateKey privateKey = (PrivateKey)keyStore.getKey(alias, keyManagers.getKeyPassword().toCharArray()); builder.setIdentity(privateKey, keyStore.getCertificateChain(alias)); } else if (privateKey != null) { builder.setIdentity(privateKey, publicKey); } if (pskStore != null) { builder.setPskStore(pskStore); } // Add all certificates from the truststore Certificate[] certs = getTrustedCerts(); if (certs.length > 0) { builder.setTrustStore(certs); } if (trustedRpkStore != null) { builder.setTrustCertificateTypes(CertificateType.RAW_PUBLIC_KEY); builder.setRpkTrustStore(trustedRpkStore); } } catch (GeneralSecurityException e) { throw new IllegalStateException("Error in configuring TLS", e); } if (getConfiguredCipherSuites() != null) { builder.setSupportedCipherSuites(getConfiguredCipherSuites()); } return new DTLSConnector(builder.build()); } }
apache-2.0
jahlborn/jackcess
src/main/java/com/healthmarketscience/jackcess/impl/query/UnionQueryImpl.java
2428
/* Copyright (c) 2008 Health Market Science, 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 com.healthmarketscience.jackcess.impl.query; import java.util.List; import static com.healthmarketscience.jackcess.impl.query.QueryFormat.*; import com.healthmarketscience.jackcess.query.UnionQuery; /** * Concrete Query subclass which represents a UNION query, e.g.: * {@code SELECT <query1> UNION SELECT <query2>} * * @author James Ahlborn */ public class UnionQueryImpl extends QueryImpl implements UnionQuery { public UnionQueryImpl(String name, List<Row> rows, int objectId, int objectFlag) { super(name, rows, objectId, objectFlag, Type.UNION); } @Override public String getUnionType() { return(hasFlag(UNION_FLAG) ? DEFAULT_TYPE : "ALL"); } @Override public String getUnionString1() { return getUnionString(UNION_PART1); } @Override public String getUnionString2() { return getUnionString(UNION_PART2); } @Override public List<String> getOrderings() { return super.getOrderings(); } private String getUnionString(String id) { for(Row row : getTableRows()) { if(id.equals(row.name2)) { return cleanUnionString(row.expression); } } throw new IllegalStateException( "Could not find union query with id " + id); } @Override protected void toSQLString(StringBuilder builder) { builder.append(getUnionString1()).append(NEWLINE) .append("UNION "); String unionType = getUnionType(); if(!DEFAULT_TYPE.equals(unionType)) { builder.append(unionType).append(' '); } builder.append(getUnionString2()); List<String> orderings = getOrderings(); if(!orderings.isEmpty()) { builder.append(NEWLINE).append("ORDER BY ").append(orderings); } } private static String cleanUnionString(String str) { return str.trim().replaceAll("[\r\n]+", NEWLINE); } }
apache-2.0
b-slim/hive
ql/src/java/org/apache/hadoop/hive/ql/ddl/table/storage/AlterTableUnarchiveDesc.java
1877
/* * 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.hadoop.hive.ql.ddl.table.storage; import java.util.Map; import org.apache.hadoop.hive.ql.ddl.DDLDesc; import org.apache.hadoop.hive.ql.plan.Explain; import org.apache.hadoop.hive.ql.plan.Explain.Level; /** * DDL task description for ALTER TABLE ... UNARCHIVE [PARTITION ...] commands. */ @Explain(displayName = "Unarchive", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED }) public class AlterTableUnarchiveDesc implements DDLDesc { private final String tableName; private final Map<String, String> partitionSpec; public AlterTableUnarchiveDesc(String tableName, Map<String, String> partitionSpec) { this.tableName = tableName; this.partitionSpec = partitionSpec; } @Explain(displayName = "table name", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED }) public String getTableName() { return tableName; } @Explain(displayName = "partition spec", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED }) public Map<String, String> getPartitionSpec() { return partitionSpec; } }
apache-2.0
citlab/vs.msc.ws14
flink-0-7-custom/flink-compiler/src/main/java/org/apache/flink/compiler/dag/CollectorMapNode.java
1960
/* * 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.flink.compiler.dag; import java.util.Collections; import java.util.List; import org.apache.flink.api.common.operators.SingleInputOperator; import org.apache.flink.compiler.DataStatistics; import org.apache.flink.compiler.operators.CollectorMapDescriptor; import org.apache.flink.compiler.operators.OperatorDescriptorSingle; /** * The optimizer's internal representation of a <i>Map</i> operator node. */ public class CollectorMapNode extends SingleInputNode { public CollectorMapNode(SingleInputOperator<?, ?, ?> operator) { super(operator); } @Override public String getName() { return "Map"; } @Override protected List<OperatorDescriptorSingle> getPossibleProperties() { return Collections.<OperatorDescriptorSingle>singletonList(new CollectorMapDescriptor()); } /** * Computes the estimates for the Map operator. Map takes one value and transforms it into another value. * The cardinality consequently stays the same. */ @Override protected void computeOperatorSpecificDefaultEstimates(DataStatistics statistics) { this.estimatedNumRecords = getPredecessorNode().getEstimatedNumRecords(); } }
apache-2.0
delebash/orientdb-parent
tests/src/test/java/com/orientechnologies/orient/test/java/collection/HashMapSpeedTest.java
1180
/* * Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.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 com.orientechnologies.orient.test.java.collection; import java.util.HashMap; import org.testng.annotations.Test; @Test(enabled = false) public class HashMapSpeedTest extends CollectionBaseAbstractSpeedTest { private HashMap<String, String> map; @Override public void cycle() { map.get(searchedValue); } @Override public void init() { map = new HashMap<String, String>(); for (int i = 0; i < collectionSize; ++i) { map.put(String.valueOf(i), ""); } } public void deInit() { map.clear(); map = null; } }
apache-2.0
firebase/firebase-admin-java
src/main/java/com/google/firebase/FirebaseApp.java
20850
/* * Copyright 2017 Google 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 com.google.firebase; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.firebase.FirebaseOptions.APPLICATION_DEFAULT_CREDENTIALS; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonParser; import com.google.api.core.ApiFuture; import com.google.auth.oauth2.AccessToken; import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.OAuth2Credentials; import com.google.auth.oauth2.OAuth2Credentials.CredentialsChangedListener; import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; import com.google.common.base.MoreObjects; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.firebase.internal.ApiClientUtils; import com.google.firebase.internal.FirebaseProcessEnvironment; import com.google.firebase.internal.FirebaseScheduledExecutor; import com.google.firebase.internal.FirebaseService; import com.google.firebase.internal.ListenableFuture2ApiFuture; import com.google.firebase.internal.NonNull; import com.google.firebase.internal.Nullable; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The entry point of Firebase SDKs. It holds common configuration and state for Firebase APIs. Most * applications don't need to directly interact with FirebaseApp. * * <p>Firebase APIs use the default FirebaseApp by default, unless a different one is explicitly * passed to the API via FirebaseFoo.getInstance(firebaseApp). * * <p>{@link FirebaseApp#initializeApp(FirebaseOptions)} initializes the default app instance. This * method should be invoked at startup. */ public class FirebaseApp { private static final Logger logger = LoggerFactory.getLogger(FirebaseApp.class); /** A map of (name, FirebaseApp) instances. */ private static final Map<String, FirebaseApp> instances = new HashMap<>(); public static final String DEFAULT_APP_NAME = "[DEFAULT]"; static final String FIREBASE_CONFIG_ENV_VAR = "FIREBASE_CONFIG"; private static final TokenRefresher.Factory DEFAULT_TOKEN_REFRESHER_FACTORY = new TokenRefresher.Factory(); /** * Global lock for synchronizing all SDK-wide application state changes. Specifically, any * accesses to instances map should be protected by this lock. */ private static final Object appsLock = new Object(); private final String name; private final FirebaseOptions options; private final TokenRefresher tokenRefresher; private final ThreadManager threadManager; private final ThreadManager.FirebaseExecutors executors; private final AtomicBoolean deleted = new AtomicBoolean(); private final Map<String, FirebaseService> services = new HashMap<>(); private volatile ScheduledExecutorService scheduledExecutor; /** * Per application lock for synchronizing all internal FirebaseApp state changes. */ private final Object lock = new Object(); /** Default constructor. */ private FirebaseApp(String name, FirebaseOptions options, TokenRefresher.Factory factory) { checkArgument(!Strings.isNullOrEmpty(name)); this.name = name; this.options = checkNotNull(options); this.tokenRefresher = checkNotNull(factory).create(this); this.threadManager = options.getThreadManager(); this.executors = this.threadManager.getFirebaseExecutors(this); } /** Returns a list of all FirebaseApps. */ public static List<FirebaseApp> getApps() { synchronized (appsLock) { return ImmutableList.copyOf(instances.values()); } } /** * Returns the default (first initialized) instance of the {@link FirebaseApp}. * * @throws IllegalStateException if the default app was not initialized. */ public static FirebaseApp getInstance() { return getInstance(DEFAULT_APP_NAME); } /** * Returns the instance identified by the unique name, or throws if it does not exist. * * @param name represents the name of the {@link FirebaseApp} instance. * @return the {@link FirebaseApp} corresponding to the name. * @throws IllegalStateException if the {@link FirebaseApp} was not initialized, either via {@link * #initializeApp(FirebaseOptions, String)} or {@link #getApps()}. */ public static FirebaseApp getInstance(@NonNull String name) { synchronized (appsLock) { FirebaseApp firebaseApp = instances.get(normalize(name)); if (firebaseApp != null) { return firebaseApp; } List<String> availableAppNames = getAllAppNames(); String availableAppNamesMessage; if (availableAppNames.isEmpty()) { availableAppNamesMessage = ""; } else { availableAppNamesMessage = "Available app names: " + Joiner.on(", ").join(availableAppNames); } String errorMessage = String.format( "FirebaseApp with name %s doesn't exist. %s", name, availableAppNamesMessage); throw new IllegalStateException(errorMessage); } } /** * Initializes the default {@link FirebaseApp} instance using Google Application Default * Credentials. Also attempts to load additional {@link FirebaseOptions} from the environment * by looking up the {@code FIREBASE_CONFIG} environment variable. If the value of * the variable starts with <code>'{'</code>, it is parsed as a JSON object. Otherwise it is * treated as a file name and the JSON content is read from the corresponding file. * * @throws IllegalStateException if the default app has already been initialized. * @throws IllegalArgumentException if an error occurs while loading options from the environment. */ public static FirebaseApp initializeApp() { return initializeApp(DEFAULT_APP_NAME); } /** * Initializes a named {@link FirebaseApp} instance using Google Application Default Credentials. * Loads additional {@link FirebaseOptions} from the environment in the same way as the * {@link #initializeApp()} method. * * @throws IllegalStateException if an app with the same name has already been initialized. * @throws IllegalArgumentException if an error occurs while loading options from the environment. */ public static FirebaseApp initializeApp(String name) { try { return initializeApp(getOptionsFromEnvironment(), name); } catch (IOException e) { throw new IllegalArgumentException( "Failed to load settings from the system's environment variables", e); } } /** * Initializes the default {@link FirebaseApp} instance using the given options. * * @throws IllegalStateException if the default app has already been initialized. */ public static FirebaseApp initializeApp(FirebaseOptions options) { return initializeApp(options, DEFAULT_APP_NAME); } /** * Initializes a named {@link FirebaseApp} instance using the given options. * * @param options represents the global {@link FirebaseOptions} * @param name unique name for the app. It is an error to initialize an app with an already * existing name. Starting and ending whitespace characters in the name are ignored (trimmed). * @return an instance of {@link FirebaseApp} * @throws IllegalStateException if an app with the same name has already been initialized. */ public static FirebaseApp initializeApp(FirebaseOptions options, String name) { return initializeApp(options, name, DEFAULT_TOKEN_REFRESHER_FACTORY); } static FirebaseApp initializeApp(FirebaseOptions options, String name, TokenRefresher.Factory tokenRefresherFactory) { String normalizedName = normalize(name); synchronized (appsLock) { checkState( !instances.containsKey(normalizedName), "FirebaseApp name " + normalizedName + " already exists!"); FirebaseApp firebaseApp = new FirebaseApp(normalizedName, options, tokenRefresherFactory); instances.put(normalizedName, firebaseApp); return firebaseApp; } } @VisibleForTesting static void clearInstancesForTest() { synchronized (appsLock) { // Copy the instances list before iterating, as delete() would attempt to remove from the // original list. for (FirebaseApp app : ImmutableList.copyOf(instances.values())) { app.delete(); } instances.clear(); } } private static List<String> getAllAppNames() { List<String> allAppNames; synchronized (appsLock) { allAppNames = new ArrayList<>(instances.keySet()); } Collections.sort(allAppNames); return ImmutableList.copyOf(allAppNames); } /** Normalizes the app name. */ private static String normalize(@NonNull String name) { return checkNotNull(name).trim(); } /** Returns the unique name of this app. */ @NonNull public String getName() { return name; } /** * Returns the specified {@link FirebaseOptions}. */ @NonNull public FirebaseOptions getOptions() { checkNotDeleted(); return options; } /** * Returns the Google Cloud project ID associated with this app. * * @return A string project ID or null. */ @Nullable String getProjectId() { checkNotDeleted(); // Try to get project ID from user-specified options. String projectId = options.getProjectId(); // Try to get project ID from the credentials. if (Strings.isNullOrEmpty(projectId)) { GoogleCredentials credentials = options.getCredentials(); if (credentials instanceof ServiceAccountCredentials) { projectId = ((ServiceAccountCredentials) credentials).getProjectId(); } } // Try to get project ID from the environment. if (Strings.isNullOrEmpty(projectId)) { projectId = FirebaseProcessEnvironment.getenv("GOOGLE_CLOUD_PROJECT"); } if (Strings.isNullOrEmpty(projectId)) { projectId = FirebaseProcessEnvironment.getenv("GCLOUD_PROJECT"); } return projectId; } @Override public boolean equals(Object o) { return o instanceof FirebaseApp && name.equals(((FirebaseApp) o).getName()); } @Override public int hashCode() { return name.hashCode(); } @Override public String toString() { return MoreObjects.toStringHelper(this).add("name", name).toString(); } /** * Deletes this {@link FirebaseApp} object, and releases any local state and managed resources * associated with it. All calls to this {@link FirebaseApp} instance will throw once this method * has been called. This also releases any managed resources allocated by other services * attached to this object instance (e.g. {@code FirebaseAuth}). * * <p>A no-op if delete was called before. */ public void delete() { synchronized (lock) { boolean valueChanged = deleted.compareAndSet(false /* expected */, true); if (!valueChanged) { return; } for (FirebaseService service : services.values()) { service.destroy(); } services.clear(); tokenRefresher.stop(); // Clean up and terminate the thread pools threadManager.releaseFirebaseExecutors(this, executors); if (scheduledExecutor != null) { scheduledExecutor.shutdownNow(); scheduledExecutor = null; } } synchronized (appsLock) { instances.remove(name); } } private void checkNotDeleted() { // Wrap the name argument in an array to ensure the invocation gets bound to the commonly // available checkState(boolean, String, Object...) overload. Otherwise the invocation may // get bound to the checkState(boolean, String, Object) overload, which is not present in older // guava versions. checkState(!deleted.get(), "FirebaseApp '%s' was deleted", new Object[]{name}); } private ScheduledExecutorService ensureScheduledExecutorService() { if (scheduledExecutor == null) { synchronized (lock) { checkNotDeleted(); if (scheduledExecutor == null) { scheduledExecutor = new FirebaseScheduledExecutor(getThreadFactory(), "firebase-scheduled-worker"); } } } return scheduledExecutor; } ThreadFactory getThreadFactory() { return threadManager.getThreadFactory(); } ScheduledExecutorService getScheduledExecutorService() { return ensureScheduledExecutorService(); } <T> ApiFuture<T> submit(Callable<T> command) { checkNotNull(command); return new ListenableFuture2ApiFuture<>(executors.getListeningExecutor().submit(command)); } <T> ScheduledFuture<T> schedule(Callable<T> command, long delayMillis) { checkNotNull(command); try { return ensureScheduledExecutorService().schedule(command, delayMillis, TimeUnit.MILLISECONDS); } catch (Exception e) { // This may fail if the underlying ThreadFactory does not support long-lived threads. throw new UnsupportedOperationException("Scheduled tasks not supported", e); } } ScheduledFuture<?> schedule(Runnable runnable, long delayMillis) { checkNotNull(runnable); try { return ensureScheduledExecutorService() .schedule(runnable, delayMillis, TimeUnit.MILLISECONDS); } catch (Exception e) { // This may fail if the underlying ThreadFactory does not support long-lived threads. throw new UnsupportedOperationException("Scheduled tasks not supported", e); } } void startTokenRefresher() { synchronized (lock) { checkNotDeleted(); // TODO: Provide an option to disable this altogether. tokenRefresher.start(); } } boolean isDefaultApp() { return DEFAULT_APP_NAME.equals(getName()); } void addService(FirebaseService service) { synchronized (lock) { checkNotDeleted(); checkArgument(!services.containsKey(checkNotNull(service).getId())); services.put(service.getId(), service); } } FirebaseService getService(String id) { synchronized (lock) { checkArgument(!Strings.isNullOrEmpty(id)); return services.get(id); } } /** * Utility class for scheduling proactive token refresh events. Each FirebaseApp should have * its own instance of this class. This class gets directly notified by GoogleCredentials * whenever the underlying OAuth2 token changes. TokenRefresher schedules subsequent token * refresh events when this happens. * * <p>This class is thread safe. It will handle only one token change event at a time. It also * cancels any pending token refresh events, before scheduling a new one. */ static class TokenRefresher implements CredentialsChangedListener { private final FirebaseApp firebaseApp; private final GoogleCredentials credentials; private final AtomicReference<State> state; private Future<Void> future; TokenRefresher(FirebaseApp firebaseApp) { this.firebaseApp = checkNotNull(firebaseApp); this.credentials = firebaseApp.getOptions().getCredentials(); this.state = new AtomicReference<>(State.READY); } @Override public final synchronized void onChanged(OAuth2Credentials credentials) { if (state.get() != State.STARTED) { return; } AccessToken accessToken = credentials.getAccessToken(); long refreshDelay = getRefreshDelay(accessToken); if (refreshDelay > 0) { scheduleRefresh(refreshDelay); } else { logger.warn("Token expiry ({}) is less than 5 minutes in the future. Not " + "scheduling a proactive refresh.", accessToken.getExpirationTime()); } } protected void cancelPrevious() { if (future != null) { future.cancel(true); } } protected void scheduleNext(Callable<Void> task, long delayMillis) { logger.debug("Scheduling next token refresh in {} milliseconds", delayMillis); try { future = firebaseApp.schedule(task, delayMillis); } catch (UnsupportedOperationException e) { // Cannot support task scheduling in the current runtime. logger.debug("Failed to schedule token refresh event", e); } } /** * Starts the TokenRefresher if not already started. Starts listening to credentials changed * events, and schedules refresh events every time the OAuth2 token changes. If no active * token is present, or if the available token is set to expire soon, this will also schedule * a refresh event to be executed immediately. * * <p>This operation is idempotent. Calling it multiple times, or calling it after the * refresher has been stopped has no effect. */ final synchronized void start() { // Allow starting only from the ready state. if (!state.compareAndSet(State.READY, State.STARTED)) { return; } logger.debug("Starting the proactive token refresher"); credentials.addChangeListener(this); AccessToken accessToken = credentials.getAccessToken(); long refreshDelay; if (accessToken != null) { // If the token is about to expire (i.e. expires in less than 5 minutes), schedule a // refresh event with 0 delay. Otherwise schedule a refresh event at the regular token // expiry time, minus 5 minutes. refreshDelay = Math.max(getRefreshDelay(accessToken), 0L); } else { // If there is no token fetched so far, fetch one immediately. refreshDelay = 0L; } scheduleRefresh(refreshDelay); } final synchronized void stop() { // Allow stopping from any state. State previous = state.getAndSet(State.STOPPED); if (previous == State.STARTED) { cancelPrevious(); logger.debug("Stopped the proactive token refresher"); } } /** * Schedule a forced token refresh to be executed after a specified duration. * * @param delayMillis Duration in milliseconds, after which the token should be forcibly * refreshed. */ private void scheduleRefresh(final long delayMillis) { cancelPrevious(); scheduleNext(new Callable<Void>() { @Override public Void call() throws Exception { logger.debug("Refreshing OAuth2 credential"); credentials.refresh(); return null; } }, delayMillis); } private long getRefreshDelay(AccessToken accessToken) { return accessToken.getExpirationTime().getTime() - System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5); } static class Factory { TokenRefresher create(FirebaseApp app) { return new TokenRefresher(app); } } enum State { READY, STARTED, STOPPED } } private static FirebaseOptions getOptionsFromEnvironment() throws IOException { String defaultConfig = FirebaseProcessEnvironment.getenv(FIREBASE_CONFIG_ENV_VAR); if (Strings.isNullOrEmpty(defaultConfig)) { return FirebaseOptions.builder() .setCredentials(APPLICATION_DEFAULT_CREDENTIALS) .build(); } JsonFactory jsonFactory = ApiClientUtils.getDefaultJsonFactory(); FirebaseOptions.Builder builder = FirebaseOptions.builder(); JsonParser parser; if (defaultConfig.startsWith("{")) { parser = jsonFactory.createJsonParser(defaultConfig); } else { FileReader reader = new FileReader(defaultConfig); parser = jsonFactory.createJsonParser(reader); } parser.parseAndClose(builder); builder.setCredentials(APPLICATION_DEFAULT_CREDENTIALS); return builder.build(); } }
apache-2.0
Hack23/cia
service.impl/src/test/java/com/hack23/cia/service/impl/AbstractServiceFunctionalIntegrationTest.java
10565
/* * Copyright 2010-2021 James Pether Sörling * * 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. * * $Id$ * $HeadURL$ */ package com.hack23.cia.service.impl; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Random; import java.util.UUID; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.dumbster.smtp.SimpleSmtpServer; import com.hack23.cia.model.internal.application.system.impl.ApplicationConfiguration; import com.hack23.cia.model.internal.application.system.impl.ApplicationSessionType; import com.hack23.cia.model.internal.application.system.impl.ConfigurationGroup; import com.hack23.cia.service.api.ApplicationManager; import com.hack23.cia.service.api.action.admin.UpdateApplicationConfigurationRequest; import com.hack23.cia.service.api.action.admin.UpdateApplicationConfigurationResponse; import com.hack23.cia.service.api.action.application.CreateApplicationSessionRequest; import com.hack23.cia.service.api.action.application.CreateApplicationSessionResponse; import com.hack23.cia.service.api.action.common.ServiceResponse.ServiceResult; import com.hack23.cia.service.data.api.ApplicationConfigurationService; import com.hack23.cia.service.impl.email.EmailServiceImpl; import com.hack23.cia.testfoundation.AbstractFunctionalIntegrationTest; /** * The Class AbstractServiceFunctionalIntegrationTest. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:/META-INF/application-context-service.xml", "classpath:/META-INF/cia-service-component-agent.xml", "classpath:META-INF/cia-jms-broker.xml", "classpath:/META-INF/application-context-service-data.xml", "classpath:META-INF/cia-service-external-common.xml", "classpath:META-INF/cia-service-external-riksdagen.xml", "classpath:META-INF/cia-service-external-worldbank.xml", "classpath:META-INF/cia-service-external-val.xml", "classpath:/META-INF/cia-test-context.xml" }) public abstract class AbstractServiceFunctionalIntegrationTest extends AbstractFunctionalIntegrationTest { /** The Constant EXPECT_A_RESULT. */ public static final String EXPECT_A_RESULT = "Expect a result"; /** The Constant EXPECT_SUCCESS. */ public static final String EXPECT_SUCCESS = "Expect success"; /** The Constant PRINCIPAL. */ private static final String PRINCIPAL = "AbstractServiceFunctionalIntegrationTest"; /** The Constant KEY. */ private static final String KEY = "FunctionalIntegrationTest"; /** The Constant ROLE_ANONYMOUS. */ private static final String ROLE_ANONYMOUS = "ROLE_ANONYMOUS"; /** The Constant ROLE_ADMIN. */ private static final String ROLE_ADMIN = "ROLE_ADMIN"; /** The application configuration service. */ @Autowired private ApplicationConfigurationService applicationConfigurationService; /** The application manager. */ @Autowired protected ApplicationManager applicationManager; /** * Instantiates a new abstract service functional integration test. */ public AbstractServiceFunctionalIntegrationTest() { super(); } /** * Configure mail server. * * @param createTestApplicationSession * the create test application session * @return the simple smtp server * @throws IOException * Signals that an I/O exception has occurred. */ protected final SimpleSmtpServer configureMailServer(CreateApplicationSessionRequest createTestApplicationSession) throws IOException { final SimpleSmtpServer dumbster = SimpleSmtpServer.start(SimpleSmtpServer.AUTO_SMTP_PORT); setAuthenticatedAdminuser(); createTestApplicationSession = createTestApplicationSession(); final ApplicationConfiguration sendEmail = applicationConfigurationService.checkValueOrLoadDefault( "Email configuration send emails", "Send email", ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), "Send email", "Responsible for sending email", "application.email.send.email", "false"); final ApplicationConfiguration smtpPort = applicationConfigurationService.checkValueOrLoadDefault( "Email configuration smtp port", "Smtp port", ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), "Smtp port", "Responsible for sending email", "application.email.smtp.port", "587"); final ApplicationConfiguration smtpHost = applicationConfigurationService.checkValueOrLoadDefault( "Email configuration smtp host", "Smtp host", ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), "Smtp host","Responsible for sending email", "application.email.smtp.host", "localhost"); updateApplicationConfiguration(createTestApplicationSession, sendEmail, "true"); updateApplicationConfiguration(createTestApplicationSession, smtpPort,Integer.toString(dumbster.getPort())); updateApplicationConfiguration(createTestApplicationSession, smtpHost,"localhost"); return dumbster; } /** * Creates the application sesstion with role anonymous. * * @return the creates the application session request */ protected final CreateApplicationSessionRequest createApplicationSesstionWithRoleAnonymous() { setAuthenticatedAnonymousUser(); return createTestApplicationSession(); } /** * Creates the test application session. * * @return the creates the application session request */ protected final CreateApplicationSessionRequest createTestApplicationSession() { final Random r = new Random(); final CreateApplicationSessionRequest serviceRequest = new CreateApplicationSessionRequest(); serviceRequest.setIpInformation(r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256)); serviceRequest.setLocale("en_US.UTF-8"); serviceRequest.setOperatingSystem("LINUX"); serviceRequest.setSessionId(UUID.randomUUID().toString()); serviceRequest.setSessionType(ApplicationSessionType.ANONYMOUS); serviceRequest.setUserAgentInformation( "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:42.0) Gecko/20100101 Firefox/42.0"); final CreateApplicationSessionResponse response = (CreateApplicationSessionResponse) applicationManager .service(serviceRequest); assertNotNull(EXPECT_A_RESULT, response); assertEquals(EXPECT_SUCCESS,ServiceResult.SUCCESS, response.getResult()); return serviceRequest; } /** * Restore mail configuration. * * @param createTestApplicationSession * the create test application session * @param dumbster * the dumbster */ protected final void restoreMailConfiguration(final CreateApplicationSessionRequest createTestApplicationSession,final SimpleSmtpServer dumbster) { final ApplicationConfiguration sendEmail = applicationConfigurationService.checkValueOrLoadDefault( "Email configuration send emails", "Send email", ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), "Send email", "Responsible for sending email", "application.email.send.email", "false"); final ApplicationConfiguration smtpPort = applicationConfigurationService.checkValueOrLoadDefault( "Email configuration smtp port", "Smtp port", ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), "Smtp port", "Responsible for sending email", "application.email.smtp.port", "587"); updateApplicationConfiguration(createTestApplicationSession, sendEmail, "false"); updateApplicationConfiguration(createTestApplicationSession, smtpPort,"587"); dumbster.stop(); } /** * Sets the authenticated adminuser. */ protected final void setAuthenticatedAdminuser() { final Collection<SimpleGrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(ROLE_ADMIN)); authorities.add(new SimpleGrantedAuthority(ROLE_ANONYMOUS)); SecurityContextHolder.getContext() .setAuthentication(new AnonymousAuthenticationToken(KEY, PRINCIPAL, authorities)); } /** * Sets the authenticated anonymous user. */ protected final void setAuthenticatedAnonymousUser() { final Collection<SimpleGrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(ROLE_ANONYMOUS)); SecurityContextHolder.getContext() .setAuthentication(new AnonymousAuthenticationToken(KEY, PRINCIPAL, authorities)); } /** * Update application configuration. * * @param createTestApplicationSession * the create test application session * @param applicationConfiguration * the application configuration * @param propertyValue * the property value */ private void updateApplicationConfiguration(final CreateApplicationSessionRequest createTestApplicationSession, final ApplicationConfiguration applicationConfiguration, final String propertyValue) { final UpdateApplicationConfigurationRequest serviceRequest = new UpdateApplicationConfigurationRequest(); serviceRequest.setApplicationConfigurationId(applicationConfiguration.getHjid()); serviceRequest.setSessionId(createTestApplicationSession.getSessionId()); serviceRequest.setComponentDescription(applicationConfiguration.getComponentDescription()); serviceRequest.setConfigDescription(applicationConfiguration.getConfigDescription()); serviceRequest.setConfigTitle(applicationConfiguration.getConfigTitle()); serviceRequest.setComponentTitle(applicationConfiguration.getComponentTitle()); serviceRequest.setPropertyValue(propertyValue); final UpdateApplicationConfigurationResponse response = (UpdateApplicationConfigurationResponse) applicationManager .service(serviceRequest); assertEquals(EXPECT_SUCCESS, ServiceResult.SUCCESS, response.getResult()); } }
apache-2.0
sequenceiq/cloudbreak
shell/src/main/java/com/sequenceiq/cloudbreak/shell/converter/NetworkNameConverter.java
1296
package com.sequenceiq.cloudbreak.shell.converter; import java.util.List; import java.util.Map; import javax.inject.Inject; import org.springframework.shell.core.Completion; import org.springframework.shell.core.MethodTarget; import com.sequenceiq.cloudbreak.client.CloudbreakClient; import com.sequenceiq.cloudbreak.shell.completion.NetworkName; import com.sequenceiq.cloudbreak.shell.transformer.ResponseTransformer; public class NetworkNameConverter extends AbstractConverter<NetworkName> { @Inject private CloudbreakClient cloudbreakClient; @Inject private ResponseTransformer responseTransformer; public NetworkNameConverter() { } @Override public boolean supports(Class<?> type, String optionContext) { return NetworkName.class.isAssignableFrom(type); } @Override public boolean getAllPossibleValues(List<Completion> completions, Class<?> targetType, String existingData, String optionContext, MethodTarget target) { try { Map<String, String> networksMap = responseTransformer.transformToMap(cloudbreakClient.networkEndpoint().getPublics(), "id", "name"); return getAllPossibleValues(completions, networksMap.values()); } catch (Exception e) { return false; } } }
apache-2.0
NatalyaP161/java_panfilova
mantis-tests/src/test/java/ru/stqa/pft/mantis/appmanager/FtpHelper.java
1094
package ru.stqa.pft.mantis.appmanager; import org.apache.commons.net.ftp.FTPClient; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class FtpHelper { private final ApplicationManager app; private FTPClient ftp; public FtpHelper(ApplicationManager app) { this.app = app; ftp = new FTPClient(); } public void upload(File file, String target, String backup) throws IOException { ftp.connect(app.getProperty("ftp.host")); ftp.login(app.getProperty("ftp.login"), app.getProperty("ftp.password")); ftp.deleteFile(backup); ftp.rename(target, backup); ftp.enterLocalPassiveMode(); ftp.storeFile(target, new FileInputStream(file)); ftp.disconnect(); } public void restore(String backup, String target) throws IOException { ftp.connect(app.getProperty("ftp.host")); ftp.login(app.getProperty("ftp.login"), app.getProperty("ftp.password")); ftp.deleteFile(target); ftp.rename(backup,target); ftp.disconnect(); } }
apache-2.0
trustedanalytics/data-acquisition
src/main/java/org/trustedanalytics/das/service/BadRequestException.java
781
/** * Copyright (c) 2015 Intel Corporation * * 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.trustedanalytics.das.service; public class BadRequestException extends RuntimeException { public BadRequestException(String msg) { super(msg); } }
apache-2.0
alexhilton/EffectiveJava
src/com/effectivejava/io/FillStrings.java
1110
package com.effectivejava.io; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class FillStrings { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub BufferedReader reader; try { reader = new BufferedReader(new FileReader(args[0])); String line; while ((line = reader.readLine()) != null) { String[] parts = line.split(":"); String filename = parts[0].trim(); String str = parts[1].trim(); PrintWriter writer = new PrintWriter( new BufferedWriter(new FileWriter(filename))); writer.append(str); writer.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
apache-2.0
geliangdashen/Material
lib/src/main/java/com/rey/material/widget/SnackBar.java
20428
package com.rey.material.widget; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.os.Build; import android.text.TextUtils; import android.text.TextUtils.TruncateAt; import android.util.AttributeSet; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.FrameLayout; import android.widget.RelativeLayout; import com.rey.material.R; import com.rey.material.drawable.RippleDrawable; import com.rey.material.util.ThemeUtil; public class SnackBar extends FrameLayout { private TextView mText; private Button mAction; public static final int MATCH_PARENT = ViewGroup.LayoutParams.MATCH_PARENT; public static final int WRAP_CONTENT = ViewGroup.LayoutParams.WRAP_CONTENT; private BackgroundDrawable mBackground; private int mMarginLeft; private int mMarginBottom; private int mWidth; private int mHeight; private int mMaxHeight; private int mMinHeight; private int mInAnimationId; private int mOutAnimationId; private long mDuration = -1; private int mActionId; private boolean mRemoveOnDismiss; private Runnable mDismissRunnable = new Runnable() { @Override public void run() { dismiss(); } }; private int mState = STATE_DISMISSED; public static final int STATE_DISMISSED = 0; public static final int STATE_SHOWED = 1; public static final int STATE_SHOWING = 2; public static final int STATE_DISMISSING = 3; public interface OnActionClickListener{ public void onActionClick(SnackBar sb, int actionId); } private OnActionClickListener mActionClickListener; public interface OnStateChangeListener{ public void onStateChange(SnackBar sb, int oldState, int newState); } private OnStateChangeListener mStateChangeListener; public static SnackBar make(Context context){ return new SnackBar(context); } public SnackBar(Context context){ super(context); init(context, null, 0, 0); } public SnackBar(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs, 0, 0); } public SnackBar(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs, defStyleAttr, 0); } public SnackBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr); init(context, attrs, defStyleAttr, defStyleRes); } @SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes){ mText = new TextView(context); mText.setGravity(Gravity.START|Gravity.CENTER_VERTICAL); addView(mText, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); mAction = new Button(context); mAction.setBackgroundResource(0); mAction.setGravity(Gravity.CENTER); mAction.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(mActionClickListener != null) mActionClickListener.onActionClick(SnackBar.this, mActionId); dismiss(); } }); addView(mAction, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); mBackground = new BackgroundDrawable(); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) setBackground(mBackground); else setBackgroundDrawable(mBackground); setClickable(true); applyStyle(attrs, defStyleAttr, defStyleRes); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthSize = MeasureSpec.getSize(widthMeasureSpec); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int width = 0; int height = 0; if(mAction.getVisibility() == View.VISIBLE){ mAction.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), heightMeasureSpec); mText.measure(MeasureSpec.makeMeasureSpec(widthSize - (mAction.getMeasuredWidth() - mText.getPaddingRight()), widthMode), heightMeasureSpec); width = mText.getMeasuredWidth() + mAction.getMeasuredWidth() - mText.getPaddingRight(); } else{ mText.measure(MeasureSpec.makeMeasureSpec(widthSize, widthMode), heightMeasureSpec); width = mText.getMeasuredWidth(); } height = Math.max(mText.getMeasuredHeight(), mAction.getMeasuredHeight()); switch (widthMode) { case MeasureSpec.AT_MOST: width = Math.min(widthSize, width); break; case MeasureSpec.EXACTLY: width = widthSize; break; } switch (heightMode) { case MeasureSpec.AT_MOST: height = Math.min(heightSize, height); break; case MeasureSpec.EXACTLY: height = heightSize; break; } if(mMaxHeight > 0) height = Math.min(mMaxHeight, height); if(mMinHeight > 0) height = Math.max(mMinHeight, height); setMeasuredDimension(width, height); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int childLeft = getPaddingLeft(); int childRight = r - l - getPaddingRight(); int childTop = getPaddingTop(); int childBottom = b - t - getPaddingBottom(); if(mAction.getVisibility() == View.VISIBLE){ mAction.layout(childRight - mAction.getMeasuredWidth(), childTop, childRight, childBottom); mText.layout(childLeft, childTop, childRight - mAction.getMeasuredWidth() + mText.getPaddingRight(), childBottom); } else mText.layout(childLeft, childTop, childRight, childBottom); } @SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private void applyStyle(AttributeSet attrs, int defStyleAttr, int defStyleRes){ Context context = getContext(); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SnackBar, defStyleAttr, defStyleRes); int backgroundColor = a.getColor(R.styleable.SnackBar_sb_backgroundColor, 0xFF323232); int backgroundRadius = a.getDimensionPixelSize(R.styleable.SnackBar_sb_backgroundCornerRadius, 0); int horizontalPadding = a.getDimensionPixelSize(R.styleable.SnackBar_sb_horizontalPadding, ThemeUtil.dpToPx(context, 24)); int verticalPadding = a.getDimensionPixelSize(R.styleable.SnackBar_sb_verticalPadding, 0); TypedValue value = a.peekValue(R.styleable.SnackBar_sb_width); if(value != null && value.type == TypedValue.TYPE_INT_DEC) mWidth = a.getInteger(R.styleable.SnackBar_sb_width, MATCH_PARENT); else mWidth = a.getDimensionPixelSize(R.styleable.SnackBar_sb_width, MATCH_PARENT); int minWidth = a.getDimensionPixelSize(R.styleable.SnackBar_sb_minWidth, 0); int maxWidth = a.getDimensionPixelSize(R.styleable.SnackBar_sb_maxWidth, 0); value = a.peekValue(R.styleable.SnackBar_sb_height); if(value != null && value.type == TypedValue.TYPE_INT_DEC) mHeight = a.getInteger(R.styleable.SnackBar_sb_height, WRAP_CONTENT); else mHeight = a.getDimensionPixelSize(R.styleable.SnackBar_sb_height, WRAP_CONTENT); int minHeight = a.getDimensionPixelSize(R.styleable.SnackBar_sb_minHeight, 0); int maxHeight = a.getDimensionPixelSize(R.styleable.SnackBar_sb_maxHeight, 0); mMarginLeft = a.getDimensionPixelSize(R.styleable.SnackBar_sb_marginLeft, 0); mMarginBottom = a.getDimensionPixelSize(R.styleable.SnackBar_sb_marginBottom, 0); int textSize = a.getDimensionPixelSize(R.styleable.SnackBar_sb_textSize, 0); boolean hasTextColor = a.hasValue(R.styleable.SnackBar_sb_textColor); int textColor = hasTextColor ? a.getColor(R.styleable.SnackBar_sb_textColor, 0xFFFFFFFF) : 0; int textAppearance = a.getResourceId(R.styleable.SnackBar_sb_textAppearance, 0); String text = a.getString(R.styleable.SnackBar_sb_text); boolean singleLine = a.getBoolean(R.styleable.SnackBar_sb_singleLine, true); int maxLines = a.getInteger(R.styleable.SnackBar_sb_maxLines, 0); int lines = a.getInteger(R.styleable.SnackBar_sb_lines, 0); int ellipsize = a.getInteger(R.styleable.SnackBar_sb_ellipsize, 0); int actionTextSize = a.getDimensionPixelSize(R.styleable.SnackBar_sb_actionTextSize, 0); ColorStateList actionTextColor; value = a.peekValue(R.styleable.SnackBar_sb_actionTextColor); if(value != null && value.type >= TypedValue.TYPE_FIRST_COLOR_INT && value.type <= TypedValue.TYPE_LAST_COLOR_INT) actionTextColor = ColorStateList.valueOf(a.getColor(R.styleable.SnackBar_sb_actionTextColor, 0xFF000000)); else actionTextColor = a.getColorStateList(R.styleable.SnackBar_sb_actionTextColor); int actionTextAppearance = a.getResourceId(R.styleable.SnackBar_sb_actionTextAppearance, 0); String actionText = a.getString(R.styleable.SnackBar_sb_actionText); int actionRipple = a.getResourceId(R.styleable.SnackBar_sb_actionRipple, 0); int duration = a.getInteger(R.styleable.SnackBar_sb_duration, -1); mInAnimationId = a.getResourceId(R.styleable.SnackBar_sb_inAnimation, 0); mOutAnimationId = a.getResourceId(R.styleable.SnackBar_sb_outAnimation, 0); mRemoveOnDismiss = a.getBoolean(R.styleable.SnackBar_sb_removeOnDismiss, true); a.recycle(); backgroundColor(backgroundColor) .backgroundRadius(backgroundRadius); padding(horizontalPadding, verticalPadding); textAppearance(textAppearance); if(textSize > 0) textSize(textSize); if(hasTextColor) textColor(textColor); if(text != null) text(text); singleLine(singleLine); if(maxLines > 0) maxLines(maxLines); if(lines > 0) lines(lines); if(minWidth > 0) minWidth(minWidth); if(maxWidth > 0) maxWidth(maxWidth); if(minHeight > 0) minHeight(minHeight); if(maxHeight > 0) maxHeight(maxHeight); switch (ellipsize) { case 1: ellipsize(TruncateAt.START); break; case 2: ellipsize(TruncateAt.MIDDLE); break; case 3: ellipsize(TruncateAt.END); break; case 4: ellipsize(TruncateAt.MARQUEE); break; default: ellipsize(TruncateAt.END); break; } if(textAppearance != 0) actionTextAppearance(actionTextAppearance); if(actionTextSize > 0) actionTextSize(actionTextSize); if(actionTextColor != null) actionTextColor(actionTextColor); if(actionText != null) actionText(actionText); if(actionRipple != 0) actionRipple(actionRipple); if(duration >= 0) duration(duration); } public SnackBar applyStyle(int resId){ applyStyle(null, 0, resId); return this; } public SnackBar text(CharSequence text){ mText.setText(text); return this; } public SnackBar text(int id){ return text(getContext().getResources().getString(id)); } public SnackBar textColor(int color){ mText.setTextColor(color); return this; } public SnackBar textSize(int size){ mText.setTextSize(TypedValue.COMPLEX_UNIT_PX, size); return this; } public SnackBar textAppearance(int resId){ if(resId != 0) mText.setTextAppearance(getContext(), resId); return this; } public SnackBar ellipsize(TruncateAt at){ mText.setEllipsize(at); return this; } public SnackBar singleLine(boolean b){ mText.setSingleLine(b); return this; } public SnackBar maxLines(int lines){ mText.setMaxLines(lines); return this; } public SnackBar lines(int lines){ mText.setLines(lines); return this; } public SnackBar actionId(int id){ mActionId = id; return this; } public SnackBar actionText(CharSequence text){ if(TextUtils.isEmpty(text)) mAction.setVisibility(View.INVISIBLE); else{ mAction.setVisibility(View.VISIBLE); mAction.setText(text); } return this; } public SnackBar actionText(int id){ if(id == 0) return actionText(null); return actionText(getContext().getResources().getString(id)); } public SnackBar actionTextColor(int color){ mAction.setTextColor(color); return this; } public SnackBar actionTextColor(ColorStateList colors){ mAction.setTextColor(colors); return this; } public SnackBar actionTextAppearance(int resId){ if(resId != 0) mAction.setTextAppearance(getContext(), resId); return this; } public SnackBar actionTextSize(int size){ mAction.setTextSize(TypedValue.COMPLEX_UNIT_PX, size); return this; } @SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public SnackBar actionRipple(int resId){ if(resId != 0){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) mAction.setBackground(new RippleDrawable.Builder(getContext(), resId).build()); else mAction.setBackgroundDrawable(new RippleDrawable.Builder(getContext(), resId).build()); } return this; } public SnackBar duration(long duration){ mDuration = duration; return this; } public SnackBar backgroundColor(int color){ mBackground.setColor(color); return this; } public SnackBar backgroundRadius(int radius){ mBackground.setRadius(radius); return this; } public SnackBar horizontalPadding(int padding){ mText.setPadding(padding, mText.getPaddingTop(), padding, mText.getPaddingBottom()); mAction.setPadding(padding, mAction.getPaddingTop(), padding, mAction.getPaddingBottom()); return this; } public SnackBar verticalPadding(int padding){ mText.setPadding(mText.getPaddingLeft(), padding, mText.getPaddingRight(), padding); mAction.setPadding(mAction.getPaddingLeft(), padding, mAction.getPaddingRight(), padding); return this; } public SnackBar padding(int horizontalPadding, int verticalPadding){ mText.setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding); mAction.setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding); return this; } public SnackBar width(int width){ mWidth = width; return this; } public SnackBar minWidth(int width){ mText.setMinWidth(width); return this; } public SnackBar maxWidth(int width){ mText.setMaxWidth(width); return this; } public SnackBar height(int height){ mHeight = height; return this; } public SnackBar maxHeight(int height){ mMaxHeight = height; return this; } public SnackBar minHeight(int height){ mMinHeight = height; return this; } public SnackBar marginLeft(int size){ mMarginLeft = size; return this; } public SnackBar marginBottom(int size){ mMarginBottom = size; return this; } public SnackBar actionClickListener(OnActionClickListener listener){ mActionClickListener = listener; return this; } public SnackBar stateChangeListener(OnStateChangeListener listener){ mStateChangeListener = listener; return this; } public SnackBar removeOnDismiss(boolean b){ mRemoveOnDismiss = b; return this; } public void show(Activity activity){ show((ViewGroup)activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT)); } public void show(ViewGroup parent){ if(mState == STATE_SHOWING || mState == STATE_DISMISSING) return; if(getParent() != parent) { if(getParent() != null) ((ViewGroup) getParent()).removeView(this); parent.addView(this); } show(); } public void show(){ ViewGroup parent = (ViewGroup)getParent(); if(parent == null || mState == STATE_SHOWING || mState == STATE_DISMISSING) return; if(parent instanceof FrameLayout){ FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)getLayoutParams(); params.width = mWidth; params.height = mHeight; params.gravity = Gravity.BOTTOM; params.leftMargin = mMarginLeft; params.bottomMargin = mMarginBottom; } else if(parent instanceof RelativeLayout){ RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)getLayoutParams(); params.width = mWidth; params.height = mHeight; params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); params.leftMargin = mMarginLeft; params.bottomMargin = mMarginBottom; } if(mInAnimationId != 0 && mState != STATE_SHOWED){ Animation anim = AnimationUtils.loadAnimation(getContext(), mInAnimationId); anim.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { setState(STATE_SHOWING); setVisibility(View.VISIBLE); } @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationEnd(Animation animation) { setState(STATE_SHOWED); startTimer(); } }); startAnimation(anim); } else{ setVisibility(View.VISIBLE); setState(STATE_SHOWED); startTimer(); } } private void startTimer(){ removeCallbacks(mDismissRunnable); if(mDuration > 0) postDelayed(mDismissRunnable, mDuration); } public void dismiss(){ if(mState != STATE_SHOWED) return; removeCallbacks(mDismissRunnable); if(mOutAnimationId != 0){ Animation anim = AnimationUtils.loadAnimation(getContext(), mOutAnimationId); anim.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { setState(STATE_DISMISSING); } @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationEnd(Animation animation) { if(mRemoveOnDismiss && getParent() != null && getParent() instanceof ViewGroup) ((ViewGroup)getParent()).removeView(SnackBar.this); setState(STATE_DISMISSED); setVisibility(View.GONE); } }); startAnimation(anim); } else{ if(mRemoveOnDismiss && getParent() != null && getParent() instanceof ViewGroup) ((ViewGroup)getParent()).removeView(this); setState(STATE_DISMISSED); setVisibility(View.GONE); } } public int getState(){ return mState; } private void setState(int state){ if(mState != state){ int oldState = mState; mState = state; if(mStateChangeListener != null) mStateChangeListener.onStateChange(this, oldState, mState); } } private class BackgroundDrawable extends Drawable{ private int mBackgroundColor; private int mBackgroundRadius; private Paint mPaint; private RectF mRect; public BackgroundDrawable(){ mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.FILL); mRect = new RectF(); } public void setColor(int color){ if(mBackgroundColor != color){ mBackgroundColor = color; mPaint.setColor(mBackgroundColor); invalidateSelf(); } } public void setRadius(int radius){ if(mBackgroundRadius != radius){ mBackgroundRadius = radius; invalidateSelf(); } } @Override protected void onBoundsChange(Rect bounds) { mRect.set(bounds); } @Override public void draw(Canvas canvas) { canvas.drawRoundRect(mRect, mBackgroundRadius, mBackgroundRadius, mPaint); } @Override public void setAlpha(int alpha) { mPaint.setAlpha(alpha); } @Override public void setColorFilter(ColorFilter cf) { mPaint.setColorFilter(cf); } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } } }
apache-2.0
ilayaperumalg/spring-cloud-stream
spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/BindingProperties.java
4364
/* * Copyright 2015-2018 the original author or authors. * * 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 * * https://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.springframework.cloud.stream.config; import javax.validation.constraints.AssertTrue; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import org.springframework.cloud.stream.binder.ConsumerProperties; import org.springframework.cloud.stream.binder.ProducerProperties; import org.springframework.util.MimeType; import org.springframework.util.MimeTypeUtils; import org.springframework.validation.annotation.Validated; /** * Contains the properties of a binding. * * @author Marius Bogoevici * @author Ilayaperumal Gopinathan * @author Gary Russell * @author Soby Chacko * @author Oleg Zhurakousky */ @JsonInclude(Include.NON_DEFAULT) @Validated public class BindingProperties { /** * Default content type for bindings. */ public static final MimeType DEFAULT_CONTENT_TYPE = MimeTypeUtils.APPLICATION_JSON; private static final String COMMA = ","; /** * The physical name at the broker that the binder binds to. */ private String destination; /** * Unique name that the binding belongs to (applies to consumers only). Multiple * consumers within the same group share the subscription. A null or empty String * value indicates an anonymous group that is not shared. * @see org.springframework.cloud.stream.binder.Binder#bindConsumer(java.lang.String, * java.lang.String, java.lang.Object, * org.springframework.cloud.stream.binder.ConsumerProperties) */ private String group; // Properties for both input and output bindings /** * Specifies content-type that will be used by this binding in the event it is not * specified in Message headers. Default: 'application/json'. */ private String contentType = DEFAULT_CONTENT_TYPE.toString(); /** * The name of the binder to use for this binding in the event multiple binders * available (e.g., 'rabbit'). */ private String binder; /** * Additional consumer specific properties (see {@link ConsumerProperties}). */ private ConsumerProperties consumer; /** * Additional producer specific properties (see {@link ProducerProperties}). */ private ProducerProperties producer; public String getDestination() { return this.destination; } public void setDestination(String destination) { this.destination = destination; } public String getGroup() { return this.group; } public void setGroup(String group) { this.group = group; } public String getContentType() { return this.contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public String getBinder() { return this.binder; } public void setBinder(String binder) { this.binder = binder; } public ConsumerProperties getConsumer() { return this.consumer; } public void setConsumer(ConsumerProperties consumer) { this.consumer = consumer; } public ProducerProperties getProducer() { return this.producer; } public void setProducer(ProducerProperties producer) { this.producer = producer; } @AssertTrue(message = "A binding must not set both producer and consumer properties.") public boolean onlyOneOfProducerOrConsumerSet() { return this.consumer == null || this.producer == null; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("destination=" + this.destination); sb.append(COMMA); sb.append("group=" + this.group); sb.append(COMMA); if (this.contentType != null) { sb.append("contentType=" + this.contentType); sb.append(COMMA); } if (this.binder != null) { sb.append("binder=" + this.binder); sb.append(COMMA); } sb.deleteCharAt(sb.lastIndexOf(COMMA)); return "BindingProperties{" + sb.toString() + "}"; } }
apache-2.0
googleapis/java-compute
proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/BackendServiceCdnPolicy.java
153820
/* * Copyright 2020 Google 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 * * https://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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/compute/v1/compute.proto package com.google.cloud.compute.v1; /** * * * <pre> * Message containing Cloud CDN configuration for a backend service. * </pre> * * Protobuf type {@code google.cloud.compute.v1.BackendServiceCdnPolicy} */ public final class BackendServiceCdnPolicy extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.compute.v1.BackendServiceCdnPolicy) BackendServiceCdnPolicyOrBuilder { private static final long serialVersionUID = 0L; // Use BackendServiceCdnPolicy.newBuilder() to construct. private BackendServiceCdnPolicy(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private BackendServiceCdnPolicy() { bypassCacheOnRequestHeaders_ = java.util.Collections.emptyList(); cacheMode_ = ""; negativeCachingPolicy_ = java.util.Collections.emptyList(); signedUrlKeyNames_ = com.google.protobuf.LazyStringArrayList.EMPTY; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new BackendServiceCdnPolicy(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private BackendServiceCdnPolicy( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 231023106: { java.lang.String s = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; cacheMode_ = s; break; } case 232274880: { bitField0_ |= 0x00000004; clientTtl_ = input.readInt32(); break; } case 802027376: { bitField0_ |= 0x00000008; defaultTtl_ = input.readInt32(); break; } case 1242879970: { if (!((mutable_bitField0_ & 0x00000080) != 0)) { negativeCachingPolicy_ = new java.util.ArrayList< com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy>(); mutable_bitField0_ |= 0x00000080; } negativeCachingPolicy_.add( input.readMessage( com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy .parser(), extensionRegistry)); break; } case 1274109818: { com.google.cloud.compute.v1.CacheKeyPolicy.Builder subBuilder = null; if (((bitField0_ & 0x00000001) != 0)) { subBuilder = cacheKeyPolicy_.toBuilder(); } cacheKeyPolicy_ = input.readMessage( com.google.cloud.compute.v1.CacheKeyPolicy.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(cacheKeyPolicy_); cacheKeyPolicy_ = subBuilder.buildPartial(); } bitField0_ |= 0x00000001; break; } case 1893457624: { bitField0_ |= 0x00000080; serveWhileStale_ = input.readInt32(); break; } case -2139971024: { bitField0_ |= 0x00000100; signedUrlCacheMaxAgeSec_ = input.readInt64(); break; } case -1834343288: { bitField0_ |= 0x00000010; maxTtl_ = input.readInt32(); break; } case -1606087256: { bitField0_ |= 0x00000020; negativeCaching_ = input.readBool(); break; } case -1320176214: { java.lang.String s = input.readStringRequireUtf8(); if (!((mutable_bitField0_ & 0x00000800) != 0)) { signedUrlKeyNames_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000800; } signedUrlKeyNames_.add(s); break; } case -405342638: { if (!((mutable_bitField0_ & 0x00000001) != 0)) { bypassCacheOnRequestHeaders_ = new java.util.ArrayList< com.google.cloud.compute.v1 .BackendServiceCdnPolicyBypassCacheOnRequestHeader>(); mutable_bitField0_ |= 0x00000001; } bypassCacheOnRequestHeaders_.add( input.readMessage( com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader .parser(), extensionRegistry)); break; } case -32501088: { bitField0_ |= 0x00000040; requestCoalescing_ = input.readBool(); break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000080) != 0)) { negativeCachingPolicy_ = java.util.Collections.unmodifiableList(negativeCachingPolicy_); } if (((mutable_bitField0_ & 0x00000800) != 0)) { signedUrlKeyNames_ = signedUrlKeyNames_.getUnmodifiableView(); } if (((mutable_bitField0_ & 0x00000001) != 0)) { bypassCacheOnRequestHeaders_ = java.util.Collections.unmodifiableList(bypassCacheOnRequestHeaders_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_BackendServiceCdnPolicy_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_BackendServiceCdnPolicy_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.BackendServiceCdnPolicy.class, com.google.cloud.compute.v1.BackendServiceCdnPolicy.Builder.class); } /** * * * <pre> * Specifies the cache setting for all responses from this backend. The possible values are: USE_ORIGIN_HEADERS Requires the origin to set valid caching headers to cache content. Responses without these headers will not be cached at Google's edge, and will require a full trip to the origin on every request, potentially impacting performance and increasing load on the origin server. FORCE_CACHE_ALL Cache all content, ignoring any "private", "no-store" or "no-cache" directives in Cache-Control response headers. Warning: this may result in Cloud CDN caching private, per-user (user identifiable) content. CACHE_ALL_STATIC Automatically cache static content, including common image formats, media (video and audio), and web assets (JavaScript and CSS). Requests and responses that are marked as uncacheable, as well as dynamic content (including HTML), will not be cached. * </pre> * * Protobuf enum {@code google.cloud.compute.v1.BackendServiceCdnPolicy.CacheMode} */ public enum CacheMode implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * A value indicating that the enum field is not set. * </pre> * * <code>UNDEFINED_CACHE_MODE = 0;</code> */ UNDEFINED_CACHE_MODE(0), /** * * * <pre> * Automatically cache static content, including common image formats, media (video and audio), and web assets (JavaScript and CSS). Requests and responses that are marked as uncacheable, as well as dynamic content (including HTML), will not be cached. * </pre> * * <code>CACHE_ALL_STATIC = 355027945;</code> */ CACHE_ALL_STATIC(355027945), /** * * * <pre> * Cache all content, ignoring any "private", "no-store" or "no-cache" directives in Cache-Control response headers. Warning: this may result in Cloud CDN caching private, per-user (user identifiable) content. * </pre> * * <code>FORCE_CACHE_ALL = 486026928;</code> */ FORCE_CACHE_ALL(486026928), /** <code>INVALID_CACHE_MODE = 381295560;</code> */ INVALID_CACHE_MODE(381295560), /** * * * <pre> * Requires the origin to set valid caching headers to cache content. Responses without these headers will not be cached at Google's edge, and will require a full trip to the origin on every request, potentially impacting performance and increasing load on the origin server. * </pre> * * <code>USE_ORIGIN_HEADERS = 55380261;</code> */ USE_ORIGIN_HEADERS(55380261), UNRECOGNIZED(-1), ; /** * * * <pre> * A value indicating that the enum field is not set. * </pre> * * <code>UNDEFINED_CACHE_MODE = 0;</code> */ public static final int UNDEFINED_CACHE_MODE_VALUE = 0; /** * * * <pre> * Automatically cache static content, including common image formats, media (video and audio), and web assets (JavaScript and CSS). Requests and responses that are marked as uncacheable, as well as dynamic content (including HTML), will not be cached. * </pre> * * <code>CACHE_ALL_STATIC = 355027945;</code> */ public static final int CACHE_ALL_STATIC_VALUE = 355027945; /** * * * <pre> * Cache all content, ignoring any "private", "no-store" or "no-cache" directives in Cache-Control response headers. Warning: this may result in Cloud CDN caching private, per-user (user identifiable) content. * </pre> * * <code>FORCE_CACHE_ALL = 486026928;</code> */ public static final int FORCE_CACHE_ALL_VALUE = 486026928; /** <code>INVALID_CACHE_MODE = 381295560;</code> */ public static final int INVALID_CACHE_MODE_VALUE = 381295560; /** * * * <pre> * Requires the origin to set valid caching headers to cache content. Responses without these headers will not be cached at Google's edge, and will require a full trip to the origin on every request, potentially impacting performance and increasing load on the origin server. * </pre> * * <code>USE_ORIGIN_HEADERS = 55380261;</code> */ public static final int USE_ORIGIN_HEADERS_VALUE = 55380261; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static CacheMode valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. */ public static CacheMode forNumber(int value) { switch (value) { case 0: return UNDEFINED_CACHE_MODE; case 355027945: return CACHE_ALL_STATIC; case 486026928: return FORCE_CACHE_ALL; case 381295560: return INVALID_CACHE_MODE; case 55380261: return USE_ORIGIN_HEADERS; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<CacheMode> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<CacheMode> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<CacheMode>() { public CacheMode findValueByNumber(int number) { return CacheMode.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.google.cloud.compute.v1.BackendServiceCdnPolicy.getDescriptor() .getEnumTypes() .get(0); } private static final CacheMode[] VALUES = values(); public static CacheMode valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private CacheMode(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.cloud.compute.v1.BackendServiceCdnPolicy.CacheMode) } private int bitField0_; public static final int BYPASS_CACHE_ON_REQUEST_HEADERS_FIELD_NUMBER = 486203082; private java.util.List< com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader> bypassCacheOnRequestHeaders_; /** * * * <pre> * Bypass the cache when the specified request headers are matched - e.g. Pragma or Authorization headers. Up to 5 headers can be specified. The cache is bypassed for all cdnPolicy.cacheMode settings. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader bypass_cache_on_request_headers = 486203082; * </code> */ @java.lang.Override public java.util.List< com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader> getBypassCacheOnRequestHeadersList() { return bypassCacheOnRequestHeaders_; } /** * * * <pre> * Bypass the cache when the specified request headers are matched - e.g. Pragma or Authorization headers. Up to 5 headers can be specified. The cache is bypassed for all cdnPolicy.cacheMode settings. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader bypass_cache_on_request_headers = 486203082; * </code> */ @java.lang.Override public java.util.List< ? extends com.google.cloud.compute.v1 .BackendServiceCdnPolicyBypassCacheOnRequestHeaderOrBuilder> getBypassCacheOnRequestHeadersOrBuilderList() { return bypassCacheOnRequestHeaders_; } /** * * * <pre> * Bypass the cache when the specified request headers are matched - e.g. Pragma or Authorization headers. Up to 5 headers can be specified. The cache is bypassed for all cdnPolicy.cacheMode settings. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader bypass_cache_on_request_headers = 486203082; * </code> */ @java.lang.Override public int getBypassCacheOnRequestHeadersCount() { return bypassCacheOnRequestHeaders_.size(); } /** * * * <pre> * Bypass the cache when the specified request headers are matched - e.g. Pragma or Authorization headers. Up to 5 headers can be specified. The cache is bypassed for all cdnPolicy.cacheMode settings. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader bypass_cache_on_request_headers = 486203082; * </code> */ @java.lang.Override public com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader getBypassCacheOnRequestHeaders(int index) { return bypassCacheOnRequestHeaders_.get(index); } /** * * * <pre> * Bypass the cache when the specified request headers are matched - e.g. Pragma or Authorization headers. Up to 5 headers can be specified. The cache is bypassed for all cdnPolicy.cacheMode settings. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader bypass_cache_on_request_headers = 486203082; * </code> */ @java.lang.Override public com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeaderOrBuilder getBypassCacheOnRequestHeadersOrBuilder(int index) { return bypassCacheOnRequestHeaders_.get(index); } public static final int CACHE_KEY_POLICY_FIELD_NUMBER = 159263727; private com.google.cloud.compute.v1.CacheKeyPolicy cacheKeyPolicy_; /** * * * <pre> * The CacheKeyPolicy for this CdnPolicy. * </pre> * * <code>optional .google.cloud.compute.v1.CacheKeyPolicy cache_key_policy = 159263727;</code> * * @return Whether the cacheKeyPolicy field is set. */ @java.lang.Override public boolean hasCacheKeyPolicy() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * The CacheKeyPolicy for this CdnPolicy. * </pre> * * <code>optional .google.cloud.compute.v1.CacheKeyPolicy cache_key_policy = 159263727;</code> * * @return The cacheKeyPolicy. */ @java.lang.Override public com.google.cloud.compute.v1.CacheKeyPolicy getCacheKeyPolicy() { return cacheKeyPolicy_ == null ? com.google.cloud.compute.v1.CacheKeyPolicy.getDefaultInstance() : cacheKeyPolicy_; } /** * * * <pre> * The CacheKeyPolicy for this CdnPolicy. * </pre> * * <code>optional .google.cloud.compute.v1.CacheKeyPolicy cache_key_policy = 159263727;</code> */ @java.lang.Override public com.google.cloud.compute.v1.CacheKeyPolicyOrBuilder getCacheKeyPolicyOrBuilder() { return cacheKeyPolicy_ == null ? com.google.cloud.compute.v1.CacheKeyPolicy.getDefaultInstance() : cacheKeyPolicy_; } public static final int CACHE_MODE_FIELD_NUMBER = 28877888; private volatile java.lang.Object cacheMode_; /** * * * <pre> * Specifies the cache setting for all responses from this backend. The possible values are: USE_ORIGIN_HEADERS Requires the origin to set valid caching headers to cache content. Responses without these headers will not be cached at Google's edge, and will require a full trip to the origin on every request, potentially impacting performance and increasing load on the origin server. FORCE_CACHE_ALL Cache all content, ignoring any "private", "no-store" or "no-cache" directives in Cache-Control response headers. Warning: this may result in Cloud CDN caching private, per-user (user identifiable) content. CACHE_ALL_STATIC Automatically cache static content, including common image formats, media (video and audio), and web assets (JavaScript and CSS). Requests and responses that are marked as uncacheable, as well as dynamic content (including HTML), will not be cached. * Check the CacheMode enum for the list of possible values. * </pre> * * <code>optional string cache_mode = 28877888;</code> * * @return Whether the cacheMode field is set. */ @java.lang.Override public boolean hasCacheMode() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Specifies the cache setting for all responses from this backend. The possible values are: USE_ORIGIN_HEADERS Requires the origin to set valid caching headers to cache content. Responses without these headers will not be cached at Google's edge, and will require a full trip to the origin on every request, potentially impacting performance and increasing load on the origin server. FORCE_CACHE_ALL Cache all content, ignoring any "private", "no-store" or "no-cache" directives in Cache-Control response headers. Warning: this may result in Cloud CDN caching private, per-user (user identifiable) content. CACHE_ALL_STATIC Automatically cache static content, including common image formats, media (video and audio), and web assets (JavaScript and CSS). Requests and responses that are marked as uncacheable, as well as dynamic content (including HTML), will not be cached. * Check the CacheMode enum for the list of possible values. * </pre> * * <code>optional string cache_mode = 28877888;</code> * * @return The cacheMode. */ @java.lang.Override public java.lang.String getCacheMode() { java.lang.Object ref = cacheMode_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); cacheMode_ = s; return s; } } /** * * * <pre> * Specifies the cache setting for all responses from this backend. The possible values are: USE_ORIGIN_HEADERS Requires the origin to set valid caching headers to cache content. Responses without these headers will not be cached at Google's edge, and will require a full trip to the origin on every request, potentially impacting performance and increasing load on the origin server. FORCE_CACHE_ALL Cache all content, ignoring any "private", "no-store" or "no-cache" directives in Cache-Control response headers. Warning: this may result in Cloud CDN caching private, per-user (user identifiable) content. CACHE_ALL_STATIC Automatically cache static content, including common image formats, media (video and audio), and web assets (JavaScript and CSS). Requests and responses that are marked as uncacheable, as well as dynamic content (including HTML), will not be cached. * Check the CacheMode enum for the list of possible values. * </pre> * * <code>optional string cache_mode = 28877888;</code> * * @return The bytes for cacheMode. */ @java.lang.Override public com.google.protobuf.ByteString getCacheModeBytes() { java.lang.Object ref = cacheMode_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); cacheMode_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CLIENT_TTL_FIELD_NUMBER = 29034360; private int clientTtl_; /** * * * <pre> * Specifies a separate client (e.g. browser client) maximum TTL. This is used to clamp the max-age (or Expires) value sent to the client. With FORCE_CACHE_ALL, the lesser of client_ttl and default_ttl is used for the response max-age directive, along with a "public" directive. For cacheable content in CACHE_ALL_STATIC mode, client_ttl clamps the max-age from the origin (if specified), or else sets the response max-age directive to the lesser of the client_ttl and default_ttl, and also ensures a "public" cache-control directive is present. If a client TTL is not specified, a default value (1 hour) will be used. The maximum allowed value is 31,622,400s (1 year). * </pre> * * <code>optional int32 client_ttl = 29034360;</code> * * @return Whether the clientTtl field is set. */ @java.lang.Override public boolean hasClientTtl() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Specifies a separate client (e.g. browser client) maximum TTL. This is used to clamp the max-age (or Expires) value sent to the client. With FORCE_CACHE_ALL, the lesser of client_ttl and default_ttl is used for the response max-age directive, along with a "public" directive. For cacheable content in CACHE_ALL_STATIC mode, client_ttl clamps the max-age from the origin (if specified), or else sets the response max-age directive to the lesser of the client_ttl and default_ttl, and also ensures a "public" cache-control directive is present. If a client TTL is not specified, a default value (1 hour) will be used. The maximum allowed value is 31,622,400s (1 year). * </pre> * * <code>optional int32 client_ttl = 29034360;</code> * * @return The clientTtl. */ @java.lang.Override public int getClientTtl() { return clientTtl_; } public static final int DEFAULT_TTL_FIELD_NUMBER = 100253422; private int defaultTtl_; /** * * * <pre> * Specifies the default TTL for cached content served by this origin for responses that do not have an existing valid TTL (max-age or s-max-age). Setting a TTL of "0" means "always revalidate". The value of defaultTTL cannot be set to a value greater than that of maxTTL, but can be equal. When the cacheMode is set to FORCE_CACHE_ALL, the defaultTTL will overwrite the TTL set in all responses. The maximum allowed value is 31,622,400s (1 year), noting that infrequently accessed objects may be evicted from the cache before the defined TTL. * </pre> * * <code>optional int32 default_ttl = 100253422;</code> * * @return Whether the defaultTtl field is set. */ @java.lang.Override public boolean hasDefaultTtl() { return ((bitField0_ & 0x00000008) != 0); } /** * * * <pre> * Specifies the default TTL for cached content served by this origin for responses that do not have an existing valid TTL (max-age or s-max-age). Setting a TTL of "0" means "always revalidate". The value of defaultTTL cannot be set to a value greater than that of maxTTL, but can be equal. When the cacheMode is set to FORCE_CACHE_ALL, the defaultTTL will overwrite the TTL set in all responses. The maximum allowed value is 31,622,400s (1 year), noting that infrequently accessed objects may be evicted from the cache before the defined TTL. * </pre> * * <code>optional int32 default_ttl = 100253422;</code> * * @return The defaultTtl. */ @java.lang.Override public int getDefaultTtl() { return defaultTtl_; } public static final int MAX_TTL_FIELD_NUMBER = 307578001; private int maxTtl_; /** * * * <pre> * Specifies the maximum allowed TTL for cached content served by this origin. Cache directives that attempt to set a max-age or s-maxage higher than this, or an Expires header more than maxTTL seconds in the future will be capped at the value of maxTTL, as if it were the value of an s-maxage Cache-Control directive. Headers sent to the client will not be modified. Setting a TTL of "0" means "always revalidate". The maximum allowed value is 31,622,400s (1 year), noting that infrequently accessed objects may be evicted from the cache before the defined TTL. * </pre> * * <code>optional int32 max_ttl = 307578001;</code> * * @return Whether the maxTtl field is set. */ @java.lang.Override public boolean hasMaxTtl() { return ((bitField0_ & 0x00000010) != 0); } /** * * * <pre> * Specifies the maximum allowed TTL for cached content served by this origin. Cache directives that attempt to set a max-age or s-maxage higher than this, or an Expires header more than maxTTL seconds in the future will be capped at the value of maxTTL, as if it were the value of an s-maxage Cache-Control directive. Headers sent to the client will not be modified. Setting a TTL of "0" means "always revalidate". The maximum allowed value is 31,622,400s (1 year), noting that infrequently accessed objects may be evicted from the cache before the defined TTL. * </pre> * * <code>optional int32 max_ttl = 307578001;</code> * * @return The maxTtl. */ @java.lang.Override public int getMaxTtl() { return maxTtl_; } public static final int NEGATIVE_CACHING_FIELD_NUMBER = 336110005; private boolean negativeCaching_; /** * * * <pre> * Negative caching allows per-status code TTLs to be set, in order to apply fine-grained caching for common errors or redirects. This can reduce the load on your origin and improve end-user experience by reducing response latency. When the cache mode is set to CACHE_ALL_STATIC or USE_ORIGIN_HEADERS, negative caching applies to responses with the specified response code that lack any Cache-Control, Expires, or Pragma: no-cache directives. When the cache mode is set to FORCE_CACHE_ALL, negative caching applies to all responses with the specified response code, and override any caching headers. By default, Cloud CDN will apply the following default TTLs to these status codes: HTTP 300 (Multiple Choice), 301, 308 (Permanent Redirects): 10m HTTP 404 (Not Found), 410 (Gone), 451 (Unavailable For Legal Reasons): 120s HTTP 405 (Method Not Found), 421 (Misdirected Request), 501 (Not Implemented): 60s. These defaults can be overridden in negative_caching_policy. * </pre> * * <code>optional bool negative_caching = 336110005;</code> * * @return Whether the negativeCaching field is set. */ @java.lang.Override public boolean hasNegativeCaching() { return ((bitField0_ & 0x00000020) != 0); } /** * * * <pre> * Negative caching allows per-status code TTLs to be set, in order to apply fine-grained caching for common errors or redirects. This can reduce the load on your origin and improve end-user experience by reducing response latency. When the cache mode is set to CACHE_ALL_STATIC or USE_ORIGIN_HEADERS, negative caching applies to responses with the specified response code that lack any Cache-Control, Expires, or Pragma: no-cache directives. When the cache mode is set to FORCE_CACHE_ALL, negative caching applies to all responses with the specified response code, and override any caching headers. By default, Cloud CDN will apply the following default TTLs to these status codes: HTTP 300 (Multiple Choice), 301, 308 (Permanent Redirects): 10m HTTP 404 (Not Found), 410 (Gone), 451 (Unavailable For Legal Reasons): 120s HTTP 405 (Method Not Found), 421 (Misdirected Request), 501 (Not Implemented): 60s. These defaults can be overridden in negative_caching_policy. * </pre> * * <code>optional bool negative_caching = 336110005;</code> * * @return The negativeCaching. */ @java.lang.Override public boolean getNegativeCaching() { return negativeCaching_; } public static final int NEGATIVE_CACHING_POLICY_FIELD_NUMBER = 155359996; private java.util.List<com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy> negativeCachingPolicy_; /** * * * <pre> * Sets a cache TTL for the specified HTTP status code. negative_caching must be enabled to configure negative_caching_policy. Omitting the policy and leaving negative_caching enabled will use Cloud CDN's default cache TTLs. Note that when specifying an explicit negative_caching_policy, you should take care to specify a cache TTL for all response codes that you wish to cache. Cloud CDN will not apply any default negative caching when a policy exists. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy negative_caching_policy = 155359996; * </code> */ @java.lang.Override public java.util.List<com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy> getNegativeCachingPolicyList() { return negativeCachingPolicy_; } /** * * * <pre> * Sets a cache TTL for the specified HTTP status code. negative_caching must be enabled to configure negative_caching_policy. Omitting the policy and leaving negative_caching enabled will use Cloud CDN's default cache TTLs. Note that when specifying an explicit negative_caching_policy, you should take care to specify a cache TTL for all response codes that you wish to cache. Cloud CDN will not apply any default negative caching when a policy exists. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy negative_caching_policy = 155359996; * </code> */ @java.lang.Override public java.util.List< ? extends com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicyOrBuilder> getNegativeCachingPolicyOrBuilderList() { return negativeCachingPolicy_; } /** * * * <pre> * Sets a cache TTL for the specified HTTP status code. negative_caching must be enabled to configure negative_caching_policy. Omitting the policy and leaving negative_caching enabled will use Cloud CDN's default cache TTLs. Note that when specifying an explicit negative_caching_policy, you should take care to specify a cache TTL for all response codes that you wish to cache. Cloud CDN will not apply any default negative caching when a policy exists. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy negative_caching_policy = 155359996; * </code> */ @java.lang.Override public int getNegativeCachingPolicyCount() { return negativeCachingPolicy_.size(); } /** * * * <pre> * Sets a cache TTL for the specified HTTP status code. negative_caching must be enabled to configure negative_caching_policy. Omitting the policy and leaving negative_caching enabled will use Cloud CDN's default cache TTLs. Note that when specifying an explicit negative_caching_policy, you should take care to specify a cache TTL for all response codes that you wish to cache. Cloud CDN will not apply any default negative caching when a policy exists. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy negative_caching_policy = 155359996; * </code> */ @java.lang.Override public com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy getNegativeCachingPolicy(int index) { return negativeCachingPolicy_.get(index); } /** * * * <pre> * Sets a cache TTL for the specified HTTP status code. negative_caching must be enabled to configure negative_caching_policy. Omitting the policy and leaving negative_caching enabled will use Cloud CDN's default cache TTLs. Note that when specifying an explicit negative_caching_policy, you should take care to specify a cache TTL for all response codes that you wish to cache. Cloud CDN will not apply any default negative caching when a policy exists. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy negative_caching_policy = 155359996; * </code> */ @java.lang.Override public com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicyOrBuilder getNegativeCachingPolicyOrBuilder(int index) { return negativeCachingPolicy_.get(index); } public static final int REQUEST_COALESCING_FIELD_NUMBER = 532808276; private boolean requestCoalescing_; /** * * * <pre> * If true then Cloud CDN will combine multiple concurrent cache fill requests into a small number of requests to the origin. * </pre> * * <code>optional bool request_coalescing = 532808276;</code> * * @return Whether the requestCoalescing field is set. */ @java.lang.Override public boolean hasRequestCoalescing() { return ((bitField0_ & 0x00000040) != 0); } /** * * * <pre> * If true then Cloud CDN will combine multiple concurrent cache fill requests into a small number of requests to the origin. * </pre> * * <code>optional bool request_coalescing = 532808276;</code> * * @return The requestCoalescing. */ @java.lang.Override public boolean getRequestCoalescing() { return requestCoalescing_; } public static final int SERVE_WHILE_STALE_FIELD_NUMBER = 236682203; private int serveWhileStale_; /** * * * <pre> * Serve existing content from the cache (if available) when revalidating content with the origin, or when an error is encountered when refreshing the cache. This setting defines the default "max-stale" duration for any cached responses that do not specify a max-stale directive. Stale responses that exceed the TTL configured here will not be served. The default limit (max-stale) is 86400s (1 day), which will allow stale content to be served up to this limit beyond the max-age (or s-max-age) of a cached response. The maximum allowed value is 604800 (1 week). Set this to zero (0) to disable serve-while-stale. * </pre> * * <code>optional int32 serve_while_stale = 236682203;</code> * * @return Whether the serveWhileStale field is set. */ @java.lang.Override public boolean hasServeWhileStale() { return ((bitField0_ & 0x00000080) != 0); } /** * * * <pre> * Serve existing content from the cache (if available) when revalidating content with the origin, or when an error is encountered when refreshing the cache. This setting defines the default "max-stale" duration for any cached responses that do not specify a max-stale directive. Stale responses that exceed the TTL configured here will not be served. The default limit (max-stale) is 86400s (1 day), which will allow stale content to be served up to this limit beyond the max-age (or s-max-age) of a cached response. The maximum allowed value is 604800 (1 week). Set this to zero (0) to disable serve-while-stale. * </pre> * * <code>optional int32 serve_while_stale = 236682203;</code> * * @return The serveWhileStale. */ @java.lang.Override public int getServeWhileStale() { return serveWhileStale_; } public static final int SIGNED_URL_CACHE_MAX_AGE_SEC_FIELD_NUMBER = 269374534; private long signedUrlCacheMaxAgeSec_; /** * * * <pre> * Maximum number of seconds the response to a signed URL request will be considered fresh. After this time period, the response will be revalidated before being served. Defaults to 1hr (3600s). When serving responses to signed URL requests, Cloud CDN will internally behave as though all responses from this backend had a "Cache-Control: public, max-age=[TTL]" header, regardless of any existing Cache-Control header. The actual headers served in responses will not be altered. * </pre> * * <code>optional int64 signed_url_cache_max_age_sec = 269374534;</code> * * @return Whether the signedUrlCacheMaxAgeSec field is set. */ @java.lang.Override public boolean hasSignedUrlCacheMaxAgeSec() { return ((bitField0_ & 0x00000100) != 0); } /** * * * <pre> * Maximum number of seconds the response to a signed URL request will be considered fresh. After this time period, the response will be revalidated before being served. Defaults to 1hr (3600s). When serving responses to signed URL requests, Cloud CDN will internally behave as though all responses from this backend had a "Cache-Control: public, max-age=[TTL]" header, regardless of any existing Cache-Control header. The actual headers served in responses will not be altered. * </pre> * * <code>optional int64 signed_url_cache_max_age_sec = 269374534;</code> * * @return The signedUrlCacheMaxAgeSec. */ @java.lang.Override public long getSignedUrlCacheMaxAgeSec() { return signedUrlCacheMaxAgeSec_; } public static final int SIGNED_URL_KEY_NAMES_FIELD_NUMBER = 371848885; private com.google.protobuf.LazyStringList signedUrlKeyNames_; /** * * * <pre> * [Output Only] Names of the keys for signing request URLs. * </pre> * * <code>repeated string signed_url_key_names = 371848885;</code> * * @return A list containing the signedUrlKeyNames. */ public com.google.protobuf.ProtocolStringList getSignedUrlKeyNamesList() { return signedUrlKeyNames_; } /** * * * <pre> * [Output Only] Names of the keys for signing request URLs. * </pre> * * <code>repeated string signed_url_key_names = 371848885;</code> * * @return The count of signedUrlKeyNames. */ public int getSignedUrlKeyNamesCount() { return signedUrlKeyNames_.size(); } /** * * * <pre> * [Output Only] Names of the keys for signing request URLs. * </pre> * * <code>repeated string signed_url_key_names = 371848885;</code> * * @param index The index of the element to return. * @return The signedUrlKeyNames at the given index. */ public java.lang.String getSignedUrlKeyNames(int index) { return signedUrlKeyNames_.get(index); } /** * * * <pre> * [Output Only] Names of the keys for signing request URLs. * </pre> * * <code>repeated string signed_url_key_names = 371848885;</code> * * @param index The index of the value to return. * @return The bytes of the signedUrlKeyNames at the given index. */ public com.google.protobuf.ByteString getSignedUrlKeyNamesBytes(int index) { return signedUrlKeyNames_.getByteString(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000002) != 0)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 28877888, cacheMode_); } if (((bitField0_ & 0x00000004) != 0)) { output.writeInt32(29034360, clientTtl_); } if (((bitField0_ & 0x00000008) != 0)) { output.writeInt32(100253422, defaultTtl_); } for (int i = 0; i < negativeCachingPolicy_.size(); i++) { output.writeMessage(155359996, negativeCachingPolicy_.get(i)); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(159263727, getCacheKeyPolicy()); } if (((bitField0_ & 0x00000080) != 0)) { output.writeInt32(236682203, serveWhileStale_); } if (((bitField0_ & 0x00000100) != 0)) { output.writeInt64(269374534, signedUrlCacheMaxAgeSec_); } if (((bitField0_ & 0x00000010) != 0)) { output.writeInt32(307578001, maxTtl_); } if (((bitField0_ & 0x00000020) != 0)) { output.writeBool(336110005, negativeCaching_); } for (int i = 0; i < signedUrlKeyNames_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString( output, 371848885, signedUrlKeyNames_.getRaw(i)); } for (int i = 0; i < bypassCacheOnRequestHeaders_.size(); i++) { output.writeMessage(486203082, bypassCacheOnRequestHeaders_.get(i)); } if (((bitField0_ & 0x00000040) != 0)) { output.writeBool(532808276, requestCoalescing_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(28877888, cacheMode_); } if (((bitField0_ & 0x00000004) != 0)) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(29034360, clientTtl_); } if (((bitField0_ & 0x00000008) != 0)) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(100253422, defaultTtl_); } for (int i = 0; i < negativeCachingPolicy_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 155359996, negativeCachingPolicy_.get(i)); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(159263727, getCacheKeyPolicy()); } if (((bitField0_ & 0x00000080) != 0)) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(236682203, serveWhileStale_); } if (((bitField0_ & 0x00000100) != 0)) { size += com.google.protobuf.CodedOutputStream.computeInt64Size( 269374534, signedUrlCacheMaxAgeSec_); } if (((bitField0_ & 0x00000010) != 0)) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(307578001, maxTtl_); } if (((bitField0_ & 0x00000020) != 0)) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(336110005, negativeCaching_); } { int dataSize = 0; for (int i = 0; i < signedUrlKeyNames_.size(); i++) { dataSize += computeStringSizeNoTag(signedUrlKeyNames_.getRaw(i)); } size += dataSize; size += 5 * getSignedUrlKeyNamesList().size(); } for (int i = 0; i < bypassCacheOnRequestHeaders_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 486203082, bypassCacheOnRequestHeaders_.get(i)); } if (((bitField0_ & 0x00000040) != 0)) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(532808276, requestCoalescing_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.compute.v1.BackendServiceCdnPolicy)) { return super.equals(obj); } com.google.cloud.compute.v1.BackendServiceCdnPolicy other = (com.google.cloud.compute.v1.BackendServiceCdnPolicy) obj; if (!getBypassCacheOnRequestHeadersList().equals(other.getBypassCacheOnRequestHeadersList())) return false; if (hasCacheKeyPolicy() != other.hasCacheKeyPolicy()) return false; if (hasCacheKeyPolicy()) { if (!getCacheKeyPolicy().equals(other.getCacheKeyPolicy())) return false; } if (hasCacheMode() != other.hasCacheMode()) return false; if (hasCacheMode()) { if (!getCacheMode().equals(other.getCacheMode())) return false; } if (hasClientTtl() != other.hasClientTtl()) return false; if (hasClientTtl()) { if (getClientTtl() != other.getClientTtl()) return false; } if (hasDefaultTtl() != other.hasDefaultTtl()) return false; if (hasDefaultTtl()) { if (getDefaultTtl() != other.getDefaultTtl()) return false; } if (hasMaxTtl() != other.hasMaxTtl()) return false; if (hasMaxTtl()) { if (getMaxTtl() != other.getMaxTtl()) return false; } if (hasNegativeCaching() != other.hasNegativeCaching()) return false; if (hasNegativeCaching()) { if (getNegativeCaching() != other.getNegativeCaching()) return false; } if (!getNegativeCachingPolicyList().equals(other.getNegativeCachingPolicyList())) return false; if (hasRequestCoalescing() != other.hasRequestCoalescing()) return false; if (hasRequestCoalescing()) { if (getRequestCoalescing() != other.getRequestCoalescing()) return false; } if (hasServeWhileStale() != other.hasServeWhileStale()) return false; if (hasServeWhileStale()) { if (getServeWhileStale() != other.getServeWhileStale()) return false; } if (hasSignedUrlCacheMaxAgeSec() != other.hasSignedUrlCacheMaxAgeSec()) return false; if (hasSignedUrlCacheMaxAgeSec()) { if (getSignedUrlCacheMaxAgeSec() != other.getSignedUrlCacheMaxAgeSec()) return false; } if (!getSignedUrlKeyNamesList().equals(other.getSignedUrlKeyNamesList())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getBypassCacheOnRequestHeadersCount() > 0) { hash = (37 * hash) + BYPASS_CACHE_ON_REQUEST_HEADERS_FIELD_NUMBER; hash = (53 * hash) + getBypassCacheOnRequestHeadersList().hashCode(); } if (hasCacheKeyPolicy()) { hash = (37 * hash) + CACHE_KEY_POLICY_FIELD_NUMBER; hash = (53 * hash) + getCacheKeyPolicy().hashCode(); } if (hasCacheMode()) { hash = (37 * hash) + CACHE_MODE_FIELD_NUMBER; hash = (53 * hash) + getCacheMode().hashCode(); } if (hasClientTtl()) { hash = (37 * hash) + CLIENT_TTL_FIELD_NUMBER; hash = (53 * hash) + getClientTtl(); } if (hasDefaultTtl()) { hash = (37 * hash) + DEFAULT_TTL_FIELD_NUMBER; hash = (53 * hash) + getDefaultTtl(); } if (hasMaxTtl()) { hash = (37 * hash) + MAX_TTL_FIELD_NUMBER; hash = (53 * hash) + getMaxTtl(); } if (hasNegativeCaching()) { hash = (37 * hash) + NEGATIVE_CACHING_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getNegativeCaching()); } if (getNegativeCachingPolicyCount() > 0) { hash = (37 * hash) + NEGATIVE_CACHING_POLICY_FIELD_NUMBER; hash = (53 * hash) + getNegativeCachingPolicyList().hashCode(); } if (hasRequestCoalescing()) { hash = (37 * hash) + REQUEST_COALESCING_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getRequestCoalescing()); } if (hasServeWhileStale()) { hash = (37 * hash) + SERVE_WHILE_STALE_FIELD_NUMBER; hash = (53 * hash) + getServeWhileStale(); } if (hasSignedUrlCacheMaxAgeSec()) { hash = (37 * hash) + SIGNED_URL_CACHE_MAX_AGE_SEC_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getSignedUrlCacheMaxAgeSec()); } if (getSignedUrlKeyNamesCount() > 0) { hash = (37 * hash) + SIGNED_URL_KEY_NAMES_FIELD_NUMBER; hash = (53 * hash) + getSignedUrlKeyNamesList().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.compute.v1.BackendServiceCdnPolicy parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.BackendServiceCdnPolicy parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.compute.v1.BackendServiceCdnPolicy parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.BackendServiceCdnPolicy parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.compute.v1.BackendServiceCdnPolicy parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.BackendServiceCdnPolicy parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.compute.v1.BackendServiceCdnPolicy parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.BackendServiceCdnPolicy parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.compute.v1.BackendServiceCdnPolicy parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.BackendServiceCdnPolicy parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.compute.v1.BackendServiceCdnPolicy parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.BackendServiceCdnPolicy parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.compute.v1.BackendServiceCdnPolicy prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Message containing Cloud CDN configuration for a backend service. * </pre> * * Protobuf type {@code google.cloud.compute.v1.BackendServiceCdnPolicy} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.BackendServiceCdnPolicy) com.google.cloud.compute.v1.BackendServiceCdnPolicyOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_BackendServiceCdnPolicy_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_BackendServiceCdnPolicy_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.BackendServiceCdnPolicy.class, com.google.cloud.compute.v1.BackendServiceCdnPolicy.Builder.class); } // Construct using com.google.cloud.compute.v1.BackendServiceCdnPolicy.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getBypassCacheOnRequestHeadersFieldBuilder(); getCacheKeyPolicyFieldBuilder(); getNegativeCachingPolicyFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); if (bypassCacheOnRequestHeadersBuilder_ == null) { bypassCacheOnRequestHeaders_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { bypassCacheOnRequestHeadersBuilder_.clear(); } if (cacheKeyPolicyBuilder_ == null) { cacheKeyPolicy_ = null; } else { cacheKeyPolicyBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000002); cacheMode_ = ""; bitField0_ = (bitField0_ & ~0x00000004); clientTtl_ = 0; bitField0_ = (bitField0_ & ~0x00000008); defaultTtl_ = 0; bitField0_ = (bitField0_ & ~0x00000010); maxTtl_ = 0; bitField0_ = (bitField0_ & ~0x00000020); negativeCaching_ = false; bitField0_ = (bitField0_ & ~0x00000040); if (negativeCachingPolicyBuilder_ == null) { negativeCachingPolicy_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000080); } else { negativeCachingPolicyBuilder_.clear(); } requestCoalescing_ = false; bitField0_ = (bitField0_ & ~0x00000100); serveWhileStale_ = 0; bitField0_ = (bitField0_ & ~0x00000200); signedUrlCacheMaxAgeSec_ = 0L; bitField0_ = (bitField0_ & ~0x00000400); signedUrlKeyNames_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000800); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_BackendServiceCdnPolicy_descriptor; } @java.lang.Override public com.google.cloud.compute.v1.BackendServiceCdnPolicy getDefaultInstanceForType() { return com.google.cloud.compute.v1.BackendServiceCdnPolicy.getDefaultInstance(); } @java.lang.Override public com.google.cloud.compute.v1.BackendServiceCdnPolicy build() { com.google.cloud.compute.v1.BackendServiceCdnPolicy result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.compute.v1.BackendServiceCdnPolicy buildPartial() { com.google.cloud.compute.v1.BackendServiceCdnPolicy result = new com.google.cloud.compute.v1.BackendServiceCdnPolicy(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (bypassCacheOnRequestHeadersBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { bypassCacheOnRequestHeaders_ = java.util.Collections.unmodifiableList(bypassCacheOnRequestHeaders_); bitField0_ = (bitField0_ & ~0x00000001); } result.bypassCacheOnRequestHeaders_ = bypassCacheOnRequestHeaders_; } else { result.bypassCacheOnRequestHeaders_ = bypassCacheOnRequestHeadersBuilder_.build(); } if (((from_bitField0_ & 0x00000002) != 0)) { if (cacheKeyPolicyBuilder_ == null) { result.cacheKeyPolicy_ = cacheKeyPolicy_; } else { result.cacheKeyPolicy_ = cacheKeyPolicyBuilder_.build(); } to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000004) != 0)) { to_bitField0_ |= 0x00000002; } result.cacheMode_ = cacheMode_; if (((from_bitField0_ & 0x00000008) != 0)) { result.clientTtl_ = clientTtl_; to_bitField0_ |= 0x00000004; } if (((from_bitField0_ & 0x00000010) != 0)) { result.defaultTtl_ = defaultTtl_; to_bitField0_ |= 0x00000008; } if (((from_bitField0_ & 0x00000020) != 0)) { result.maxTtl_ = maxTtl_; to_bitField0_ |= 0x00000010; } if (((from_bitField0_ & 0x00000040) != 0)) { result.negativeCaching_ = negativeCaching_; to_bitField0_ |= 0x00000020; } if (negativeCachingPolicyBuilder_ == null) { if (((bitField0_ & 0x00000080) != 0)) { negativeCachingPolicy_ = java.util.Collections.unmodifiableList(negativeCachingPolicy_); bitField0_ = (bitField0_ & ~0x00000080); } result.negativeCachingPolicy_ = negativeCachingPolicy_; } else { result.negativeCachingPolicy_ = negativeCachingPolicyBuilder_.build(); } if (((from_bitField0_ & 0x00000100) != 0)) { result.requestCoalescing_ = requestCoalescing_; to_bitField0_ |= 0x00000040; } if (((from_bitField0_ & 0x00000200) != 0)) { result.serveWhileStale_ = serveWhileStale_; to_bitField0_ |= 0x00000080; } if (((from_bitField0_ & 0x00000400) != 0)) { result.signedUrlCacheMaxAgeSec_ = signedUrlCacheMaxAgeSec_; to_bitField0_ |= 0x00000100; } if (((bitField0_ & 0x00000800) != 0)) { signedUrlKeyNames_ = signedUrlKeyNames_.getUnmodifiableView(); bitField0_ = (bitField0_ & ~0x00000800); } result.signedUrlKeyNames_ = signedUrlKeyNames_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.compute.v1.BackendServiceCdnPolicy) { return mergeFrom((com.google.cloud.compute.v1.BackendServiceCdnPolicy) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.compute.v1.BackendServiceCdnPolicy other) { if (other == com.google.cloud.compute.v1.BackendServiceCdnPolicy.getDefaultInstance()) return this; if (bypassCacheOnRequestHeadersBuilder_ == null) { if (!other.bypassCacheOnRequestHeaders_.isEmpty()) { if (bypassCacheOnRequestHeaders_.isEmpty()) { bypassCacheOnRequestHeaders_ = other.bypassCacheOnRequestHeaders_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureBypassCacheOnRequestHeadersIsMutable(); bypassCacheOnRequestHeaders_.addAll(other.bypassCacheOnRequestHeaders_); } onChanged(); } } else { if (!other.bypassCacheOnRequestHeaders_.isEmpty()) { if (bypassCacheOnRequestHeadersBuilder_.isEmpty()) { bypassCacheOnRequestHeadersBuilder_.dispose(); bypassCacheOnRequestHeadersBuilder_ = null; bypassCacheOnRequestHeaders_ = other.bypassCacheOnRequestHeaders_; bitField0_ = (bitField0_ & ~0x00000001); bypassCacheOnRequestHeadersBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getBypassCacheOnRequestHeadersFieldBuilder() : null; } else { bypassCacheOnRequestHeadersBuilder_.addAllMessages(other.bypassCacheOnRequestHeaders_); } } } if (other.hasCacheKeyPolicy()) { mergeCacheKeyPolicy(other.getCacheKeyPolicy()); } if (other.hasCacheMode()) { bitField0_ |= 0x00000004; cacheMode_ = other.cacheMode_; onChanged(); } if (other.hasClientTtl()) { setClientTtl(other.getClientTtl()); } if (other.hasDefaultTtl()) { setDefaultTtl(other.getDefaultTtl()); } if (other.hasMaxTtl()) { setMaxTtl(other.getMaxTtl()); } if (other.hasNegativeCaching()) { setNegativeCaching(other.getNegativeCaching()); } if (negativeCachingPolicyBuilder_ == null) { if (!other.negativeCachingPolicy_.isEmpty()) { if (negativeCachingPolicy_.isEmpty()) { negativeCachingPolicy_ = other.negativeCachingPolicy_; bitField0_ = (bitField0_ & ~0x00000080); } else { ensureNegativeCachingPolicyIsMutable(); negativeCachingPolicy_.addAll(other.negativeCachingPolicy_); } onChanged(); } } else { if (!other.negativeCachingPolicy_.isEmpty()) { if (negativeCachingPolicyBuilder_.isEmpty()) { negativeCachingPolicyBuilder_.dispose(); negativeCachingPolicyBuilder_ = null; negativeCachingPolicy_ = other.negativeCachingPolicy_; bitField0_ = (bitField0_ & ~0x00000080); negativeCachingPolicyBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getNegativeCachingPolicyFieldBuilder() : null; } else { negativeCachingPolicyBuilder_.addAllMessages(other.negativeCachingPolicy_); } } } if (other.hasRequestCoalescing()) { setRequestCoalescing(other.getRequestCoalescing()); } if (other.hasServeWhileStale()) { setServeWhileStale(other.getServeWhileStale()); } if (other.hasSignedUrlCacheMaxAgeSec()) { setSignedUrlCacheMaxAgeSec(other.getSignedUrlCacheMaxAgeSec()); } if (!other.signedUrlKeyNames_.isEmpty()) { if (signedUrlKeyNames_.isEmpty()) { signedUrlKeyNames_ = other.signedUrlKeyNames_; bitField0_ = (bitField0_ & ~0x00000800); } else { ensureSignedUrlKeyNamesIsMutable(); signedUrlKeyNames_.addAll(other.signedUrlKeyNames_); } onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.compute.v1.BackendServiceCdnPolicy parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.compute.v1.BackendServiceCdnPolicy) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.util.List< com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader> bypassCacheOnRequestHeaders_ = java.util.Collections.emptyList(); private void ensureBypassCacheOnRequestHeadersIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { bypassCacheOnRequestHeaders_ = new java.util.ArrayList< com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader>( bypassCacheOnRequestHeaders_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader, com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader.Builder, com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeaderOrBuilder> bypassCacheOnRequestHeadersBuilder_; /** * * * <pre> * Bypass the cache when the specified request headers are matched - e.g. Pragma or Authorization headers. Up to 5 headers can be specified. The cache is bypassed for all cdnPolicy.cacheMode settings. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader bypass_cache_on_request_headers = 486203082; * </code> */ public java.util.List< com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader> getBypassCacheOnRequestHeadersList() { if (bypassCacheOnRequestHeadersBuilder_ == null) { return java.util.Collections.unmodifiableList(bypassCacheOnRequestHeaders_); } else { return bypassCacheOnRequestHeadersBuilder_.getMessageList(); } } /** * * * <pre> * Bypass the cache when the specified request headers are matched - e.g. Pragma or Authorization headers. Up to 5 headers can be specified. The cache is bypassed for all cdnPolicy.cacheMode settings. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader bypass_cache_on_request_headers = 486203082; * </code> */ public int getBypassCacheOnRequestHeadersCount() { if (bypassCacheOnRequestHeadersBuilder_ == null) { return bypassCacheOnRequestHeaders_.size(); } else { return bypassCacheOnRequestHeadersBuilder_.getCount(); } } /** * * * <pre> * Bypass the cache when the specified request headers are matched - e.g. Pragma or Authorization headers. Up to 5 headers can be specified. The cache is bypassed for all cdnPolicy.cacheMode settings. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader bypass_cache_on_request_headers = 486203082; * </code> */ public com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader getBypassCacheOnRequestHeaders(int index) { if (bypassCacheOnRequestHeadersBuilder_ == null) { return bypassCacheOnRequestHeaders_.get(index); } else { return bypassCacheOnRequestHeadersBuilder_.getMessage(index); } } /** * * * <pre> * Bypass the cache when the specified request headers are matched - e.g. Pragma or Authorization headers. Up to 5 headers can be specified. The cache is bypassed for all cdnPolicy.cacheMode settings. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader bypass_cache_on_request_headers = 486203082; * </code> */ public Builder setBypassCacheOnRequestHeaders( int index, com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader value) { if (bypassCacheOnRequestHeadersBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureBypassCacheOnRequestHeadersIsMutable(); bypassCacheOnRequestHeaders_.set(index, value); onChanged(); } else { bypassCacheOnRequestHeadersBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * Bypass the cache when the specified request headers are matched - e.g. Pragma or Authorization headers. Up to 5 headers can be specified. The cache is bypassed for all cdnPolicy.cacheMode settings. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader bypass_cache_on_request_headers = 486203082; * </code> */ public Builder setBypassCacheOnRequestHeaders( int index, com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader.Builder builderForValue) { if (bypassCacheOnRequestHeadersBuilder_ == null) { ensureBypassCacheOnRequestHeadersIsMutable(); bypassCacheOnRequestHeaders_.set(index, builderForValue.build()); onChanged(); } else { bypassCacheOnRequestHeadersBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Bypass the cache when the specified request headers are matched - e.g. Pragma or Authorization headers. Up to 5 headers can be specified. The cache is bypassed for all cdnPolicy.cacheMode settings. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader bypass_cache_on_request_headers = 486203082; * </code> */ public Builder addBypassCacheOnRequestHeaders( com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader value) { if (bypassCacheOnRequestHeadersBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureBypassCacheOnRequestHeadersIsMutable(); bypassCacheOnRequestHeaders_.add(value); onChanged(); } else { bypassCacheOnRequestHeadersBuilder_.addMessage(value); } return this; } /** * * * <pre> * Bypass the cache when the specified request headers are matched - e.g. Pragma or Authorization headers. Up to 5 headers can be specified. The cache is bypassed for all cdnPolicy.cacheMode settings. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader bypass_cache_on_request_headers = 486203082; * </code> */ public Builder addBypassCacheOnRequestHeaders( int index, com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader value) { if (bypassCacheOnRequestHeadersBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureBypassCacheOnRequestHeadersIsMutable(); bypassCacheOnRequestHeaders_.add(index, value); onChanged(); } else { bypassCacheOnRequestHeadersBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * Bypass the cache when the specified request headers are matched - e.g. Pragma or Authorization headers. Up to 5 headers can be specified. The cache is bypassed for all cdnPolicy.cacheMode settings. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader bypass_cache_on_request_headers = 486203082; * </code> */ public Builder addBypassCacheOnRequestHeaders( com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader.Builder builderForValue) { if (bypassCacheOnRequestHeadersBuilder_ == null) { ensureBypassCacheOnRequestHeadersIsMutable(); bypassCacheOnRequestHeaders_.add(builderForValue.build()); onChanged(); } else { bypassCacheOnRequestHeadersBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * Bypass the cache when the specified request headers are matched - e.g. Pragma or Authorization headers. Up to 5 headers can be specified. The cache is bypassed for all cdnPolicy.cacheMode settings. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader bypass_cache_on_request_headers = 486203082; * </code> */ public Builder addBypassCacheOnRequestHeaders( int index, com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader.Builder builderForValue) { if (bypassCacheOnRequestHeadersBuilder_ == null) { ensureBypassCacheOnRequestHeadersIsMutable(); bypassCacheOnRequestHeaders_.add(index, builderForValue.build()); onChanged(); } else { bypassCacheOnRequestHeadersBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Bypass the cache when the specified request headers are matched - e.g. Pragma or Authorization headers. Up to 5 headers can be specified. The cache is bypassed for all cdnPolicy.cacheMode settings. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader bypass_cache_on_request_headers = 486203082; * </code> */ public Builder addAllBypassCacheOnRequestHeaders( java.lang.Iterable< ? extends com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader> values) { if (bypassCacheOnRequestHeadersBuilder_ == null) { ensureBypassCacheOnRequestHeadersIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, bypassCacheOnRequestHeaders_); onChanged(); } else { bypassCacheOnRequestHeadersBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * Bypass the cache when the specified request headers are matched - e.g. Pragma or Authorization headers. Up to 5 headers can be specified. The cache is bypassed for all cdnPolicy.cacheMode settings. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader bypass_cache_on_request_headers = 486203082; * </code> */ public Builder clearBypassCacheOnRequestHeaders() { if (bypassCacheOnRequestHeadersBuilder_ == null) { bypassCacheOnRequestHeaders_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { bypassCacheOnRequestHeadersBuilder_.clear(); } return this; } /** * * * <pre> * Bypass the cache when the specified request headers are matched - e.g. Pragma or Authorization headers. Up to 5 headers can be specified. The cache is bypassed for all cdnPolicy.cacheMode settings. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader bypass_cache_on_request_headers = 486203082; * </code> */ public Builder removeBypassCacheOnRequestHeaders(int index) { if (bypassCacheOnRequestHeadersBuilder_ == null) { ensureBypassCacheOnRequestHeadersIsMutable(); bypassCacheOnRequestHeaders_.remove(index); onChanged(); } else { bypassCacheOnRequestHeadersBuilder_.remove(index); } return this; } /** * * * <pre> * Bypass the cache when the specified request headers are matched - e.g. Pragma or Authorization headers. Up to 5 headers can be specified. The cache is bypassed for all cdnPolicy.cacheMode settings. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader bypass_cache_on_request_headers = 486203082; * </code> */ public com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader.Builder getBypassCacheOnRequestHeadersBuilder(int index) { return getBypassCacheOnRequestHeadersFieldBuilder().getBuilder(index); } /** * * * <pre> * Bypass the cache when the specified request headers are matched - e.g. Pragma or Authorization headers. Up to 5 headers can be specified. The cache is bypassed for all cdnPolicy.cacheMode settings. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader bypass_cache_on_request_headers = 486203082; * </code> */ public com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeaderOrBuilder getBypassCacheOnRequestHeadersOrBuilder(int index) { if (bypassCacheOnRequestHeadersBuilder_ == null) { return bypassCacheOnRequestHeaders_.get(index); } else { return bypassCacheOnRequestHeadersBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * Bypass the cache when the specified request headers are matched - e.g. Pragma or Authorization headers. Up to 5 headers can be specified. The cache is bypassed for all cdnPolicy.cacheMode settings. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader bypass_cache_on_request_headers = 486203082; * </code> */ public java.util.List< ? extends com.google.cloud.compute.v1 .BackendServiceCdnPolicyBypassCacheOnRequestHeaderOrBuilder> getBypassCacheOnRequestHeadersOrBuilderList() { if (bypassCacheOnRequestHeadersBuilder_ != null) { return bypassCacheOnRequestHeadersBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(bypassCacheOnRequestHeaders_); } } /** * * * <pre> * Bypass the cache when the specified request headers are matched - e.g. Pragma or Authorization headers. Up to 5 headers can be specified. The cache is bypassed for all cdnPolicy.cacheMode settings. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader bypass_cache_on_request_headers = 486203082; * </code> */ public com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader.Builder addBypassCacheOnRequestHeadersBuilder() { return getBypassCacheOnRequestHeadersFieldBuilder() .addBuilder( com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader .getDefaultInstance()); } /** * * * <pre> * Bypass the cache when the specified request headers are matched - e.g. Pragma or Authorization headers. Up to 5 headers can be specified. The cache is bypassed for all cdnPolicy.cacheMode settings. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader bypass_cache_on_request_headers = 486203082; * </code> */ public com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader.Builder addBypassCacheOnRequestHeadersBuilder(int index) { return getBypassCacheOnRequestHeadersFieldBuilder() .addBuilder( index, com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader .getDefaultInstance()); } /** * * * <pre> * Bypass the cache when the specified request headers are matched - e.g. Pragma or Authorization headers. Up to 5 headers can be specified. The cache is bypassed for all cdnPolicy.cacheMode settings. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader bypass_cache_on_request_headers = 486203082; * </code> */ public java.util.List< com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader.Builder> getBypassCacheOnRequestHeadersBuilderList() { return getBypassCacheOnRequestHeadersFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader, com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader.Builder, com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeaderOrBuilder> getBypassCacheOnRequestHeadersFieldBuilder() { if (bypassCacheOnRequestHeadersBuilder_ == null) { bypassCacheOnRequestHeadersBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader, com.google.cloud.compute.v1.BackendServiceCdnPolicyBypassCacheOnRequestHeader .Builder, com.google.cloud.compute.v1 .BackendServiceCdnPolicyBypassCacheOnRequestHeaderOrBuilder>( bypassCacheOnRequestHeaders_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); bypassCacheOnRequestHeaders_ = null; } return bypassCacheOnRequestHeadersBuilder_; } private com.google.cloud.compute.v1.CacheKeyPolicy cacheKeyPolicy_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.compute.v1.CacheKeyPolicy, com.google.cloud.compute.v1.CacheKeyPolicy.Builder, com.google.cloud.compute.v1.CacheKeyPolicyOrBuilder> cacheKeyPolicyBuilder_; /** * * * <pre> * The CacheKeyPolicy for this CdnPolicy. * </pre> * * <code>optional .google.cloud.compute.v1.CacheKeyPolicy cache_key_policy = 159263727;</code> * * @return Whether the cacheKeyPolicy field is set. */ public boolean hasCacheKeyPolicy() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * The CacheKeyPolicy for this CdnPolicy. * </pre> * * <code>optional .google.cloud.compute.v1.CacheKeyPolicy cache_key_policy = 159263727;</code> * * @return The cacheKeyPolicy. */ public com.google.cloud.compute.v1.CacheKeyPolicy getCacheKeyPolicy() { if (cacheKeyPolicyBuilder_ == null) { return cacheKeyPolicy_ == null ? com.google.cloud.compute.v1.CacheKeyPolicy.getDefaultInstance() : cacheKeyPolicy_; } else { return cacheKeyPolicyBuilder_.getMessage(); } } /** * * * <pre> * The CacheKeyPolicy for this CdnPolicy. * </pre> * * <code>optional .google.cloud.compute.v1.CacheKeyPolicy cache_key_policy = 159263727;</code> */ public Builder setCacheKeyPolicy(com.google.cloud.compute.v1.CacheKeyPolicy value) { if (cacheKeyPolicyBuilder_ == null) { if (value == null) { throw new NullPointerException(); } cacheKeyPolicy_ = value; onChanged(); } else { cacheKeyPolicyBuilder_.setMessage(value); } bitField0_ |= 0x00000002; return this; } /** * * * <pre> * The CacheKeyPolicy for this CdnPolicy. * </pre> * * <code>optional .google.cloud.compute.v1.CacheKeyPolicy cache_key_policy = 159263727;</code> */ public Builder setCacheKeyPolicy( com.google.cloud.compute.v1.CacheKeyPolicy.Builder builderForValue) { if (cacheKeyPolicyBuilder_ == null) { cacheKeyPolicy_ = builderForValue.build(); onChanged(); } else { cacheKeyPolicyBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; return this; } /** * * * <pre> * The CacheKeyPolicy for this CdnPolicy. * </pre> * * <code>optional .google.cloud.compute.v1.CacheKeyPolicy cache_key_policy = 159263727;</code> */ public Builder mergeCacheKeyPolicy(com.google.cloud.compute.v1.CacheKeyPolicy value) { if (cacheKeyPolicyBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && cacheKeyPolicy_ != null && cacheKeyPolicy_ != com.google.cloud.compute.v1.CacheKeyPolicy.getDefaultInstance()) { cacheKeyPolicy_ = com.google.cloud.compute.v1.CacheKeyPolicy.newBuilder(cacheKeyPolicy_) .mergeFrom(value) .buildPartial(); } else { cacheKeyPolicy_ = value; } onChanged(); } else { cacheKeyPolicyBuilder_.mergeFrom(value); } bitField0_ |= 0x00000002; return this; } /** * * * <pre> * The CacheKeyPolicy for this CdnPolicy. * </pre> * * <code>optional .google.cloud.compute.v1.CacheKeyPolicy cache_key_policy = 159263727;</code> */ public Builder clearCacheKeyPolicy() { if (cacheKeyPolicyBuilder_ == null) { cacheKeyPolicy_ = null; onChanged(); } else { cacheKeyPolicyBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000002); return this; } /** * * * <pre> * The CacheKeyPolicy for this CdnPolicy. * </pre> * * <code>optional .google.cloud.compute.v1.CacheKeyPolicy cache_key_policy = 159263727;</code> */ public com.google.cloud.compute.v1.CacheKeyPolicy.Builder getCacheKeyPolicyBuilder() { bitField0_ |= 0x00000002; onChanged(); return getCacheKeyPolicyFieldBuilder().getBuilder(); } /** * * * <pre> * The CacheKeyPolicy for this CdnPolicy. * </pre> * * <code>optional .google.cloud.compute.v1.CacheKeyPolicy cache_key_policy = 159263727;</code> */ public com.google.cloud.compute.v1.CacheKeyPolicyOrBuilder getCacheKeyPolicyOrBuilder() { if (cacheKeyPolicyBuilder_ != null) { return cacheKeyPolicyBuilder_.getMessageOrBuilder(); } else { return cacheKeyPolicy_ == null ? com.google.cloud.compute.v1.CacheKeyPolicy.getDefaultInstance() : cacheKeyPolicy_; } } /** * * * <pre> * The CacheKeyPolicy for this CdnPolicy. * </pre> * * <code>optional .google.cloud.compute.v1.CacheKeyPolicy cache_key_policy = 159263727;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.compute.v1.CacheKeyPolicy, com.google.cloud.compute.v1.CacheKeyPolicy.Builder, com.google.cloud.compute.v1.CacheKeyPolicyOrBuilder> getCacheKeyPolicyFieldBuilder() { if (cacheKeyPolicyBuilder_ == null) { cacheKeyPolicyBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.compute.v1.CacheKeyPolicy, com.google.cloud.compute.v1.CacheKeyPolicy.Builder, com.google.cloud.compute.v1.CacheKeyPolicyOrBuilder>( getCacheKeyPolicy(), getParentForChildren(), isClean()); cacheKeyPolicy_ = null; } return cacheKeyPolicyBuilder_; } private java.lang.Object cacheMode_ = ""; /** * * * <pre> * Specifies the cache setting for all responses from this backend. The possible values are: USE_ORIGIN_HEADERS Requires the origin to set valid caching headers to cache content. Responses without these headers will not be cached at Google's edge, and will require a full trip to the origin on every request, potentially impacting performance and increasing load on the origin server. FORCE_CACHE_ALL Cache all content, ignoring any "private", "no-store" or "no-cache" directives in Cache-Control response headers. Warning: this may result in Cloud CDN caching private, per-user (user identifiable) content. CACHE_ALL_STATIC Automatically cache static content, including common image formats, media (video and audio), and web assets (JavaScript and CSS). Requests and responses that are marked as uncacheable, as well as dynamic content (including HTML), will not be cached. * Check the CacheMode enum for the list of possible values. * </pre> * * <code>optional string cache_mode = 28877888;</code> * * @return Whether the cacheMode field is set. */ public boolean hasCacheMode() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Specifies the cache setting for all responses from this backend. The possible values are: USE_ORIGIN_HEADERS Requires the origin to set valid caching headers to cache content. Responses without these headers will not be cached at Google's edge, and will require a full trip to the origin on every request, potentially impacting performance and increasing load on the origin server. FORCE_CACHE_ALL Cache all content, ignoring any "private", "no-store" or "no-cache" directives in Cache-Control response headers. Warning: this may result in Cloud CDN caching private, per-user (user identifiable) content. CACHE_ALL_STATIC Automatically cache static content, including common image formats, media (video and audio), and web assets (JavaScript and CSS). Requests and responses that are marked as uncacheable, as well as dynamic content (including HTML), will not be cached. * Check the CacheMode enum for the list of possible values. * </pre> * * <code>optional string cache_mode = 28877888;</code> * * @return The cacheMode. */ public java.lang.String getCacheMode() { java.lang.Object ref = cacheMode_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); cacheMode_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Specifies the cache setting for all responses from this backend. The possible values are: USE_ORIGIN_HEADERS Requires the origin to set valid caching headers to cache content. Responses without these headers will not be cached at Google's edge, and will require a full trip to the origin on every request, potentially impacting performance and increasing load on the origin server. FORCE_CACHE_ALL Cache all content, ignoring any "private", "no-store" or "no-cache" directives in Cache-Control response headers. Warning: this may result in Cloud CDN caching private, per-user (user identifiable) content. CACHE_ALL_STATIC Automatically cache static content, including common image formats, media (video and audio), and web assets (JavaScript and CSS). Requests and responses that are marked as uncacheable, as well as dynamic content (including HTML), will not be cached. * Check the CacheMode enum for the list of possible values. * </pre> * * <code>optional string cache_mode = 28877888;</code> * * @return The bytes for cacheMode. */ public com.google.protobuf.ByteString getCacheModeBytes() { java.lang.Object ref = cacheMode_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); cacheMode_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Specifies the cache setting for all responses from this backend. The possible values are: USE_ORIGIN_HEADERS Requires the origin to set valid caching headers to cache content. Responses without these headers will not be cached at Google's edge, and will require a full trip to the origin on every request, potentially impacting performance and increasing load on the origin server. FORCE_CACHE_ALL Cache all content, ignoring any "private", "no-store" or "no-cache" directives in Cache-Control response headers. Warning: this may result in Cloud CDN caching private, per-user (user identifiable) content. CACHE_ALL_STATIC Automatically cache static content, including common image formats, media (video and audio), and web assets (JavaScript and CSS). Requests and responses that are marked as uncacheable, as well as dynamic content (including HTML), will not be cached. * Check the CacheMode enum for the list of possible values. * </pre> * * <code>optional string cache_mode = 28877888;</code> * * @param value The cacheMode to set. * @return This builder for chaining. */ public Builder setCacheMode(java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; cacheMode_ = value; onChanged(); return this; } /** * * * <pre> * Specifies the cache setting for all responses from this backend. The possible values are: USE_ORIGIN_HEADERS Requires the origin to set valid caching headers to cache content. Responses without these headers will not be cached at Google's edge, and will require a full trip to the origin on every request, potentially impacting performance and increasing load on the origin server. FORCE_CACHE_ALL Cache all content, ignoring any "private", "no-store" or "no-cache" directives in Cache-Control response headers. Warning: this may result in Cloud CDN caching private, per-user (user identifiable) content. CACHE_ALL_STATIC Automatically cache static content, including common image formats, media (video and audio), and web assets (JavaScript and CSS). Requests and responses that are marked as uncacheable, as well as dynamic content (including HTML), will not be cached. * Check the CacheMode enum for the list of possible values. * </pre> * * <code>optional string cache_mode = 28877888;</code> * * @return This builder for chaining. */ public Builder clearCacheMode() { bitField0_ = (bitField0_ & ~0x00000004); cacheMode_ = getDefaultInstance().getCacheMode(); onChanged(); return this; } /** * * * <pre> * Specifies the cache setting for all responses from this backend. The possible values are: USE_ORIGIN_HEADERS Requires the origin to set valid caching headers to cache content. Responses without these headers will not be cached at Google's edge, and will require a full trip to the origin on every request, potentially impacting performance and increasing load on the origin server. FORCE_CACHE_ALL Cache all content, ignoring any "private", "no-store" or "no-cache" directives in Cache-Control response headers. Warning: this may result in Cloud CDN caching private, per-user (user identifiable) content. CACHE_ALL_STATIC Automatically cache static content, including common image formats, media (video and audio), and web assets (JavaScript and CSS). Requests and responses that are marked as uncacheable, as well as dynamic content (including HTML), will not be cached. * Check the CacheMode enum for the list of possible values. * </pre> * * <code>optional string cache_mode = 28877888;</code> * * @param value The bytes for cacheMode to set. * @return This builder for chaining. */ public Builder setCacheModeBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); bitField0_ |= 0x00000004; cacheMode_ = value; onChanged(); return this; } private int clientTtl_; /** * * * <pre> * Specifies a separate client (e.g. browser client) maximum TTL. This is used to clamp the max-age (or Expires) value sent to the client. With FORCE_CACHE_ALL, the lesser of client_ttl and default_ttl is used for the response max-age directive, along with a "public" directive. For cacheable content in CACHE_ALL_STATIC mode, client_ttl clamps the max-age from the origin (if specified), or else sets the response max-age directive to the lesser of the client_ttl and default_ttl, and also ensures a "public" cache-control directive is present. If a client TTL is not specified, a default value (1 hour) will be used. The maximum allowed value is 31,622,400s (1 year). * </pre> * * <code>optional int32 client_ttl = 29034360;</code> * * @return Whether the clientTtl field is set. */ @java.lang.Override public boolean hasClientTtl() { return ((bitField0_ & 0x00000008) != 0); } /** * * * <pre> * Specifies a separate client (e.g. browser client) maximum TTL. This is used to clamp the max-age (or Expires) value sent to the client. With FORCE_CACHE_ALL, the lesser of client_ttl and default_ttl is used for the response max-age directive, along with a "public" directive. For cacheable content in CACHE_ALL_STATIC mode, client_ttl clamps the max-age from the origin (if specified), or else sets the response max-age directive to the lesser of the client_ttl and default_ttl, and also ensures a "public" cache-control directive is present. If a client TTL is not specified, a default value (1 hour) will be used. The maximum allowed value is 31,622,400s (1 year). * </pre> * * <code>optional int32 client_ttl = 29034360;</code> * * @return The clientTtl. */ @java.lang.Override public int getClientTtl() { return clientTtl_; } /** * * * <pre> * Specifies a separate client (e.g. browser client) maximum TTL. This is used to clamp the max-age (or Expires) value sent to the client. With FORCE_CACHE_ALL, the lesser of client_ttl and default_ttl is used for the response max-age directive, along with a "public" directive. For cacheable content in CACHE_ALL_STATIC mode, client_ttl clamps the max-age from the origin (if specified), or else sets the response max-age directive to the lesser of the client_ttl and default_ttl, and also ensures a "public" cache-control directive is present. If a client TTL is not specified, a default value (1 hour) will be used. The maximum allowed value is 31,622,400s (1 year). * </pre> * * <code>optional int32 client_ttl = 29034360;</code> * * @param value The clientTtl to set. * @return This builder for chaining. */ public Builder setClientTtl(int value) { bitField0_ |= 0x00000008; clientTtl_ = value; onChanged(); return this; } /** * * * <pre> * Specifies a separate client (e.g. browser client) maximum TTL. This is used to clamp the max-age (or Expires) value sent to the client. With FORCE_CACHE_ALL, the lesser of client_ttl and default_ttl is used for the response max-age directive, along with a "public" directive. For cacheable content in CACHE_ALL_STATIC mode, client_ttl clamps the max-age from the origin (if specified), or else sets the response max-age directive to the lesser of the client_ttl and default_ttl, and also ensures a "public" cache-control directive is present. If a client TTL is not specified, a default value (1 hour) will be used. The maximum allowed value is 31,622,400s (1 year). * </pre> * * <code>optional int32 client_ttl = 29034360;</code> * * @return This builder for chaining. */ public Builder clearClientTtl() { bitField0_ = (bitField0_ & ~0x00000008); clientTtl_ = 0; onChanged(); return this; } private int defaultTtl_; /** * * * <pre> * Specifies the default TTL for cached content served by this origin for responses that do not have an existing valid TTL (max-age or s-max-age). Setting a TTL of "0" means "always revalidate". The value of defaultTTL cannot be set to a value greater than that of maxTTL, but can be equal. When the cacheMode is set to FORCE_CACHE_ALL, the defaultTTL will overwrite the TTL set in all responses. The maximum allowed value is 31,622,400s (1 year), noting that infrequently accessed objects may be evicted from the cache before the defined TTL. * </pre> * * <code>optional int32 default_ttl = 100253422;</code> * * @return Whether the defaultTtl field is set. */ @java.lang.Override public boolean hasDefaultTtl() { return ((bitField0_ & 0x00000010) != 0); } /** * * * <pre> * Specifies the default TTL for cached content served by this origin for responses that do not have an existing valid TTL (max-age or s-max-age). Setting a TTL of "0" means "always revalidate". The value of defaultTTL cannot be set to a value greater than that of maxTTL, but can be equal. When the cacheMode is set to FORCE_CACHE_ALL, the defaultTTL will overwrite the TTL set in all responses. The maximum allowed value is 31,622,400s (1 year), noting that infrequently accessed objects may be evicted from the cache before the defined TTL. * </pre> * * <code>optional int32 default_ttl = 100253422;</code> * * @return The defaultTtl. */ @java.lang.Override public int getDefaultTtl() { return defaultTtl_; } /** * * * <pre> * Specifies the default TTL for cached content served by this origin for responses that do not have an existing valid TTL (max-age or s-max-age). Setting a TTL of "0" means "always revalidate". The value of defaultTTL cannot be set to a value greater than that of maxTTL, but can be equal. When the cacheMode is set to FORCE_CACHE_ALL, the defaultTTL will overwrite the TTL set in all responses. The maximum allowed value is 31,622,400s (1 year), noting that infrequently accessed objects may be evicted from the cache before the defined TTL. * </pre> * * <code>optional int32 default_ttl = 100253422;</code> * * @param value The defaultTtl to set. * @return This builder for chaining. */ public Builder setDefaultTtl(int value) { bitField0_ |= 0x00000010; defaultTtl_ = value; onChanged(); return this; } /** * * * <pre> * Specifies the default TTL for cached content served by this origin for responses that do not have an existing valid TTL (max-age or s-max-age). Setting a TTL of "0" means "always revalidate". The value of defaultTTL cannot be set to a value greater than that of maxTTL, but can be equal. When the cacheMode is set to FORCE_CACHE_ALL, the defaultTTL will overwrite the TTL set in all responses. The maximum allowed value is 31,622,400s (1 year), noting that infrequently accessed objects may be evicted from the cache before the defined TTL. * </pre> * * <code>optional int32 default_ttl = 100253422;</code> * * @return This builder for chaining. */ public Builder clearDefaultTtl() { bitField0_ = (bitField0_ & ~0x00000010); defaultTtl_ = 0; onChanged(); return this; } private int maxTtl_; /** * * * <pre> * Specifies the maximum allowed TTL for cached content served by this origin. Cache directives that attempt to set a max-age or s-maxage higher than this, or an Expires header more than maxTTL seconds in the future will be capped at the value of maxTTL, as if it were the value of an s-maxage Cache-Control directive. Headers sent to the client will not be modified. Setting a TTL of "0" means "always revalidate". The maximum allowed value is 31,622,400s (1 year), noting that infrequently accessed objects may be evicted from the cache before the defined TTL. * </pre> * * <code>optional int32 max_ttl = 307578001;</code> * * @return Whether the maxTtl field is set. */ @java.lang.Override public boolean hasMaxTtl() { return ((bitField0_ & 0x00000020) != 0); } /** * * * <pre> * Specifies the maximum allowed TTL for cached content served by this origin. Cache directives that attempt to set a max-age or s-maxage higher than this, or an Expires header more than maxTTL seconds in the future will be capped at the value of maxTTL, as if it were the value of an s-maxage Cache-Control directive. Headers sent to the client will not be modified. Setting a TTL of "0" means "always revalidate". The maximum allowed value is 31,622,400s (1 year), noting that infrequently accessed objects may be evicted from the cache before the defined TTL. * </pre> * * <code>optional int32 max_ttl = 307578001;</code> * * @return The maxTtl. */ @java.lang.Override public int getMaxTtl() { return maxTtl_; } /** * * * <pre> * Specifies the maximum allowed TTL for cached content served by this origin. Cache directives that attempt to set a max-age or s-maxage higher than this, or an Expires header more than maxTTL seconds in the future will be capped at the value of maxTTL, as if it were the value of an s-maxage Cache-Control directive. Headers sent to the client will not be modified. Setting a TTL of "0" means "always revalidate". The maximum allowed value is 31,622,400s (1 year), noting that infrequently accessed objects may be evicted from the cache before the defined TTL. * </pre> * * <code>optional int32 max_ttl = 307578001;</code> * * @param value The maxTtl to set. * @return This builder for chaining. */ public Builder setMaxTtl(int value) { bitField0_ |= 0x00000020; maxTtl_ = value; onChanged(); return this; } /** * * * <pre> * Specifies the maximum allowed TTL for cached content served by this origin. Cache directives that attempt to set a max-age or s-maxage higher than this, or an Expires header more than maxTTL seconds in the future will be capped at the value of maxTTL, as if it were the value of an s-maxage Cache-Control directive. Headers sent to the client will not be modified. Setting a TTL of "0" means "always revalidate". The maximum allowed value is 31,622,400s (1 year), noting that infrequently accessed objects may be evicted from the cache before the defined TTL. * </pre> * * <code>optional int32 max_ttl = 307578001;</code> * * @return This builder for chaining. */ public Builder clearMaxTtl() { bitField0_ = (bitField0_ & ~0x00000020); maxTtl_ = 0; onChanged(); return this; } private boolean negativeCaching_; /** * * * <pre> * Negative caching allows per-status code TTLs to be set, in order to apply fine-grained caching for common errors or redirects. This can reduce the load on your origin and improve end-user experience by reducing response latency. When the cache mode is set to CACHE_ALL_STATIC or USE_ORIGIN_HEADERS, negative caching applies to responses with the specified response code that lack any Cache-Control, Expires, or Pragma: no-cache directives. When the cache mode is set to FORCE_CACHE_ALL, negative caching applies to all responses with the specified response code, and override any caching headers. By default, Cloud CDN will apply the following default TTLs to these status codes: HTTP 300 (Multiple Choice), 301, 308 (Permanent Redirects): 10m HTTP 404 (Not Found), 410 (Gone), 451 (Unavailable For Legal Reasons): 120s HTTP 405 (Method Not Found), 421 (Misdirected Request), 501 (Not Implemented): 60s. These defaults can be overridden in negative_caching_policy. * </pre> * * <code>optional bool negative_caching = 336110005;</code> * * @return Whether the negativeCaching field is set. */ @java.lang.Override public boolean hasNegativeCaching() { return ((bitField0_ & 0x00000040) != 0); } /** * * * <pre> * Negative caching allows per-status code TTLs to be set, in order to apply fine-grained caching for common errors or redirects. This can reduce the load on your origin and improve end-user experience by reducing response latency. When the cache mode is set to CACHE_ALL_STATIC or USE_ORIGIN_HEADERS, negative caching applies to responses with the specified response code that lack any Cache-Control, Expires, or Pragma: no-cache directives. When the cache mode is set to FORCE_CACHE_ALL, negative caching applies to all responses with the specified response code, and override any caching headers. By default, Cloud CDN will apply the following default TTLs to these status codes: HTTP 300 (Multiple Choice), 301, 308 (Permanent Redirects): 10m HTTP 404 (Not Found), 410 (Gone), 451 (Unavailable For Legal Reasons): 120s HTTP 405 (Method Not Found), 421 (Misdirected Request), 501 (Not Implemented): 60s. These defaults can be overridden in negative_caching_policy. * </pre> * * <code>optional bool negative_caching = 336110005;</code> * * @return The negativeCaching. */ @java.lang.Override public boolean getNegativeCaching() { return negativeCaching_; } /** * * * <pre> * Negative caching allows per-status code TTLs to be set, in order to apply fine-grained caching for common errors or redirects. This can reduce the load on your origin and improve end-user experience by reducing response latency. When the cache mode is set to CACHE_ALL_STATIC or USE_ORIGIN_HEADERS, negative caching applies to responses with the specified response code that lack any Cache-Control, Expires, or Pragma: no-cache directives. When the cache mode is set to FORCE_CACHE_ALL, negative caching applies to all responses with the specified response code, and override any caching headers. By default, Cloud CDN will apply the following default TTLs to these status codes: HTTP 300 (Multiple Choice), 301, 308 (Permanent Redirects): 10m HTTP 404 (Not Found), 410 (Gone), 451 (Unavailable For Legal Reasons): 120s HTTP 405 (Method Not Found), 421 (Misdirected Request), 501 (Not Implemented): 60s. These defaults can be overridden in negative_caching_policy. * </pre> * * <code>optional bool negative_caching = 336110005;</code> * * @param value The negativeCaching to set. * @return This builder for chaining. */ public Builder setNegativeCaching(boolean value) { bitField0_ |= 0x00000040; negativeCaching_ = value; onChanged(); return this; } /** * * * <pre> * Negative caching allows per-status code TTLs to be set, in order to apply fine-grained caching for common errors or redirects. This can reduce the load on your origin and improve end-user experience by reducing response latency. When the cache mode is set to CACHE_ALL_STATIC or USE_ORIGIN_HEADERS, negative caching applies to responses with the specified response code that lack any Cache-Control, Expires, or Pragma: no-cache directives. When the cache mode is set to FORCE_CACHE_ALL, negative caching applies to all responses with the specified response code, and override any caching headers. By default, Cloud CDN will apply the following default TTLs to these status codes: HTTP 300 (Multiple Choice), 301, 308 (Permanent Redirects): 10m HTTP 404 (Not Found), 410 (Gone), 451 (Unavailable For Legal Reasons): 120s HTTP 405 (Method Not Found), 421 (Misdirected Request), 501 (Not Implemented): 60s. These defaults can be overridden in negative_caching_policy. * </pre> * * <code>optional bool negative_caching = 336110005;</code> * * @return This builder for chaining. */ public Builder clearNegativeCaching() { bitField0_ = (bitField0_ & ~0x00000040); negativeCaching_ = false; onChanged(); return this; } private java.util.List<com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy> negativeCachingPolicy_ = java.util.Collections.emptyList(); private void ensureNegativeCachingPolicyIsMutable() { if (!((bitField0_ & 0x00000080) != 0)) { negativeCachingPolicy_ = new java.util.ArrayList< com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy>( negativeCachingPolicy_); bitField0_ |= 0x00000080; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy, com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy.Builder, com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicyOrBuilder> negativeCachingPolicyBuilder_; /** * * * <pre> * Sets a cache TTL for the specified HTTP status code. negative_caching must be enabled to configure negative_caching_policy. Omitting the policy and leaving negative_caching enabled will use Cloud CDN's default cache TTLs. Note that when specifying an explicit negative_caching_policy, you should take care to specify a cache TTL for all response codes that you wish to cache. Cloud CDN will not apply any default negative caching when a policy exists. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy negative_caching_policy = 155359996; * </code> */ public java.util.List<com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy> getNegativeCachingPolicyList() { if (negativeCachingPolicyBuilder_ == null) { return java.util.Collections.unmodifiableList(negativeCachingPolicy_); } else { return negativeCachingPolicyBuilder_.getMessageList(); } } /** * * * <pre> * Sets a cache TTL for the specified HTTP status code. negative_caching must be enabled to configure negative_caching_policy. Omitting the policy and leaving negative_caching enabled will use Cloud CDN's default cache TTLs. Note that when specifying an explicit negative_caching_policy, you should take care to specify a cache TTL for all response codes that you wish to cache. Cloud CDN will not apply any default negative caching when a policy exists. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy negative_caching_policy = 155359996; * </code> */ public int getNegativeCachingPolicyCount() { if (negativeCachingPolicyBuilder_ == null) { return negativeCachingPolicy_.size(); } else { return negativeCachingPolicyBuilder_.getCount(); } } /** * * * <pre> * Sets a cache TTL for the specified HTTP status code. negative_caching must be enabled to configure negative_caching_policy. Omitting the policy and leaving negative_caching enabled will use Cloud CDN's default cache TTLs. Note that when specifying an explicit negative_caching_policy, you should take care to specify a cache TTL for all response codes that you wish to cache. Cloud CDN will not apply any default negative caching when a policy exists. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy negative_caching_policy = 155359996; * </code> */ public com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy getNegativeCachingPolicy(int index) { if (negativeCachingPolicyBuilder_ == null) { return negativeCachingPolicy_.get(index); } else { return negativeCachingPolicyBuilder_.getMessage(index); } } /** * * * <pre> * Sets a cache TTL for the specified HTTP status code. negative_caching must be enabled to configure negative_caching_policy. Omitting the policy and leaving negative_caching enabled will use Cloud CDN's default cache TTLs. Note that when specifying an explicit negative_caching_policy, you should take care to specify a cache TTL for all response codes that you wish to cache. Cloud CDN will not apply any default negative caching when a policy exists. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy negative_caching_policy = 155359996; * </code> */ public Builder setNegativeCachingPolicy( int index, com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy value) { if (negativeCachingPolicyBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureNegativeCachingPolicyIsMutable(); negativeCachingPolicy_.set(index, value); onChanged(); } else { negativeCachingPolicyBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * Sets a cache TTL for the specified HTTP status code. negative_caching must be enabled to configure negative_caching_policy. Omitting the policy and leaving negative_caching enabled will use Cloud CDN's default cache TTLs. Note that when specifying an explicit negative_caching_policy, you should take care to specify a cache TTL for all response codes that you wish to cache. Cloud CDN will not apply any default negative caching when a policy exists. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy negative_caching_policy = 155359996; * </code> */ public Builder setNegativeCachingPolicy( int index, com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy.Builder builderForValue) { if (negativeCachingPolicyBuilder_ == null) { ensureNegativeCachingPolicyIsMutable(); negativeCachingPolicy_.set(index, builderForValue.build()); onChanged(); } else { negativeCachingPolicyBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Sets a cache TTL for the specified HTTP status code. negative_caching must be enabled to configure negative_caching_policy. Omitting the policy and leaving negative_caching enabled will use Cloud CDN's default cache TTLs. Note that when specifying an explicit negative_caching_policy, you should take care to specify a cache TTL for all response codes that you wish to cache. Cloud CDN will not apply any default negative caching when a policy exists. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy negative_caching_policy = 155359996; * </code> */ public Builder addNegativeCachingPolicy( com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy value) { if (negativeCachingPolicyBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureNegativeCachingPolicyIsMutable(); negativeCachingPolicy_.add(value); onChanged(); } else { negativeCachingPolicyBuilder_.addMessage(value); } return this; } /** * * * <pre> * Sets a cache TTL for the specified HTTP status code. negative_caching must be enabled to configure negative_caching_policy. Omitting the policy and leaving negative_caching enabled will use Cloud CDN's default cache TTLs. Note that when specifying an explicit negative_caching_policy, you should take care to specify a cache TTL for all response codes that you wish to cache. Cloud CDN will not apply any default negative caching when a policy exists. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy negative_caching_policy = 155359996; * </code> */ public Builder addNegativeCachingPolicy( int index, com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy value) { if (negativeCachingPolicyBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureNegativeCachingPolicyIsMutable(); negativeCachingPolicy_.add(index, value); onChanged(); } else { negativeCachingPolicyBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * Sets a cache TTL for the specified HTTP status code. negative_caching must be enabled to configure negative_caching_policy. Omitting the policy and leaving negative_caching enabled will use Cloud CDN's default cache TTLs. Note that when specifying an explicit negative_caching_policy, you should take care to specify a cache TTL for all response codes that you wish to cache. Cloud CDN will not apply any default negative caching when a policy exists. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy negative_caching_policy = 155359996; * </code> */ public Builder addNegativeCachingPolicy( com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy.Builder builderForValue) { if (negativeCachingPolicyBuilder_ == null) { ensureNegativeCachingPolicyIsMutable(); negativeCachingPolicy_.add(builderForValue.build()); onChanged(); } else { negativeCachingPolicyBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * Sets a cache TTL for the specified HTTP status code. negative_caching must be enabled to configure negative_caching_policy. Omitting the policy and leaving negative_caching enabled will use Cloud CDN's default cache TTLs. Note that when specifying an explicit negative_caching_policy, you should take care to specify a cache TTL for all response codes that you wish to cache. Cloud CDN will not apply any default negative caching when a policy exists. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy negative_caching_policy = 155359996; * </code> */ public Builder addNegativeCachingPolicy( int index, com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy.Builder builderForValue) { if (negativeCachingPolicyBuilder_ == null) { ensureNegativeCachingPolicyIsMutable(); negativeCachingPolicy_.add(index, builderForValue.build()); onChanged(); } else { negativeCachingPolicyBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Sets a cache TTL for the specified HTTP status code. negative_caching must be enabled to configure negative_caching_policy. Omitting the policy and leaving negative_caching enabled will use Cloud CDN's default cache TTLs. Note that when specifying an explicit negative_caching_policy, you should take care to specify a cache TTL for all response codes that you wish to cache. Cloud CDN will not apply any default negative caching when a policy exists. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy negative_caching_policy = 155359996; * </code> */ public Builder addAllNegativeCachingPolicy( java.lang.Iterable< ? extends com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy> values) { if (negativeCachingPolicyBuilder_ == null) { ensureNegativeCachingPolicyIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, negativeCachingPolicy_); onChanged(); } else { negativeCachingPolicyBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * Sets a cache TTL for the specified HTTP status code. negative_caching must be enabled to configure negative_caching_policy. Omitting the policy and leaving negative_caching enabled will use Cloud CDN's default cache TTLs. Note that when specifying an explicit negative_caching_policy, you should take care to specify a cache TTL for all response codes that you wish to cache. Cloud CDN will not apply any default negative caching when a policy exists. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy negative_caching_policy = 155359996; * </code> */ public Builder clearNegativeCachingPolicy() { if (negativeCachingPolicyBuilder_ == null) { negativeCachingPolicy_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000080); onChanged(); } else { negativeCachingPolicyBuilder_.clear(); } return this; } /** * * * <pre> * Sets a cache TTL for the specified HTTP status code. negative_caching must be enabled to configure negative_caching_policy. Omitting the policy and leaving negative_caching enabled will use Cloud CDN's default cache TTLs. Note that when specifying an explicit negative_caching_policy, you should take care to specify a cache TTL for all response codes that you wish to cache. Cloud CDN will not apply any default negative caching when a policy exists. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy negative_caching_policy = 155359996; * </code> */ public Builder removeNegativeCachingPolicy(int index) { if (negativeCachingPolicyBuilder_ == null) { ensureNegativeCachingPolicyIsMutable(); negativeCachingPolicy_.remove(index); onChanged(); } else { negativeCachingPolicyBuilder_.remove(index); } return this; } /** * * * <pre> * Sets a cache TTL for the specified HTTP status code. negative_caching must be enabled to configure negative_caching_policy. Omitting the policy and leaving negative_caching enabled will use Cloud CDN's default cache TTLs. Note that when specifying an explicit negative_caching_policy, you should take care to specify a cache TTL for all response codes that you wish to cache. Cloud CDN will not apply any default negative caching when a policy exists. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy negative_caching_policy = 155359996; * </code> */ public com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy.Builder getNegativeCachingPolicyBuilder(int index) { return getNegativeCachingPolicyFieldBuilder().getBuilder(index); } /** * * * <pre> * Sets a cache TTL for the specified HTTP status code. negative_caching must be enabled to configure negative_caching_policy. Omitting the policy and leaving negative_caching enabled will use Cloud CDN's default cache TTLs. Note that when specifying an explicit negative_caching_policy, you should take care to specify a cache TTL for all response codes that you wish to cache. Cloud CDN will not apply any default negative caching when a policy exists. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy negative_caching_policy = 155359996; * </code> */ public com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicyOrBuilder getNegativeCachingPolicyOrBuilder(int index) { if (negativeCachingPolicyBuilder_ == null) { return negativeCachingPolicy_.get(index); } else { return negativeCachingPolicyBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * Sets a cache TTL for the specified HTTP status code. negative_caching must be enabled to configure negative_caching_policy. Omitting the policy and leaving negative_caching enabled will use Cloud CDN's default cache TTLs. Note that when specifying an explicit negative_caching_policy, you should take care to specify a cache TTL for all response codes that you wish to cache. Cloud CDN will not apply any default negative caching when a policy exists. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy negative_caching_policy = 155359996; * </code> */ public java.util.List< ? extends com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicyOrBuilder> getNegativeCachingPolicyOrBuilderList() { if (negativeCachingPolicyBuilder_ != null) { return negativeCachingPolicyBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(negativeCachingPolicy_); } } /** * * * <pre> * Sets a cache TTL for the specified HTTP status code. negative_caching must be enabled to configure negative_caching_policy. Omitting the policy and leaving negative_caching enabled will use Cloud CDN's default cache TTLs. Note that when specifying an explicit negative_caching_policy, you should take care to specify a cache TTL for all response codes that you wish to cache. Cloud CDN will not apply any default negative caching when a policy exists. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy negative_caching_policy = 155359996; * </code> */ public com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy.Builder addNegativeCachingPolicyBuilder() { return getNegativeCachingPolicyFieldBuilder() .addBuilder( com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy .getDefaultInstance()); } /** * * * <pre> * Sets a cache TTL for the specified HTTP status code. negative_caching must be enabled to configure negative_caching_policy. Omitting the policy and leaving negative_caching enabled will use Cloud CDN's default cache TTLs. Note that when specifying an explicit negative_caching_policy, you should take care to specify a cache TTL for all response codes that you wish to cache. Cloud CDN will not apply any default negative caching when a policy exists. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy negative_caching_policy = 155359996; * </code> */ public com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy.Builder addNegativeCachingPolicyBuilder(int index) { return getNegativeCachingPolicyFieldBuilder() .addBuilder( index, com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy .getDefaultInstance()); } /** * * * <pre> * Sets a cache TTL for the specified HTTP status code. negative_caching must be enabled to configure negative_caching_policy. Omitting the policy and leaving negative_caching enabled will use Cloud CDN's default cache TTLs. Note that when specifying an explicit negative_caching_policy, you should take care to specify a cache TTL for all response codes that you wish to cache. Cloud CDN will not apply any default negative caching when a policy exists. * </pre> * * <code> * repeated .google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy negative_caching_policy = 155359996; * </code> */ public java.util.List< com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy.Builder> getNegativeCachingPolicyBuilderList() { return getNegativeCachingPolicyFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy, com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy.Builder, com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicyOrBuilder> getNegativeCachingPolicyFieldBuilder() { if (negativeCachingPolicyBuilder_ == null) { negativeCachingPolicyBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy, com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicy.Builder, com.google.cloud.compute.v1.BackendServiceCdnPolicyNegativeCachingPolicyOrBuilder>( negativeCachingPolicy_, ((bitField0_ & 0x00000080) != 0), getParentForChildren(), isClean()); negativeCachingPolicy_ = null; } return negativeCachingPolicyBuilder_; } private boolean requestCoalescing_; /** * * * <pre> * If true then Cloud CDN will combine multiple concurrent cache fill requests into a small number of requests to the origin. * </pre> * * <code>optional bool request_coalescing = 532808276;</code> * * @return Whether the requestCoalescing field is set. */ @java.lang.Override public boolean hasRequestCoalescing() { return ((bitField0_ & 0x00000100) != 0); } /** * * * <pre> * If true then Cloud CDN will combine multiple concurrent cache fill requests into a small number of requests to the origin. * </pre> * * <code>optional bool request_coalescing = 532808276;</code> * * @return The requestCoalescing. */ @java.lang.Override public boolean getRequestCoalescing() { return requestCoalescing_; } /** * * * <pre> * If true then Cloud CDN will combine multiple concurrent cache fill requests into a small number of requests to the origin. * </pre> * * <code>optional bool request_coalescing = 532808276;</code> * * @param value The requestCoalescing to set. * @return This builder for chaining. */ public Builder setRequestCoalescing(boolean value) { bitField0_ |= 0x00000100; requestCoalescing_ = value; onChanged(); return this; } /** * * * <pre> * If true then Cloud CDN will combine multiple concurrent cache fill requests into a small number of requests to the origin. * </pre> * * <code>optional bool request_coalescing = 532808276;</code> * * @return This builder for chaining. */ public Builder clearRequestCoalescing() { bitField0_ = (bitField0_ & ~0x00000100); requestCoalescing_ = false; onChanged(); return this; } private int serveWhileStale_; /** * * * <pre> * Serve existing content from the cache (if available) when revalidating content with the origin, or when an error is encountered when refreshing the cache. This setting defines the default "max-stale" duration for any cached responses that do not specify a max-stale directive. Stale responses that exceed the TTL configured here will not be served. The default limit (max-stale) is 86400s (1 day), which will allow stale content to be served up to this limit beyond the max-age (or s-max-age) of a cached response. The maximum allowed value is 604800 (1 week). Set this to zero (0) to disable serve-while-stale. * </pre> * * <code>optional int32 serve_while_stale = 236682203;</code> * * @return Whether the serveWhileStale field is set. */ @java.lang.Override public boolean hasServeWhileStale() { return ((bitField0_ & 0x00000200) != 0); } /** * * * <pre> * Serve existing content from the cache (if available) when revalidating content with the origin, or when an error is encountered when refreshing the cache. This setting defines the default "max-stale" duration for any cached responses that do not specify a max-stale directive. Stale responses that exceed the TTL configured here will not be served. The default limit (max-stale) is 86400s (1 day), which will allow stale content to be served up to this limit beyond the max-age (or s-max-age) of a cached response. The maximum allowed value is 604800 (1 week). Set this to zero (0) to disable serve-while-stale. * </pre> * * <code>optional int32 serve_while_stale = 236682203;</code> * * @return The serveWhileStale. */ @java.lang.Override public int getServeWhileStale() { return serveWhileStale_; } /** * * * <pre> * Serve existing content from the cache (if available) when revalidating content with the origin, or when an error is encountered when refreshing the cache. This setting defines the default "max-stale" duration for any cached responses that do not specify a max-stale directive. Stale responses that exceed the TTL configured here will not be served. The default limit (max-stale) is 86400s (1 day), which will allow stale content to be served up to this limit beyond the max-age (or s-max-age) of a cached response. The maximum allowed value is 604800 (1 week). Set this to zero (0) to disable serve-while-stale. * </pre> * * <code>optional int32 serve_while_stale = 236682203;</code> * * @param value The serveWhileStale to set. * @return This builder for chaining. */ public Builder setServeWhileStale(int value) { bitField0_ |= 0x00000200; serveWhileStale_ = value; onChanged(); return this; } /** * * * <pre> * Serve existing content from the cache (if available) when revalidating content with the origin, or when an error is encountered when refreshing the cache. This setting defines the default "max-stale" duration for any cached responses that do not specify a max-stale directive. Stale responses that exceed the TTL configured here will not be served. The default limit (max-stale) is 86400s (1 day), which will allow stale content to be served up to this limit beyond the max-age (or s-max-age) of a cached response. The maximum allowed value is 604800 (1 week). Set this to zero (0) to disable serve-while-stale. * </pre> * * <code>optional int32 serve_while_stale = 236682203;</code> * * @return This builder for chaining. */ public Builder clearServeWhileStale() { bitField0_ = (bitField0_ & ~0x00000200); serveWhileStale_ = 0; onChanged(); return this; } private long signedUrlCacheMaxAgeSec_; /** * * * <pre> * Maximum number of seconds the response to a signed URL request will be considered fresh. After this time period, the response will be revalidated before being served. Defaults to 1hr (3600s). When serving responses to signed URL requests, Cloud CDN will internally behave as though all responses from this backend had a "Cache-Control: public, max-age=[TTL]" header, regardless of any existing Cache-Control header. The actual headers served in responses will not be altered. * </pre> * * <code>optional int64 signed_url_cache_max_age_sec = 269374534;</code> * * @return Whether the signedUrlCacheMaxAgeSec field is set. */ @java.lang.Override public boolean hasSignedUrlCacheMaxAgeSec() { return ((bitField0_ & 0x00000400) != 0); } /** * * * <pre> * Maximum number of seconds the response to a signed URL request will be considered fresh. After this time period, the response will be revalidated before being served. Defaults to 1hr (3600s). When serving responses to signed URL requests, Cloud CDN will internally behave as though all responses from this backend had a "Cache-Control: public, max-age=[TTL]" header, regardless of any existing Cache-Control header. The actual headers served in responses will not be altered. * </pre> * * <code>optional int64 signed_url_cache_max_age_sec = 269374534;</code> * * @return The signedUrlCacheMaxAgeSec. */ @java.lang.Override public long getSignedUrlCacheMaxAgeSec() { return signedUrlCacheMaxAgeSec_; } /** * * * <pre> * Maximum number of seconds the response to a signed URL request will be considered fresh. After this time period, the response will be revalidated before being served. Defaults to 1hr (3600s). When serving responses to signed URL requests, Cloud CDN will internally behave as though all responses from this backend had a "Cache-Control: public, max-age=[TTL]" header, regardless of any existing Cache-Control header. The actual headers served in responses will not be altered. * </pre> * * <code>optional int64 signed_url_cache_max_age_sec = 269374534;</code> * * @param value The signedUrlCacheMaxAgeSec to set. * @return This builder for chaining. */ public Builder setSignedUrlCacheMaxAgeSec(long value) { bitField0_ |= 0x00000400; signedUrlCacheMaxAgeSec_ = value; onChanged(); return this; } /** * * * <pre> * Maximum number of seconds the response to a signed URL request will be considered fresh. After this time period, the response will be revalidated before being served. Defaults to 1hr (3600s). When serving responses to signed URL requests, Cloud CDN will internally behave as though all responses from this backend had a "Cache-Control: public, max-age=[TTL]" header, regardless of any existing Cache-Control header. The actual headers served in responses will not be altered. * </pre> * * <code>optional int64 signed_url_cache_max_age_sec = 269374534;</code> * * @return This builder for chaining. */ public Builder clearSignedUrlCacheMaxAgeSec() { bitField0_ = (bitField0_ & ~0x00000400); signedUrlCacheMaxAgeSec_ = 0L; onChanged(); return this; } private com.google.protobuf.LazyStringList signedUrlKeyNames_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureSignedUrlKeyNamesIsMutable() { if (!((bitField0_ & 0x00000800) != 0)) { signedUrlKeyNames_ = new com.google.protobuf.LazyStringArrayList(signedUrlKeyNames_); bitField0_ |= 0x00000800; } } /** * * * <pre> * [Output Only] Names of the keys for signing request URLs. * </pre> * * <code>repeated string signed_url_key_names = 371848885;</code> * * @return A list containing the signedUrlKeyNames. */ public com.google.protobuf.ProtocolStringList getSignedUrlKeyNamesList() { return signedUrlKeyNames_.getUnmodifiableView(); } /** * * * <pre> * [Output Only] Names of the keys for signing request URLs. * </pre> * * <code>repeated string signed_url_key_names = 371848885;</code> * * @return The count of signedUrlKeyNames. */ public int getSignedUrlKeyNamesCount() { return signedUrlKeyNames_.size(); } /** * * * <pre> * [Output Only] Names of the keys for signing request URLs. * </pre> * * <code>repeated string signed_url_key_names = 371848885;</code> * * @param index The index of the element to return. * @return The signedUrlKeyNames at the given index. */ public java.lang.String getSignedUrlKeyNames(int index) { return signedUrlKeyNames_.get(index); } /** * * * <pre> * [Output Only] Names of the keys for signing request URLs. * </pre> * * <code>repeated string signed_url_key_names = 371848885;</code> * * @param index The index of the value to return. * @return The bytes of the signedUrlKeyNames at the given index. */ public com.google.protobuf.ByteString getSignedUrlKeyNamesBytes(int index) { return signedUrlKeyNames_.getByteString(index); } /** * * * <pre> * [Output Only] Names of the keys for signing request URLs. * </pre> * * <code>repeated string signed_url_key_names = 371848885;</code> * * @param index The index to set the value at. * @param value The signedUrlKeyNames to set. * @return This builder for chaining. */ public Builder setSignedUrlKeyNames(int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureSignedUrlKeyNamesIsMutable(); signedUrlKeyNames_.set(index, value); onChanged(); return this; } /** * * * <pre> * [Output Only] Names of the keys for signing request URLs. * </pre> * * <code>repeated string signed_url_key_names = 371848885;</code> * * @param value The signedUrlKeyNames to add. * @return This builder for chaining. */ public Builder addSignedUrlKeyNames(java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureSignedUrlKeyNamesIsMutable(); signedUrlKeyNames_.add(value); onChanged(); return this; } /** * * * <pre> * [Output Only] Names of the keys for signing request URLs. * </pre> * * <code>repeated string signed_url_key_names = 371848885;</code> * * @param values The signedUrlKeyNames to add. * @return This builder for chaining. */ public Builder addAllSignedUrlKeyNames(java.lang.Iterable<java.lang.String> values) { ensureSignedUrlKeyNamesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, signedUrlKeyNames_); onChanged(); return this; } /** * * * <pre> * [Output Only] Names of the keys for signing request URLs. * </pre> * * <code>repeated string signed_url_key_names = 371848885;</code> * * @return This builder for chaining. */ public Builder clearSignedUrlKeyNames() { signedUrlKeyNames_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000800); onChanged(); return this; } /** * * * <pre> * [Output Only] Names of the keys for signing request URLs. * </pre> * * <code>repeated string signed_url_key_names = 371848885;</code> * * @param value The bytes of the signedUrlKeyNames to add. * @return This builder for chaining. */ public Builder addSignedUrlKeyNamesBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureSignedUrlKeyNamesIsMutable(); signedUrlKeyNames_.add(value); onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.compute.v1.BackendServiceCdnPolicy) } // @@protoc_insertion_point(class_scope:google.cloud.compute.v1.BackendServiceCdnPolicy) private static final com.google.cloud.compute.v1.BackendServiceCdnPolicy DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.compute.v1.BackendServiceCdnPolicy(); } public static com.google.cloud.compute.v1.BackendServiceCdnPolicy getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<BackendServiceCdnPolicy> PARSER = new com.google.protobuf.AbstractParser<BackendServiceCdnPolicy>() { @java.lang.Override public BackendServiceCdnPolicy parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new BackendServiceCdnPolicy(input, extensionRegistry); } }; public static com.google.protobuf.Parser<BackendServiceCdnPolicy> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<BackendServiceCdnPolicy> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.compute.v1.BackendServiceCdnPolicy getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache-2.0
Shenker93/playframework
documentation/manual/working/javaGuide/main/http/code/javaguide/http/routing/controllers/Api.java
511
/* * Copyright (C) 2009-2018 Lightbend Inc. <https://www.lightbend.com> */ package javaguide.http.routing.controllers; import java.util.Optional; import play.mvc.Controller; import play.mvc.Result; public class Api extends Controller { public Result list(String version) { return ok("version " + version); } public Result listOpt(Optional<String> version) { return ok("version " + version.orElse("unknown")); } public Result newThing() { return ok(); } }
apache-2.0
QualiMaster/Infrastructure
AdaptationLayer/src/eu/qualimaster/adaptation/internal/IAdaptationLogger.java
3887
/* * Copyright 2009-2016 University of Hildesheim, Software Systems Engineering * * 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 eu.qualimaster.adaptation.internal; import eu.qualimaster.adaptation.events.AdaptationEvent; import eu.qualimaster.coordination.commands.CoordinationCommand; import eu.qualimaster.coordination.events.CoordinationCommandExecutionEvent; import eu.qualimaster.monitoring.events.FrozenSystemState; /** * Defines the interface for logging the adaptation activities (for reflective adaptation). Passed in instances * must not be modified! * * @author Holger Eichelberger */ public interface IAdaptationLogger { /** * Starts the adaptation for a given <code>event</code> and <code>state</code>. * * @param event the causing adaptation event * @param state the actual (frozen) system state * @see #endAdaptation() */ public void startAdaptation(AdaptationEvent event, FrozenSystemState state); /** * Notifies the logger that a strategy has been executed. * * @param name the name of the strategy * @param successful <code>true</code> for successful execution (if this is a non-nested strategy, * the changes will be enacted), <code>false</code> else */ public void executedStrategy(String name, boolean successful); /** * Notifies the logger that a tactic has been executed. * * @param name the name of the tactic * @param successful <code>true</code> for successful execution (if the calling strategy does not object, * the changes will be enacted), <code>false</code> else */ public void executedTactic(String name, boolean successful); /** * Notifies the logger that a coordination command is being executed as part of the enactment. Please note that * this does not mean that the command has been (completely) executed, just that it is scheduled for execution. * * @param command the coordination command * @see #enacted(CoordinationCommand, CoordinationCommandExecutionEvent) */ public void enacting(CoordinationCommand command); /** * Ends the adaptation started with {@link #startAdaptation(AdaptationEvent, FrozenSystemState)}. * * @param successful <code>true</code> for successful execution */ public void endAdaptation(boolean successful); /** * Called when an execution command actually has been processed. Please note that this method may be called after * {@link #endAdaptation(boolean)} as the commands are executed asynchronously. You may correlate the command/event * id of {@link #enacting(CoordinationCommand)}, the adaptation execution and the actual enactment indicated by * this method. * * @param command the command (may be <b>null</b> if the execution took too long and the relation between * <code>command</code> and <code>event</code> is already deleted). * @param event the execution event indicating the execution status and also the id of the command that has been * executed */ public void enacted(CoordinationCommand command, CoordinationCommandExecutionEvent event); /** * Closes the log. */ public void close(); }
apache-2.0
fSergio101/orchextra-android-sdk
orchextrasdk/src/main/java/com/gigigo/orchextra/sdk/features/BeaconFeature.java
1274
/* * Created by Orchextra * * Copyright (C) 2016 Gigigo Mobile Services SL * * 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.gigigo.orchextra.sdk.features; import com.gigigo.orchextra.domain.abstractions.beacons.BluetoothStatus; import com.gigigo.orchextra.domain.initalization.features.Feature; import com.gigigo.orchextra.domain.abstractions.initialization.features.FeatureType; import com.gigigo.orchextra.domain.model.StringValueEnum; public class BeaconFeature extends Feature { public BeaconFeature(StringValueEnum status) { super(FeatureType.BEACONS, status); } @Override public boolean isSuccess() { return !(getStatus() == BluetoothStatus.NO_BLTE_SUPPORTED || getStatus() == BluetoothStatus.NO_PERMISSIONS); } }
apache-2.0
jyotisingh/gocd
server/src/main/java/com/thoughtworks/go/server/newsecurity/controllers/AuthenticationController.java
10802
/* * Copyright 2018 ThoughtWorks, 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 com.thoughtworks.go.server.newsecurity.controllers; import com.thoughtworks.go.CurrentGoCDVersion; import com.thoughtworks.go.server.newsecurity.models.AccessToken; import com.thoughtworks.go.server.newsecurity.models.AuthenticationToken; import com.thoughtworks.go.server.newsecurity.models.UsernamePassword; import com.thoughtworks.go.server.newsecurity.providers.PasswordBasedPluginAuthenticationProvider; import com.thoughtworks.go.server.newsecurity.providers.WebBasedPluginAuthenticationProvider; import com.thoughtworks.go.server.newsecurity.utils.SessionUtils; import com.thoughtworks.go.server.service.SecurityAuthConfigService; import com.thoughtworks.go.server.service.SecurityService; import com.thoughtworks.go.server.web.GoVelocityView; import com.thoughtworks.go.util.Clock; import com.thoughtworks.go.util.SystemEnvironment; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.savedrequest.SavedRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.RedirectView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import static com.thoughtworks.go.server.newsecurity.utils.SessionUtils.isAnonymousAuthenticationToken; @Controller public class AuthenticationController { public static final String BAD_CREDENTIALS_MSG = "Invalid credentials. Either your username and password are incorrect, or there is a problem with your browser cookies. Please check with your administrator."; private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationController.class); private static final RedirectView REDIRECT_TO_LOGIN_PAGE = new RedirectView("/auth/login", true); private static final String UNKNOWN_ERROR_WHILE_AUTHENTICATION = "There was an unknown error authenticating you. Please try again after some time, and contact the administrator if the problem persists."; private final SecurityService securityService; private final SecurityAuthConfigService securityAuthConfigService; private final SystemEnvironment systemEnvironment; private final Clock clock; private final PasswordBasedPluginAuthenticationProvider passwordBasedPluginAuthenticationProvider; private final WebBasedPluginAuthenticationProvider webBasedPluginAuthenticationProvider; @Autowired public AuthenticationController(SecurityService securityService, SecurityAuthConfigService securityAuthConfigService, SystemEnvironment systemEnvironment, Clock clock, PasswordBasedPluginAuthenticationProvider passwordBasedPluginAuthenticationProvider, WebBasedPluginAuthenticationProvider webBasedPluginAuthenticationProvider) { this.securityService = securityService; this.securityAuthConfigService = securityAuthConfigService; this.systemEnvironment = systemEnvironment; this.clock = clock; this.passwordBasedPluginAuthenticationProvider = passwordBasedPluginAuthenticationProvider; this.webBasedPluginAuthenticationProvider = webBasedPluginAuthenticationProvider; } @RequestMapping(value = "/auth/security_check", method = RequestMethod.POST) public RedirectView performLogin(@RequestParam("j_username") String username, @RequestParam("j_password") String password, HttpServletRequest request) { if (securityIsDisabledOrAlreadyLoggedIn(request)) { return new RedirectView("/pipelines", true); } LOGGER.debug("Requesting authentication for form auth."); try { SavedRequest savedRequest = SessionUtils.savedRequest(request); final AuthenticationToken<UsernamePassword> authenticationToken = passwordBasedPluginAuthenticationProvider.authenticate(new UsernamePassword(username, password), null); if (authenticationToken == null) { return badAuthentication(request, BAD_CREDENTIALS_MSG); } else { SessionUtils.setAuthenticationTokenAfterRecreatingSession(authenticationToken, request); } String redirectUrl = savedRequest == null ? "/go/pipelines" : savedRequest.getRedirectUrl(); return new RedirectView(redirectUrl, false); } catch (AuthenticationException e) { LOGGER.error("Failed to authenticate user: {} ", username, e); return badAuthentication(request, e.getMessage()); } catch (Exception e) { return unknownAuthenticationError(request); } } @RequestMapping(value = "/auth/login", method = RequestMethod.GET) public Object renderLoginPage(HttpServletRequest request, HttpServletResponse response) { if (securityIsDisabledOrAlreadyLoggedIn(request)) { return new RedirectView("/pipelines", true); } response.setHeader("Cache-Control", "no-cache, must-revalidate, no-store"); response.setHeader("Pragma", "no-cache"); Map<String, Object> model = new HashMap<>(); model.put("security_auth_config_service", securityAuthConfigService); model.put(GoVelocityView.CURRENT_GOCD_VERSION, CurrentGoCDVersion.getInstance()); return new ModelAndView("auth/login", model); } @RequestMapping(value = "/auth/logout", method = RequestMethod.GET) public RedirectView logout(HttpServletRequest request) { SessionUtils.recreateSessionWithoutCopyingOverSessionState(request); return new RedirectView("/auth/login", true); } @RequestMapping(value = "/plugin/{pluginId}/login", method = RequestMethod.GET) public RedirectView redirectToThirdPartyLoginPage(@PathVariable("pluginId") String pluginId, HttpServletRequest request) { if (securityIsDisabledOrAlreadyLoggedIn(request)) { return new RedirectView("/pipelines", true); } final StringBuffer requestURL = request.getRequestURL(); requestURL.setLength(requestURL.length() - request.getRequestURI().length()); return new RedirectView(webBasedPluginAuthenticationProvider.getAuthorizationServerUrl(pluginId, requestURL.toString()), false); } @RequestMapping(value = "/plugin/{pluginId}/authenticate") public RedirectView authenticateWithWebBasedPlugin(@PathVariable("pluginId") String pluginId, HttpServletRequest request) { if (securityIsDisabledOrAlreadyLoggedIn(request)) { return new RedirectView("/pipelines", true); } LOGGER.debug("Requesting authentication for form auth."); SavedRequest savedRequest = SessionUtils.savedRequest(request); try { final AccessToken accessToken = webBasedPluginAuthenticationProvider.fetchAccessToken(pluginId, getRequestHeaders(request), getParameterMap(request)); AuthenticationToken<AccessToken> authenticationToken = webBasedPluginAuthenticationProvider.authenticate(accessToken, pluginId); if (authenticationToken == null) { return unknownAuthenticationError(request); } SessionUtils.setAuthenticationTokenAfterRecreatingSession(authenticationToken, request); } catch (AuthenticationException e) { LOGGER.error("Failed to authenticate user.", e); return badAuthentication(request, e.getMessage()); } catch (Exception e) { return unknownAuthenticationError(request); } SessionUtils.removeAuthenticationError(request); String redirectUrl = savedRequest == null ? "/go/pipelines" : savedRequest.getRedirectUrl(); return new RedirectView(redirectUrl, false); } private boolean securityIsDisabledOrAlreadyLoggedIn(HttpServletRequest request) { return !securityService.isSecurityEnabled() || (!isAnonymousAuthenticationToken(request) && SessionUtils.isAuthenticated(request, clock, systemEnvironment)); } private RedirectView badAuthentication(HttpServletRequest request, String message) { SessionUtils.setAuthenticationError(message, request); return REDIRECT_TO_LOGIN_PAGE; } private RedirectView unknownAuthenticationError(HttpServletRequest request) { return badAuthentication(request, UNKNOWN_ERROR_WHILE_AUTHENTICATION); } private HashMap<String, String> getRequestHeaders(HttpServletRequest request) { HashMap<String, String> headers = new HashMap<>(); Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String header = (String) headerNames.nextElement(); String value = request.getHeader(header); headers.put(header, value); } return headers; } private Map<String, String> getParameterMap(HttpServletRequest request) { Map<String, String[]> springParameterMap = request.getParameterMap(); Map<String, String> pluginParameterMap = new HashMap<>(); for (String parameterName : springParameterMap.keySet()) { String[] values = springParameterMap.get(parameterName); if (values != null && values.length > 0) { pluginParameterMap.put(parameterName, values[0]); } else { pluginParameterMap.put(parameterName, null); } } return pluginParameterMap; } }
apache-2.0
dalmia/Sunshine-Advanced
app/src/main/java/com/passenger/android/sunshine/app/sync/SunshineSyncAdapter.java
29453
package com.passenger.android.sunshine.app.sync; import android.accounts.Account; import android.accounts.AccountManager; import android.annotation.SuppressLint; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.AbstractThreadedSyncAdapter; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SyncRequest; import android.content.SyncResult; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.annotation.IntDef; import android.support.v4.app.NotificationCompat; import android.support.v4.app.TaskStackBuilder; import android.text.format.Time; import android.util.Log; import com.bumptech.glide.Glide; import com.passenger.android.sunshine.app.BuildConfig; import com.passenger.android.sunshine.app.MainActivity; import com.passenger.android.sunshine.app.R; import com.passenger.android.sunshine.app.Utility; import com.passenger.android.sunshine.app.data.WeatherContract; import com.passenger.android.sunshine.app.muzei.WeatherMuzeiSource; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.net.HttpURLConnection; import java.net.URL; import java.util.Vector; import java.util.concurrent.ExecutionException; public class SunshineSyncAdapter extends AbstractThreadedSyncAdapter { public final String LOG_TAG = SunshineSyncAdapter.class.getSimpleName(); public static final String ACTION_DATA_UPDATED = "com.example.android.sunshine.app.ACTION_DATA_UPDATED"; // Interval at which to sync with the weather, in seconds. // 60 seconds (1 minute) * 180 = 3 hours public static final int SYNC_INTERVAL = 60 * 180; public static final int SYNC_FLEXTIME = SYNC_INTERVAL / 3; private static final long DAY_IN_MILLIS = 1000 * 60 * 60 * 24; private static final int WEATHER_NOTIFICATION_ID = 3004; private static final String[] NOTIFY_WEATHER_PROJECTION = new String[]{ WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, WeatherContract.WeatherEntry.COLUMN_MIN_TEMP, WeatherContract.WeatherEntry.COLUMN_SHORT_DESC }; // these indices must match the projection private static final int INDEX_WEATHER_ID = 0; private static final int INDEX_MAX_TEMP = 1; private static final int INDEX_MIN_TEMP = 2; private static final int INDEX_SHORT_DESC = 3; //Annotations to notify the user correctly in case //there is a problem with the server. @Retention(RetentionPolicy.SOURCE) @IntDef({LOCATION_STATUS_OK, LOCATION_STATUS_SERVER_DOWN, LOCATION_STATUS_SERVER_INVALID, LOCATION_STATUS_UNKNOWN, LOCATION_STATUS_INVALID}) public @interface LocationStatus { } public static final int LOCATION_STATUS_OK = 0; public static final int LOCATION_STATUS_SERVER_DOWN = 1; public static final int LOCATION_STATUS_SERVER_INVALID = 2; public static final int LOCATION_STATUS_UNKNOWN = 3; public static final int LOCATION_STATUS_INVALID = 4; public SunshineSyncAdapter(Context context, boolean autoInitialize) { super(context, autoInitialize); } @Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { Log.d(LOG_TAG, "Starting sync"); String locationQuery = Utility.getPreferredLocation(getContext()); // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String forecastJsonStr = null; String format = "json"; String units = "metric"; int numDays = 14; try { // Construct the URL for the OpenWeatherMap query // Possible parameters are avaiable at OWM's forecast API page, at // http://openweathermap.org/API#forecast final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?"; final String QUERY_PARAM = "q"; final String FORMAT_PARAM = "mode"; final String LAT_PARAM = "lat"; final String LON_PARAM = "lon"; final String UNITS_PARAM = "units"; final String DAYS_PARAM = "cnt"; final String APPID_PARAM = "APPID"; Uri.Builder builder = Uri.parse(FORECAST_BASE_URL).buildUpon(); if (Utility.isLocationLatLonAvailable(getContext())) { builder.appendQueryParameter(LAT_PARAM, String.valueOf(Utility.getLocationLatitude(getContext()))) .appendQueryParameter(LON_PARAM, String.valueOf(Utility.getLocationLongitude(getContext()))); } else { builder.appendQueryParameter(QUERY_PARAM, locationQuery); } Uri builtUri = builder.appendQueryParameter(FORMAT_PARAM, format) .appendQueryParameter(UNITS_PARAM, units) .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)) .appendQueryParameter(APPID_PARAM, BuildConfig.OPEN_WEATHER_MAP_API_KEY) .build(); URL url = new URL(builtUri.toString()); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. return; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { setLocationStatus(getContext(), LOCATION_STATUS_SERVER_DOWN); return; } forecastJsonStr = buffer.toString(); getWeatherDataFromJson(forecastJsonStr, locationQuery); } catch (IOException e) { Log.e(LOG_TAG, "Error ", e); setLocationStatus(getContext(), LOCATION_STATUS_SERVER_DOWN); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); setLocationStatus(getContext(), LOCATION_STATUS_SERVER_INVALID); e.printStackTrace(); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(LOG_TAG, "Error closing stream", e); } } } return; } /** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * <p/> * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us. */ private void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException { // Now we have a String representing the complete forecast in JSON Format. // Fortunately parsing is easy: constructor takes the JSON string and converts it // into an Object hierarchy for us. // These are the names of the JSON objects that need to be extracted. // Location information final String OWM_CITY = "city"; final String OWM_CITY_NAME = "name"; final String OWM_COORD = "coord"; // Location coordinate final String OWM_LATITUDE = "lat"; final String OWM_LONGITUDE = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_PRESSURE = "pressure"; final String OWM_HUMIDITY = "humidity"; final String OWM_WINDSPEED = "speed"; final String OWM_WIND_DIRECTION = "deg"; // All temperatures are children of the "temp" object. final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_WEATHER = "weather"; final String OWM_DESCRIPTION = "main"; final String OWM_WEATHER_ID = "id"; final String OWM_MESSAGE_CODE = "code"; try { JSONObject forecastJson = new JSONObject(forecastJsonStr); if (forecastJson.has(OWM_MESSAGE_CODE)) { int errorCode = forecastJson.getInt(OWM_MESSAGE_CODE); switch (errorCode) { case HttpURLConnection.HTTP_OK: break; case HttpURLConnection.HTTP_NOT_FOUND: setLocationStatus(getContext(), LOCATION_STATUS_INVALID); break; default: setLocationStatus(getContext(), LOCATION_STATUS_SERVER_DOWN); } } JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY); String cityName = cityJson.getString(OWM_CITY_NAME); JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD); double cityLatitude = cityCoord.getDouble(OWM_LATITUDE); double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE); long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude); // Insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length()); // OWM returns daily forecasts based upon the local time of the city that is being // asked for, which means that we need to know the GMT offset to translate this data // properly. // Since this data is also sent in-order and the first day is always the // current day, we're going to take advantage of that to get a nice // normalized UTC date for all of our weather. Time dayTime = new Time(); dayTime.setToNow(); // we start at the day returned by local time. Otherwise this is a mess. int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // now we work exclusively in UTC dayTime = new Time(); for (int i = 0; i < weatherArray.length(); i++) { // These are the values that will be collected. long dateTime; double pressure; int humidity; double windSpeed; double windDirection; double high; double low; String description; int weatherId; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // Cheating to convert this to UTC time, which is what we want anyhow dateTime = dayTime.setJulianDay(julianStartDay + i); pressure = dayForecast.getDouble(OWM_PRESSURE); humidity = dayForecast.getInt(OWM_HUMIDITY); windSpeed = dayForecast.getDouble(OWM_WINDSPEED); windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION); // Description is in a child array called "weather", which is 1 element long. // That element also contains a weather code. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); weatherId = weatherObject.getInt(OWM_WEATHER_ID); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); high = temperatureObject.getDouble(OWM_MAX); low = temperatureObject.getDouble(OWM_MIN); ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_LOC_KEY, locationId); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DATE, dateTime); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_HUMIDITY, humidity); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_PRESSURE, pressure); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WIND_SPEED, windSpeed); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DEGREES, windDirection); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, high); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MIN_TEMP, low); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_SHORT_DESC, description); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, weatherId); cVVector.add(weatherValues); } int inserted = 0; // add to database if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); getContext().getContentResolver().bulkInsert(WeatherContract.WeatherEntry.CONTENT_URI, cvArray); // delete old data so we don't build up an endless history getContext().getContentResolver().delete(WeatherContract.WeatherEntry.CONTENT_URI, WeatherContract.WeatherEntry.COLUMN_DATE + " <= ?", new String[]{Long.toString(dayTime.setJulianDay(julianStartDay - 1))}); updateWidgets(); updateMuzei(); notifyWeather(); } Log.d(LOG_TAG, "Sync Complete. " + cVVector.size() + " Inserted"); setLocationStatus(getContext(), LOCATION_STATUS_OK); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); setLocationStatus(getContext(), LOCATION_STATUS_SERVER_INVALID); e.printStackTrace(); } } private void updateWidgets(){ Context context = getContext(); Intent dataUpdatedIntent = new Intent(ACTION_DATA_UPDATED) .setPackage(context.getPackageName()); context.sendBroadcast(dataUpdatedIntent); } private void updateMuzei(){ if(Build.VERSION.SDK_INT>Build.VERSION_CODES.JELLY_BEAN){ Context context = getContext(); context.startService(new Intent(ACTION_DATA_UPDATED) .setClass(context, WeatherMuzeiSource.class)); } } private void notifyWeather() { Context context = getContext(); //checking the last update and notify if it' the first of the day SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String displayNotificationsKey = context.getString(R.string.pref_enable_notifications_key); boolean displayNotifications = prefs.getBoolean(displayNotificationsKey, Boolean.parseBoolean(context.getString(R.string.pref_enable_notifications_default))); if (displayNotifications) { String lastNotificationKey = context.getString(R.string.pref_last_notification); long lastSync = prefs.getLong(lastNotificationKey, 0); if (System.currentTimeMillis() - lastSync >= DAY_IN_MILLIS) { // Last sync was more than 1 day ago, let's send a notification with the weather. String locationQuery = Utility.getPreferredLocation(context); Uri weatherUri = WeatherContract.WeatherEntry.buildWeatherLocationWithDate(locationQuery, System.currentTimeMillis()); // we'll query our contentProvider, as always Cursor cursor = context.getContentResolver().query(weatherUri, NOTIFY_WEATHER_PROJECTION, null, null, null); if (cursor.moveToFirst()) { int weatherId = cursor.getInt(INDEX_WEATHER_ID); double high = cursor.getDouble(INDEX_MAX_TEMP); double low = cursor.getDouble(INDEX_MIN_TEMP); String desc = cursor.getString(INDEX_SHORT_DESC); int iconId = Utility.getIconResourceForWeatherCondition(weatherId); Resources resources = context.getResources(); int artResourceId = Utility.getArtResourceForWeatherCondition(weatherId); String artUrl = Utility.getArtUrlForWeatherCondition(context, weatherId); // On Honeycomb and higher devices, we can retrieve the size of the large icon // Prior to that, we use a fixed size @SuppressLint("InlinedApi") int largeIconWidth = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_width) : resources.getDimensionPixelSize(R.dimen.notification_large_icon_default); @SuppressLint("InlinedApi") int largeIconHeight = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_height) : resources.getDimensionPixelSize(R.dimen.notification_large_icon_default); // Retrieve the large icon Bitmap largeIcon; try { largeIcon = Glide.with(context) .load(artUrl) .asBitmap() .error(artResourceId) .fitCenter() .into(largeIconWidth, largeIconHeight).get(); } catch (InterruptedException | ExecutionException e) { Log.e(LOG_TAG, "Error retrieving large icon from " + artUrl, e); largeIcon = BitmapFactory.decodeResource(resources, artResourceId); } String title = context.getString(R.string.app_name); // Define the text of the forecast. String contentText = String.format(context.getString(R.string.format_notification), desc, Utility.formatTemperature(context, high), Utility.formatTemperature(context, low)); // NotificationCompatBuilder is a very convenient way to build backward-compatible // notifications. Just throw in some data. NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getContext()) .setColor(resources.getColor(R.color.primary_light)) .setSmallIcon(iconId) .setLargeIcon(largeIcon) .setContentTitle(title) .setContentText(contentText); // Make something interesting happen when the user clicks on the notification. // In this case, opening the app is sufficient. Intent resultIntent = new Intent(context, MainActivity.class); // The stack builder object will contain an artificial back stack for the // started Activity. // This ensures that navigating backward from the Activity leads out of // your application to the Home screen. TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT ); mBuilder.setContentIntent(resultPendingIntent); NotificationManager mNotificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE); // WEATHER_NOTIFICATION_ID allows you to update the notification later on. mNotificationManager.notify(WEATHER_NOTIFICATION_ID, mBuilder.build()); //refreshing last sync SharedPreferences.Editor editor = prefs.edit(); editor.putLong(lastNotificationKey, System.currentTimeMillis()); editor.commit(); } cursor.close(); } } } /** * Helper method to handle insertion of a new location in the weather database. * * @param locationSetting The location string used to request updates from the server. * @param cityName A human-readable city name, e.g "Mountain View" * @param lat the latitude of the city * @param lon the longitude of the city * @return the row ID of the added location. */ long addLocation(String locationSetting, String cityName, double lat, double lon) { long locationId; // First, check if the location with this city name exists in the db Cursor locationCursor = getContext().getContentResolver().query( WeatherContract.LocationEntry.CONTENT_URI, new String[]{WeatherContract.LocationEntry._ID}, WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[]{locationSetting}, null); if (locationCursor.moveToFirst()) { int locationIdIndex = locationCursor.getColumnIndex(WeatherContract.LocationEntry._ID); locationId = locationCursor.getLong(locationIdIndex); } else { // Now that the content provider is set up, inserting rows of data is pretty simple. // First create a ContentValues object to hold the data you want to insert. ContentValues locationValues = new ContentValues(); // Then add the data, along with the corresponding name of the data type, // so the content provider knows what kind of value is being inserted. locationValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName); locationValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting); locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat); locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon); // Finally, insert location data into the database. Uri insertedUri = getContext().getContentResolver().insert( WeatherContract.LocationEntry.CONTENT_URI, locationValues ); // The resulting URI contains the ID for the row. Extract the locationId from the Uri. locationId = ContentUris.parseId(insertedUri); } locationCursor.close(); // Wait, that worked? Yes! return locationId; } /** * Helper method to schedule the sync adapter periodic execution */ public static void configurePeriodicSync(Context context, int syncInterval, int flexTime) { Account account = getSyncAccount(context); String authority = context.getString(R.string.content_authority); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // we can enable inexact timers in our periodic sync SyncRequest request = new SyncRequest.Builder(). syncPeriodic(syncInterval, flexTime). setSyncAdapter(account, authority). setExtras(new Bundle()).build(); ContentResolver.requestSync(request); } else { ContentResolver.addPeriodicSync(account, authority, new Bundle(), syncInterval); } } /** * Helper method to have the sync adapter sync immediately * * @param context The context used to access the account service */ public static void syncImmediately(Context context) { Bundle bundle = new Bundle(); bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); ContentResolver.requestSync(getSyncAccount(context), context.getString(R.string.content_authority), bundle); } /** * Helper method to get the fake account to be used with SyncAdapter, or make a new one * if the fake account doesn't exist yet. If we make a new account, we call the * onAccountCreated method so we can initialize things. * * @param context The context used to access the account service * @return a fake account. */ public static Account getSyncAccount(Context context) { // Get an instance of the Android account manager AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE); // Create the account type and default account Account newAccount = new Account( context.getString(R.string.app_name), context.getString(R.string.sync_account_type)); // If the password doesn't exist, the account doesn't exist if (null == accountManager.getPassword(newAccount)) { /* * Add the account and account type, no password or user data * If successful, return the Account object, otherwise report an error. */ if (!accountManager.addAccountExplicitly(newAccount, "", null)) { return null; } /* * If you don't set android:syncable="true" in * in your <provider> element in the manifest, * then call ContentResolver.setIsSyncable(account, AUTHORITY, 1) * here. */ onAccountCreated(newAccount, context); } return newAccount; } private static void onAccountCreated(Account newAccount, Context context) { /* * Since we've created an account */ SunshineSyncAdapter.configurePeriodicSync(context, SYNC_INTERVAL, SYNC_FLEXTIME); /* * Without calling setSyncAutomatically, our periodic sync will not be enabled. */ ContentResolver.setSyncAutomatically(newAccount, context.getString(R.string.content_authority), true); /* * Finally, let's do a sync to get things started */ syncImmediately(context); } public static void initializeSyncAdapter(Context context) { getSyncAccount(context); } /** * Set the current location status according to the response received from the server. * * @param context * @param locationStatus - Annotated with @LocationStatus so that only the desired values appear */ public void setLocationStatus(Context context, @LocationStatus int locationStatus) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt(context.getString(R.string.pref_location_status_key), locationStatus); editor.commit(); } }
apache-2.0
MrJacek/agent
src/main/java/pl/hojczak/swa/agents/Country.java
959
/* * 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 pl.hojczak.swa.agents; import pl.hojczak.swa.abstracts.AbstractAgent; import pl.hojczak.swa.enums.Resources; /** * * @author jhojczak */ public class Country extends AbstractAgent { private static final long serialVersionUID = -2622338287143408788L; public int[] collects = new int[Resources.values().length]; public int cancelContractCount = 0; public String printState() { StringBuilder builder = new StringBuilder(this.getLocalName()); builder.append(": {"); for (Resources res : Resources.values()) { builder.append(res.name()).append("=").append(collects[res.ordinal()]).append(" "); } builder.append("cash=").append(this.cash).append("}"); return builder.toString(); } }
apache-2.0
liuyuanyuan/dbeaver
plugins/org.jkiss.dbeaver.data.transfer.ui/src/org/jkiss/dbeaver/tools/transfer/ui/internal/DTUIActivator.java
1686
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2019 Serge Rider (serge@jkiss.org) * * 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.jkiss.dbeaver.tools.transfer.ui.internal; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; public class DTUIActivator extends AbstractUIPlugin { // The plug-in ID public static final String PLUGIN_ID = "org.jkiss.dbeaver.data.transfer"; // The shared instance private static DTUIActivator plugin; public DTUIActivator() { } @Override public void start(BundleContext context) throws Exception { super.start(context); plugin = this; } @Override public void stop(BundleContext context) throws Exception { plugin = null; super.stop(context); } public static DTUIActivator getDefault() { return plugin; } public static ImageDescriptor getImageDescriptor(String path) { return imageDescriptorFromPlugin(PLUGIN_ID, path); } public void saveDialogSettings() { super.saveDialogSettings(); } }
apache-2.0