code
stringlengths
5
1.04M
repo_name
stringlengths
7
108
path
stringlengths
6
299
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1.04M
package org.molgenis.ontology.initializer; public interface OntologyScriptInitializer { void initialize(); }
marijevdgeest/molgenis
molgenis-ontology/src/main/java/org/molgenis/ontology/initializer/OntologyScriptInitializer.java
Java
lgpl-3.0
111
/* * 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.stratos.messaging.listener.application; import org.apache.stratos.messaging.listener.EventListener; public abstract class GroupInstanceActivatedEventListener extends EventListener { }
pubudu538/stratos
components/org.apache.stratos.messaging/src/main/java/org/apache/stratos/messaging/listener/application/GroupInstanceActivatedEventListener.java
Java
apache-2.0
1,012
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide.actions; import com.intellij.find.FindManager; import com.intellij.find.FindUtil; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.editor.Caret; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.actionSystem.EditorAction; import com.intellij.openapi.editor.actionSystem.EditorActionHandler; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDocumentManager; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import static com.intellij.openapi.editor.actions.IncrementalFindAction.SEARCH_DISABLED; public class SearchBackAction extends EditorAction implements DumbAware { public SearchBackAction() { super(new Handler()); setEnabledInModalContext(true); } private static class Handler extends EditorActionHandler { @Override protected void doExecute(@NotNull Editor editor, @Nullable Caret caret, DataContext dataContext) { final Project project = dataContext.getData(CommonDataKeys.PROJECT); if (project == null) return; PsiDocumentManager.getInstance(project).commitAllDocuments(); FindManager findManager = FindManager.getInstance(project); if(!findManager.selectNextOccurrenceWasPerformed() && findManager.findPreviousUsageInEditor(editor)) { return; } FindUtil.searchBack(project, editor, dataContext); } @Override protected boolean isEnabledForCaret(@NotNull Editor editor, @NotNull Caret caret, DataContext dataContext) { Project project = dataContext.getData(CommonDataKeys.PROJECT); if (project == null) { return false; } return !editor.isOneLineMode() && !SEARCH_DISABLED.get(editor, false); } } }
siosio/intellij-community
platform/lang-impl/src/com/intellij/ide/actions/SearchBackAction.java
Java
apache-2.0
2,416
/* * Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package org.jetbrains.yaml.meta.model; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.yaml.YAMLBundle; import org.jetbrains.yaml.psi.YAMLQuotedText; import org.jetbrains.yaml.psi.YAMLScalar; @ApiStatus.Internal public class YamlNumberType extends YamlScalarType { private static final YamlNumberType SHARED_INSTANCE_NO_QUOTED_VALUES_ALLOWED = new YamlNumberType(false); private static final YamlNumberType SHARED_INSTANCE_QUOTED_VALUES_ALLOWED = new YamlNumberType(true); private final boolean myQuotedValuesAllowed; public static YamlNumberType getInstance(boolean quotedValuesAllowed) { return quotedValuesAllowed ? SHARED_INSTANCE_QUOTED_VALUES_ALLOWED : SHARED_INSTANCE_NO_QUOTED_VALUES_ALLOWED; } public YamlNumberType(boolean quotedValuesAllowed) { super("yaml:number"); myQuotedValuesAllowed = quotedValuesAllowed; setDisplayName("number"); } @Override protected void validateScalarValue(@NotNull YAMLScalar scalarValue, @NotNull ProblemsHolder holder) { try { if (!myQuotedValuesAllowed && scalarValue instanceof YAMLQuotedText) { throw new NumberFormatException("no quoted values allowed"); } final String textValue = scalarValue.getTextValue(); // Float.parseFloat() successfully parses values like " 1.0 ", i.e. starting or ending with spaces, // which is not valid for typed schema if (textValue.startsWith(" ") || textValue.endsWith(" ")) { throw new NumberFormatException("contains spaces"); } Float.parseFloat(textValue); } catch (NumberFormatException e) { holder.registerProblem(scalarValue, YAMLBundle.message("YamlNumberType.error.numeric.value"), ProblemHighlightType.ERROR); } } }
siosio/intellij-community
plugins/yaml/src/org/jetbrains/yaml/meta/model/YamlNumberType.java
Java
apache-2.0
2,048
/* * 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.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators; import java.io.IOException; import java.io.ObjectInputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapreduce.Job; import org.apache.pig.FuncSpec; import org.apache.pig.IndexableLoadFunc; import org.apache.pig.LoadFunc; import org.apache.pig.PigException; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigMapReduce; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.POStatus; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.PhysicalOperator; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.Result; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.plans.PhyPlanVisitor; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.plans.PhysicalPlan; import org.apache.pig.data.DataType; import org.apache.pig.data.SchemaTuple; import org.apache.pig.data.SchemaTupleBackend; import org.apache.pig.data.SchemaTupleClassGenerator.GenContext; import org.apache.pig.data.SchemaTupleFactory; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.data.TupleMaker; import org.apache.pig.impl.PigContext; import org.apache.pig.impl.builtin.DefaultIndexableLoader; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.apache.pig.impl.plan.NodeIdGenerator; import org.apache.pig.impl.plan.OperatorKey; import org.apache.pig.impl.plan.PlanException; import org.apache.pig.impl.plan.VisitorException; import org.apache.pig.impl.util.MultiMap; import org.apache.pig.newplan.logical.relational.LOJoin; /** This operator implements merge join algorithm to do map side joins. * Currently, only two-way joins are supported. One input of join is identified as left * and other is identified as right. Left input tuples are the input records in map. * Right tuples are read from HDFS by opening right stream. * * This join doesn't support outer join. * Data is assumed to be sorted in ascending order. It will fail if data is sorted in descending order. */ public class POMergeJoin extends PhysicalOperator { private static final Log log = LogFactory.getLog(POMergeJoin.class); private static final long serialVersionUID = 1L; private static final String keyOrderReminder = "Remember that you should " + "not change the order of keys before a merge join in a FOREACH or " + "manipulate join keys in a UDF in a way that would change the sort " + "order. UDFs in a FOREACH are allowed as long as they do not change" + "the join key values in a way that would change the sort order.\n"; // flag to indicate when getNext() is called first. private boolean firstTime = true; //The Local Rearrange operators modeling the join key private POLocalRearrange[] LRs; private transient LoadFunc rightLoader; private OperatorKey opKey; private Object prevLeftKey; private Result prevLeftInp; private Object prevRightKey = null; private Result prevRightInp; //boolean denoting whether we are generating joined tuples in this getNext() call or do we need to read in more data. private boolean doingJoin; private FuncSpec rightLoaderFuncSpec; private String rightInputFileName; private String indexFile; // Buffer to hold accumulated left tuples. private transient TuplesToSchemaTupleList leftTuples; private MultiMap<PhysicalOperator, PhysicalPlan> inpPlans; private PhysicalOperator rightPipelineLeaf; private PhysicalOperator rightPipelineRoot; private boolean noInnerPlanOnRightSide; private Object curJoinKey; private Tuple curJoiningRightTup; private int counter; // # of tuples on left side with same key. private int leftTupSize = -1; private int rightTupSize = -1; private int arrayListSize = 1024; private LOJoin.JOINTYPE joinType; private String signature; private byte endOfRecordMark = POStatus.STATUS_NULL; // This serves as the default TupleFactory private transient TupleFactory mTupleFactory; /** * These TupleFactories are used for more efficient Tuple generation. This should * decrease the amount of memory needed for a given map task to successfully perform * a merge join. */ private transient TupleMaker mergedTupleMaker; private transient TupleMaker leftTupleMaker; private Schema leftInputSchema; private Schema mergedInputSchema; /** * @param k * @param rp * @param inp * @param inpPlans there can only be 2 inputs each being a List<PhysicalPlan> * Ex. join A by ($0,$1), B by ($1,$2); */ public POMergeJoin(OperatorKey k, int rp, List<PhysicalOperator> inp, MultiMap<PhysicalOperator, PhysicalPlan> inpPlans, List<List<Byte>> keyTypes, LOJoin.JOINTYPE joinType, Schema leftInputSchema, Schema rightInputSchema, Schema mergedInputSchema) throws PlanException{ super(k, rp, inp); this.opKey = k; this.doingJoin = false; this.inpPlans = inpPlans; LRs = new POLocalRearrange[2]; this.createJoinPlans(inpPlans,keyTypes); this.indexFile = null; this.joinType = joinType; this.leftInputSchema = leftInputSchema; this.mergedInputSchema = mergedInputSchema; } /** * Configures the Local Rearrange operators to get keys out of tuple. * @throws ExecException */ private void createJoinPlans(MultiMap<PhysicalOperator, PhysicalPlan> inpPlans, List<List<Byte>> keyTypes) throws PlanException{ int i=-1; for (PhysicalOperator inpPhyOp : inpPlans.keySet()) { ++i; POLocalRearrange lr = new POLocalRearrange(genKey()); try { lr.setIndex(i); } catch (ExecException e) { throw new PlanException(e.getMessage(),e.getErrorCode(),e.getErrorSource(),e); } lr.setResultType(DataType.TUPLE); lr.setKeyType(keyTypes.get(i).size() > 1 ? DataType.TUPLE : keyTypes.get(i).get(0)); lr.setPlans(inpPlans.get(inpPhyOp)); LRs[i]= lr; } } /** * This is a helper method that sets up all of the TupleFactory members. */ private void prepareTupleFactories() { mTupleFactory = TupleFactory.getInstance(); if (leftInputSchema != null) { leftTupleMaker = SchemaTupleBackend.newSchemaTupleFactory(leftInputSchema, false, GenContext.MERGE_JOIN); } if (leftTupleMaker == null) { log.debug("No SchemaTupleFactory available for combined left merge join schema: " + leftInputSchema); leftTupleMaker = mTupleFactory; } else { log.debug("Using SchemaTupleFactory for left merge join schema: " + leftInputSchema); } if (mergedInputSchema != null) { mergedTupleMaker = SchemaTupleBackend.newSchemaTupleFactory(mergedInputSchema, false, GenContext.MERGE_JOIN); } if (mergedTupleMaker == null) { log.debug("No SchemaTupleFactory available for combined left/right merge join schema: " + mergedInputSchema); mergedTupleMaker = mTupleFactory; } else { log.debug("Using SchemaTupleFactory for left/right merge join schema: " + mergedInputSchema); } } /** * This provides a List to store Tuples in. The implementation of that list depends on whether * or not there is a TupleFactory available. * @return the list object to store Tuples in */ private TuplesToSchemaTupleList newLeftTupleArray() { return new TuplesToSchemaTupleList(arrayListSize, leftTupleMaker); } /** * This is a class that extends ArrayList, making it easy to provide on the fly conversion * from Tuple to SchemaTuple. This is necessary because we are not getting SchemaTuples * from the source, though in the future that is what we would like to do. */ public static class TuplesToSchemaTupleList { private List<Tuple> tuples; private SchemaTupleFactory tf; public TuplesToSchemaTupleList(int ct, TupleMaker<?> tf) { tuples = new ArrayList<Tuple>(ct); if (tf instanceof SchemaTupleFactory) { this.tf = (SchemaTupleFactory)tf; } } public static SchemaTuple<?> convert(Tuple t, SchemaTupleFactory tf) { if (t instanceof SchemaTuple<?>) { return (SchemaTuple<?>)t; } SchemaTuple<?> st = tf.newTuple(); try { return st.set(t); } catch (ExecException e) { throw new RuntimeException("Unable to set SchemaTuple with schema [" + st.getSchemaString() + "] with given Tuple in merge join."); } } public boolean add(Tuple t) { if (tf != null) { t = convert(t, tf); } return tuples.add(t); } public Tuple get(int i) { return tuples.get(i); } public int size() { return tuples.size(); } public List<Tuple> getList() { return tuples; } } @SuppressWarnings("unchecked") @Override public Result getNextTuple() throws ExecException { Object curLeftKey; Result curLeftInp; if(firstTime){ prepareTupleFactories(); leftTuples = newLeftTupleArray(); // Do initial setup. curLeftInp = processInput(); if(curLeftInp.returnStatus != POStatus.STATUS_OK) return curLeftInp; // Return because we want to fetch next left tuple. curLeftKey = extractKeysFromTuple(curLeftInp, 0); if(null == curLeftKey) // We drop the tuples which have null keys. return new Result(endOfRecordMark, null); try { seekInRightStream(curLeftKey); } catch (IOException e) { throwProcessingException(true, e); } catch (ClassCastException e) { throwProcessingException(true, e); } leftTuples.add((Tuple)curLeftInp.result); firstTime = false; prevLeftKey = curLeftKey; return new Result(endOfRecordMark, null); } if(doingJoin){ // We matched on keys. Time to do the join. if(counter > 0){ // We have left tuples to join with current right tuple. Tuple joiningLeftTup = leftTuples.get(--counter); leftTupSize = joiningLeftTup.size(); Tuple joinedTup = mergedTupleMaker.newTuple(leftTupSize + rightTupSize); for(int i=0; i<leftTupSize; i++) { joinedTup.set(i, joiningLeftTup.get(i)); } for(int i=0; i < rightTupSize; i++) { joinedTup.set(i+leftTupSize, curJoiningRightTup.get(i)); } return new Result(POStatus.STATUS_OK, joinedTup); } // Join with current right input has ended. But bag of left tuples // may still join with next right tuple. doingJoin = false; while(true){ Result rightInp = getNextRightInp(); if(rightInp.returnStatus != POStatus.STATUS_OK){ prevRightInp = null; return rightInp; } else{ Object rightKey = extractKeysFromTuple(rightInp, 1); if(null == rightKey) // If we see tuple having null keys in stream, we drop them continue; // and fetch next tuple. int cmpval = ((Comparable)rightKey).compareTo(curJoinKey); if (cmpval == 0){ // Matched the very next right tuple. curJoiningRightTup = (Tuple)rightInp.result; rightTupSize = curJoiningRightTup.size(); counter = leftTuples.size(); doingJoin = true; return this.getNextTuple(); } else if(cmpval > 0){ // We got ahead on right side. Store currently read right tuple. if(!this.parentPlan.endOfAllInput){ prevRightKey = rightKey; prevRightInp = rightInp; // There cant be any more join on this key. leftTuples = newLeftTupleArray(); leftTuples.add((Tuple)prevLeftInp.result); return new Result(endOfRecordMark, null); } else{ // This is end of all input and this is last join output. // Right loader in this case wouldn't get a chance to close input stream. So, we close it ourself. try { ((IndexableLoadFunc)rightLoader).close(); } catch (IOException e) { // Non-fatal error. We can continue. log.error("Received exception while trying to close right side file: " + e.getMessage()); } return new Result(POStatus.STATUS_EOP, null); } } else{ // At this point right side can't be behind. int errCode = 1102; String errMsg = "Data is not sorted on right side. \n" + keyOrderReminder + "Last two tuples encountered were: \n"+ curJoiningRightTup+ "\n" + (Tuple)rightInp.result ; throw new ExecException(errMsg,errCode); } } } } curLeftInp = processInput(); switch(curLeftInp.returnStatus){ case POStatus.STATUS_OK: curLeftKey = extractKeysFromTuple(curLeftInp, 0); if(null == curLeftKey) // We drop the tuples which have null keys. return new Result(endOfRecordMark, null); int cmpVal = ((Comparable)curLeftKey).compareTo(prevLeftKey); if(cmpVal == 0){ // Keep on accumulating. leftTuples.add((Tuple)curLeftInp.result); return new Result(endOfRecordMark, null); } else if(cmpVal > 0){ // Filled with left bag. Move on. curJoinKey = prevLeftKey; break; } else{ // Current key < Prev Key int errCode = 1102; String errMsg = "Data is not sorted on left side. \n" + keyOrderReminder + "Last two tuples encountered were: \n" + prevLeftKey+ "\n" + curLeftKey ; throw new ExecException(errMsg,errCode); } case POStatus.STATUS_EOP: if(this.parentPlan.endOfAllInput){ // We hit the end on left input. // Tuples in bag may still possibly join with right side. curJoinKey = prevLeftKey; curLeftKey = null; break; } else // Fetch next left input. return curLeftInp; default: // If encountered with ERR / NULL on left side, we send it down. return curLeftInp; } if((null != prevRightKey) && !this.parentPlan.endOfAllInput && ((Comparable)prevRightKey).compareTo(curLeftKey) >= 0){ // This will happen when we accumulated inputs on left side and moved on, but are still behind the right side // In that case, throw away the tuples accumulated till now and add the one we read in this function call. leftTuples = newLeftTupleArray(); leftTuples.add((Tuple)curLeftInp.result); prevLeftInp = curLeftInp; prevLeftKey = curLeftKey; return new Result(endOfRecordMark, null); } // Accumulated tuples with same key on left side. // But since we are reading ahead we still haven't checked the read ahead right tuple. // Accumulated left tuples may potentially join with that. So, lets check that first. if((null != prevRightKey) && prevRightKey.equals(prevLeftKey)){ curJoiningRightTup = (Tuple)prevRightInp.result; counter = leftTuples.size(); rightTupSize = curJoiningRightTup.size(); doingJoin = true; prevLeftInp = curLeftInp; prevLeftKey = curLeftKey; return this.getNextTuple(); } // We will get here only when curLeftKey > prevRightKey boolean slidingToNextRecord = false; while(true){ // Start moving on right stream to find the tuple whose key is same as with current left bag key. Result rightInp; if (slidingToNextRecord) { rightInp = getNextRightInp(); slidingToNextRecord = false; } else rightInp = getNextRightInp(prevLeftKey); if(rightInp.returnStatus != POStatus.STATUS_OK) return rightInp; Object extractedRightKey = extractKeysFromTuple(rightInp, 1); if(null == extractedRightKey) // If we see tuple having null keys in stream, we drop them continue; // and fetch next tuple. Comparable rightKey = (Comparable)extractedRightKey; if( prevRightKey != null && rightKey.compareTo(prevRightKey) < 0){ // Sanity check. int errCode = 1102; String errMsg = "Data is not sorted on right side. \n" + keyOrderReminder + "Last two tuples encountered were: \n"+ prevRightKey+ "\n" + rightKey ; throw new ExecException(errMsg,errCode); } int cmpval = rightKey.compareTo(prevLeftKey); if(cmpval < 0) { // still behind the left side, do nothing, fetch next right tuple. slidingToNextRecord = true; continue; } else if (cmpval == 0){ // Found matching tuple. Time to do join. curJoiningRightTup = (Tuple)rightInp.result; counter = leftTuples.size(); rightTupSize = curJoiningRightTup.size(); doingJoin = true; prevLeftInp = curLeftInp; prevLeftKey = curLeftKey; return this.getNextTuple(); } else{ // We got ahead on right side. Store currently read right tuple. prevRightKey = rightKey; prevRightInp = rightInp; // Since we didn't find any matching right tuple we throw away the buffered left tuples and add the one read in this function call. leftTuples = newLeftTupleArray(); leftTuples.add((Tuple)curLeftInp.result); prevLeftInp = curLeftInp; prevLeftKey = curLeftKey; if(this.parentPlan.endOfAllInput){ // This is end of all input and this is last time we will read right input. // Right loader in this case wouldn't get a chance to close input stream. So, we close it ourself. try { ((IndexableLoadFunc)rightLoader).close(); } catch (IOException e) { // Non-fatal error. We can continue. log.error("Received exception while trying to close right side file: " + e.getMessage()); } } return new Result(endOfRecordMark, null); } } } private void seekInRightStream(Object firstLeftKey) throws IOException{ rightLoader = (LoadFunc)PigContext.instantiateFuncFromSpec(rightLoaderFuncSpec); // check if hadoop distributed cache is used if (indexFile != null && rightLoader instanceof DefaultIndexableLoader) { DefaultIndexableLoader loader = (DefaultIndexableLoader)rightLoader; loader.setIndexFile(indexFile); } // Pass signature of the loader to rightLoader // make a copy of the conf to use in calls to rightLoader. rightLoader.setUDFContextSignature(signature); Job job = new Job(new Configuration(PigMapReduce.sJobConfInternal.get())); rightLoader.setLocation(rightInputFileName, job); ((IndexableLoadFunc)rightLoader).initialize(job.getConfiguration()); ((IndexableLoadFunc)rightLoader).seekNear( firstLeftKey instanceof Tuple ? (Tuple)firstLeftKey : mTupleFactory.newTuple(firstLeftKey)); } private Result getNextRightInp(Object leftKey) throws ExecException{ /* * Only call seekNear if the merge join is 'merge-sparse'. DefaultIndexableLoader does not * support more than a single call to seekNear per split - so don't call seekNear. */ if (joinType == LOJoin.JOINTYPE.MERGESPARSE) { try { ((IndexableLoadFunc)rightLoader).seekNear(leftKey instanceof Tuple ? (Tuple)leftKey : mTupleFactory.newTuple(leftKey)); prevRightKey = null; } catch (IOException e) { throwProcessingException(true, e); } } return this.getNextRightInp(); } private Result getNextRightInp() throws ExecException{ try { if(noInnerPlanOnRightSide){ Tuple t = rightLoader.getNext(); if(t == null) { // no more data on right side return new Result(POStatus.STATUS_EOP, null); } else { return new Result(POStatus.STATUS_OK, t); } } else { Result res = rightPipelineLeaf.getNextTuple(); rightPipelineLeaf.detachInput(); switch(res.returnStatus){ case POStatus.STATUS_OK: return res; case POStatus.STATUS_EOP: Tuple t = rightLoader.getNext(); if(t == null) { // no more data on right side return new Result(POStatus.STATUS_EOP, null); } else { // run the tuple through the pipeline rightPipelineRoot.attachInput(t); return this.getNextRightInp(); } default: // We don't deal with ERR/NULL. just pass them down throwProcessingException(false, null); } } } catch (IOException e) { throwProcessingException(true, e); } // we should never get here! return new Result(POStatus.STATUS_ERR, null); } public void throwProcessingException (boolean withCauseException, Exception e) throws ExecException { int errCode = 2176; String errMsg = "Error processing right input during merge join"; if(withCauseException) { throw new ExecException(errMsg, errCode, PigException.BUG, e); } else { throw new ExecException(errMsg, errCode, PigException.BUG); } } private Object extractKeysFromTuple(Result inp, int lrIdx) throws ExecException{ //Separate Key & Value of input using corresponding LR operator POLocalRearrange lr = LRs[lrIdx]; lr.attachInput((Tuple)inp.result); Result lrOut = lr.getNextTuple(); lr.detachInput(); if(lrOut.returnStatus!=POStatus.STATUS_OK){ int errCode = 2167; String errMsg = "LocalRearrange used to extract keys from tuple isn't configured correctly"; throw new ExecException(errMsg,errCode,PigException.BUG); } return ((Tuple) lrOut.result).get(1); } public void setupRightPipeline(PhysicalPlan rightPipeline) throws FrontendException{ if(rightPipeline != null){ if(rightPipeline.getLeaves().size() != 1 || rightPipeline.getRoots().size() != 1){ int errCode = 2168; String errMsg = "Expected physical plan with exactly one root and one leaf."; throw new FrontendException(errMsg,errCode,PigException.BUG); } noInnerPlanOnRightSide = false; this.rightPipelineLeaf = rightPipeline.getLeaves().get(0); this.rightPipelineRoot = rightPipeline.getRoots().get(0); this.rightPipelineRoot.setInputs(null); } else noInnerPlanOnRightSide = true; } private void readObject(ObjectInputStream is) throws IOException, ClassNotFoundException, ExecException{ is.defaultReadObject(); mTupleFactory = TupleFactory.getInstance(); } private OperatorKey genKey(){ return new OperatorKey(opKey.scope,NodeIdGenerator.getGenerator().getNextNodeId(opKey.scope)); } public void setRightLoaderFuncSpec(FuncSpec rightLoaderFuncSpec) { this.rightLoaderFuncSpec = rightLoaderFuncSpec; } public List<PhysicalPlan> getInnerPlansOf(int index) { return inpPlans.get(inputs.get(index)); } @Override public void visit(PhyPlanVisitor v) throws VisitorException { v.visitMergeJoin(this); } @Override public String name() { String name = getAliasString() + "MergeJoin"; if (joinType==LOJoin.JOINTYPE.MERGESPARSE) name+="(sparse)"; name+="[" + DataType.findTypeName(resultType) + "]" + " - " + mKey.toString(); return name; } @Override public boolean supportsMultipleInputs() { return true; } /* (non-Javadoc) * @see org.apache.pig.impl.plan.Operator#supportsMultipleOutputs() */ @Override public boolean supportsMultipleOutputs() { return false; } /** * @param rightInputFileName the rightInputFileName to set */ public void setRightInputFileName(String rightInputFileName) { this.rightInputFileName = rightInputFileName; } public String getSignature() { return signature; } public void setSignature(String signature) { this.signature = signature; } public void setIndexFile(String indexFile) { this.indexFile = indexFile; } public String getIndexFile() { return indexFile; } @Override public Tuple illustratorMarkup(Object in, Object out, int eqClassIndex) { return null; } public LOJoin.JOINTYPE getJoinType() { return joinType; } }
netxillon/pig
src/org/apache/pig/backend/hadoop/executionengine/physicalLayer/relationalOperators/POMergeJoin.java
Java
apache-2.0
28,504
/** * 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.apex.examples.uniquecount; import org.junit.Test; import org.apache.hadoop.conf.Configuration; import com.datatorrent.api.LocalMode; /** * Test the DAG declaration in local mode. */ public class UniqueKeyValExampleTest { @Test public void testApplication() throws Exception { LocalMode lma = LocalMode.newInstance(); new UniqueKeyValCountExample().populateDAG(lma.getDAG(), new Configuration(false)); LocalMode.Controller lc = lma.getController(); lc.run(10000); } }
tweise/apex-malhar
examples/uniquecount/src/test/java/org/apache/apex/examples/uniquecount/UniqueKeyValExampleTest.java
Java
apache-2.0
1,323
/* * 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.spark.unsafe.memory; import org.apache.spark.unsafe.Platform; import org.junit.Assert; import org.junit.Test; import java.nio.ByteOrder; import static org.hamcrest.core.StringContains.containsString; public class MemoryBlockSuite { private static final boolean bigEndianPlatform = ByteOrder.nativeOrder().equals(ByteOrder.BIG_ENDIAN); private void check(MemoryBlock memory, Object obj, long offset, int length) { memory.setPageNumber(1); memory.fill((byte)-1); memory.putBoolean(0, true); memory.putByte(1, (byte)127); memory.putShort(2, (short)257); memory.putInt(4, 0x20000002); memory.putLong(8, 0x1234567089ABCDEFL); memory.putFloat(16, 1.0F); memory.putLong(20, 0x1234567089ABCDEFL); memory.putDouble(28, 2.0); MemoryBlock.copyMemory(memory, 0L, memory, 36, 4); int[] a = new int[2]; a[0] = 0x12345678; a[1] = 0x13579BDF; memory.copyFrom(a, Platform.INT_ARRAY_OFFSET, 40, 8); byte[] b = new byte[8]; memory.writeTo(40, b, Platform.BYTE_ARRAY_OFFSET, 8); Assert.assertEquals(obj, memory.getBaseObject()); Assert.assertEquals(offset, memory.getBaseOffset()); Assert.assertEquals(length, memory.size()); Assert.assertEquals(1, memory.getPageNumber()); Assert.assertEquals(true, memory.getBoolean(0)); Assert.assertEquals((byte)127, memory.getByte(1 )); Assert.assertEquals((short)257, memory.getShort(2)); Assert.assertEquals(0x20000002, memory.getInt(4)); Assert.assertEquals(0x1234567089ABCDEFL, memory.getLong(8)); Assert.assertEquals(1.0F, memory.getFloat(16), 0); Assert.assertEquals(0x1234567089ABCDEFL, memory.getLong(20)); Assert.assertEquals(2.0, memory.getDouble(28), 0); Assert.assertEquals(true, memory.getBoolean(36)); Assert.assertEquals((byte)127, memory.getByte(37 )); Assert.assertEquals((short)257, memory.getShort(38)); Assert.assertEquals(a[0], memory.getInt(40)); Assert.assertEquals(a[1], memory.getInt(44)); if (bigEndianPlatform) { Assert.assertEquals(a[0], ((int)b[0] & 0xff) << 24 | ((int)b[1] & 0xff) << 16 | ((int)b[2] & 0xff) << 8 | ((int)b[3] & 0xff)); Assert.assertEquals(a[1], ((int)b[4] & 0xff) << 24 | ((int)b[5] & 0xff) << 16 | ((int)b[6] & 0xff) << 8 | ((int)b[7] & 0xff)); } else { Assert.assertEquals(a[0], ((int)b[3] & 0xff) << 24 | ((int)b[2] & 0xff) << 16 | ((int)b[1] & 0xff) << 8 | ((int)b[0] & 0xff)); Assert.assertEquals(a[1], ((int)b[7] & 0xff) << 24 | ((int)b[6] & 0xff) << 16 | ((int)b[5] & 0xff) << 8 | ((int)b[4] & 0xff)); } for (int i = 48; i < memory.size(); i++) { Assert.assertEquals((byte) -1, memory.getByte(i)); } assert(memory.subBlock(0, memory.size()) == memory); try { memory.subBlock(-8, 8); Assert.fail(); } catch (Exception expected) { Assert.assertThat(expected.getMessage(), containsString("non-negative")); } try { memory.subBlock(0, -8); Assert.fail(); } catch (Exception expected) { Assert.assertThat(expected.getMessage(), containsString("non-negative")); } try { memory.subBlock(0, length + 8); Assert.fail(); } catch (Exception expected) { Assert.assertThat(expected.getMessage(), containsString("should not be larger than")); } try { memory.subBlock(8, length - 4); Assert.fail(); } catch (Exception expected) { Assert.assertThat(expected.getMessage(), containsString("should not be larger than")); } try { memory.subBlock(length + 8, 4); Assert.fail(); } catch (Exception expected) { Assert.assertThat(expected.getMessage(), containsString("should not be larger than")); } memory.setPageNumber(MemoryBlock.NO_PAGE_NUMBER); } @Test public void testByteArrayMemoryBlock() { byte[] obj = new byte[56]; long offset = Platform.BYTE_ARRAY_OFFSET; int length = obj.length; MemoryBlock memory = new ByteArrayMemoryBlock(obj, offset, length); check(memory, obj, offset, length); memory = ByteArrayMemoryBlock.fromArray(obj); check(memory, obj, offset, length); obj = new byte[112]; memory = new ByteArrayMemoryBlock(obj, offset, length); check(memory, obj, offset, length); } @Test public void testOnHeapMemoryBlock() { long[] obj = new long[7]; long offset = Platform.LONG_ARRAY_OFFSET; int length = obj.length * 8; MemoryBlock memory = new OnHeapMemoryBlock(obj, offset, length); check(memory, obj, offset, length); memory = OnHeapMemoryBlock.fromArray(obj); check(memory, obj, offset, length); obj = new long[14]; memory = new OnHeapMemoryBlock(obj, offset, length); check(memory, obj, offset, length); } @Test public void testOffHeapArrayMemoryBlock() { MemoryAllocator memoryAllocator = new UnsafeMemoryAllocator(); MemoryBlock memory = memoryAllocator.allocate(56); Object obj = memory.getBaseObject(); long offset = memory.getBaseOffset(); int length = 56; check(memory, obj, offset, length); memoryAllocator.free(memory); long address = Platform.allocateMemory(112); memory = new OffHeapMemoryBlock(address, length); obj = memory.getBaseObject(); offset = memory.getBaseOffset(); check(memory, obj, offset, length); Platform.freeMemory(address); } }
bravo-zhang/spark
common/unsafe/src/test/java/org/apache/spark/unsafe/memory/MemoryBlockSuite.java
Java
apache-2.0
6,238
/* * 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.drill.exec.rpc.data; import io.netty.buffer.DrillBuf; import org.apache.drill.exec.memory.BufferAllocator; import org.apache.drill.exec.proto.BitData.FragmentRecordBatch; import org.apache.drill.exec.record.RawFragmentBatch; import org.apache.drill.shaded.guava.com.google.common.base.Preconditions; /** * An incoming batch of data. The data is held by the original allocator. Any use of the associated data must be * leveraged through the use of newRawFragmentBatch(). */ public class IncomingDataBatch { private final FragmentRecordBatch header; private final DrillBuf body; private final AckSender sender; /** * Create a new batch. Does not impact reference counts of body. * * @param header * Batch header * @param body * Data body. Could be null. * @param sender * AckSender to use for underlying RawFragmentBatches. */ public IncomingDataBatch(FragmentRecordBatch header, DrillBuf body, AckSender sender) { Preconditions.checkNotNull(header); Preconditions.checkNotNull(sender); this.header = header; this.body = body; this.sender = sender; } /** * Create a new RawFragmentBatch based on this incoming data batch that is transferred into the provided allocator. * Also increments the AckSender to expect one additional return message. * * @param allocator * Target allocator that should be associated with data underlying this batch. * @return The newly created RawFragmentBatch */ public RawFragmentBatch newRawFragmentBatch(final BufferAllocator allocator) { final DrillBuf transferredBuffer = body == null ? null : body.transferOwnership(allocator).buffer; sender.increment(); return new RawFragmentBatch(header, transferredBuffer, sender); } public FragmentRecordBatch getHeader() { return header; } }
johnnywale/drill
exec/java-exec/src/main/java/org/apache/drill/exec/rpc/data/IncomingDataBatch.java
Java
apache-2.0
2,686
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.siyeh.ig.bugs; import com.intellij.codeInspection.InspectionProfileEntry; import com.siyeh.ig.LightJavaInspectionTestCase; import org.jetbrains.annotations.Nullable; public class PrimitiveArrayArgumentToVariableArgMethodInspectionTest extends LightJavaInspectionTestCase { public void testPrimitiveArrayArgumentToVariableArgMethod() { doTest(); } @Nullable @Override protected InspectionProfileEntry getInspection() { return new PrimitiveArrayArgumentToVariableArgMethodInspection(); } @Override protected String getBasePath() { return "/plugins/InspectionGadgets/test/com/siyeh/igtest/bugs/var_arg"; } }
siosio/intellij-community
plugins/InspectionGadgets/testsrc/com/siyeh/ig/bugs/PrimitiveArrayArgumentToVariableArgMethodInspectionTest.java
Java
apache-2.0
1,252
/* * Copyright (c) 2011 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.api.client.http; import com.google.api.client.util.IOUtils; import com.google.api.client.util.StringUtils; import junit.framework.TestCase; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * Tests {@link ByteArrayContent}. * * @author Yaniv Inbar */ public class ByteArrayContentTest extends TestCase { private static final byte[] FOO = StringUtils.getBytesUtf8("foo"); public void testConstructor() throws IOException { subtestConstructor(new ByteArrayContent("type", FOO), "foo"); subtestConstructor(new ByteArrayContent("type", FOO, 0, 3), "foo"); subtestConstructor(new ByteArrayContent("type", FOO, 1, 2), "oo"); subtestConstructor(new ByteArrayContent("type", FOO, 0, 0), ""); try { new ByteArrayContent(null, FOO, -1, 2); fail("expected " + IllegalArgumentException.class); } catch (IllegalArgumentException e) { // expected assertEquals("offset -1, length 2, array length 3", e.getMessage()); } try { new ByteArrayContent(null, FOO, 2, 2); fail("expected " + IllegalArgumentException.class); } catch (IllegalArgumentException e) { // expected assertEquals("offset 2, length 2, array length 3", e.getMessage()); } try { new ByteArrayContent(null, FOO, 3, 1); fail("expected " + IllegalArgumentException.class); } catch (IllegalArgumentException e) { // expected assertEquals("offset 3, length 1, array length 3", e.getMessage()); } } public void subtestConstructor(ByteArrayContent content, String expected) throws IOException { assertEquals("type", content.getType()); assertTrue(content.retrySupported()); assertEquals(expected.length(), content.getLength()); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(content.getInputStream(), out); assertEquals(expected, out.toString()); } }
wgpshashank/google-http-java-client
google-http-client/src/test/java/com/google/api/client/http/ByteArrayContentTest.java
Java
apache-2.0
2,513
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.models; import org.keycloak.provider.Provider; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @author <a href="mailto:[email protected]">Bill Burke</a> * @version $Revision: 1 $ */ public interface UserSessionProvider extends Provider { /** * Returns currently used Keycloak session. * @return {@link KeycloakSession} */ KeycloakSession getKeycloakSession(); AuthenticatedClientSessionModel createClientSession(RealmModel realm, ClientModel client, UserSessionModel userSession); /** * @deprecated Use {@link #getClientSession(UserSessionModel, ClientModel, String, boolean)} instead. */ default AuthenticatedClientSessionModel getClientSession(UserSessionModel userSession, ClientModel client, UUID clientSessionId, boolean offline) { return getClientSession(userSession, client, clientSessionId == null ? null : clientSessionId.toString(), offline); } AuthenticatedClientSessionModel getClientSession(UserSessionModel userSession, ClientModel client, String clientSessionId, boolean offline); UserSessionModel createUserSession(RealmModel realm, UserModel user, String loginUsername, String ipAddress, String authMethod, boolean rememberMe, String brokerSessionId, String brokerUserId); UserSessionModel createUserSession(String id, RealmModel realm, UserModel user, String loginUsername, String ipAddress, String authMethod, boolean rememberMe, String brokerSessionId, String brokerUserId, UserSessionModel.SessionPersistenceState persistenceState); UserSessionModel getUserSession(RealmModel realm, String id); /** * @deprecated Use {@link #getUserSessionsStream(RealmModel, ClientModel) getUserSessionsStream} instead. */ @Deprecated default List<UserSessionModel> getUserSessions(RealmModel realm, UserModel user) { return this.getUserSessionsStream(realm, user).collect(Collectors.toList()); } /** * Obtains the online user sessions associated with the specified user. * * @param realm a reference to the realm. * @param user the user whose sessions are being searched. * @return a non-null {@link Stream} of online user sessions. */ Stream<UserSessionModel> getUserSessionsStream(RealmModel realm, UserModel user); /** * @deprecated Use {@link #getUserSessionsStream(RealmModel, ClientModel) getUserSessionsStream} instead. */ @Deprecated default List<UserSessionModel> getUserSessions(RealmModel realm, ClientModel client) { return this.getUserSessionsStream(realm, client).collect(Collectors.toList()); } /** * Obtains the online user sessions associated with the specified client. * * @param realm a reference to the realm. * @param client the client whose user sessions are being searched. * @return a non-null {@link Stream} of online user sessions. */ Stream<UserSessionModel> getUserSessionsStream(RealmModel realm, ClientModel client); /** * @deprecated Use {@link #getUserSessionsStream(RealmModel, ClientModel, Integer, Integer) getUserSessionsStream} instead. */ @Deprecated default List<UserSessionModel> getUserSessions(RealmModel realm, ClientModel client, int firstResult, int maxResults) { return this.getUserSessionsStream(realm, client, firstResult, maxResults).collect(Collectors.toList()); } /** * Obtains the online user sessions associated with the specified client, starting from the {@code firstResult} and containing * at most {@code maxResults}. * * @param realm a reference tot he realm. * @param client the client whose user sessions are being searched. * @param firstResult first result to return. Ignored if negative or {@code null}. * @param maxResults maximum number of results to return. Ignored if negative or {@code null}. * @return a non-null {@link Stream} of online user sessions. */ Stream<UserSessionModel> getUserSessionsStream(RealmModel realm, ClientModel client, Integer firstResult, Integer maxResults); /** * @deprecated Use {@link #getUserSessionByBrokerUserIdStream(RealmModel, String) getUserSessionByBrokerUserIdStream} * instead. */ @Deprecated default List<UserSessionModel> getUserSessionByBrokerUserId(RealmModel realm, String brokerUserId) { return this.getUserSessionByBrokerUserIdStream(realm, brokerUserId).collect(Collectors.toList()); } /** * Obtains the online user sessions associated with the user that matches the specified {@code brokerUserId}. * * @param realm a reference to the realm. * @param brokerUserId the id of the broker user whose sessions are being searched. * @return a non-null {@link Stream} of online user sessions. */ Stream<UserSessionModel> getUserSessionByBrokerUserIdStream(RealmModel realm, String brokerUserId); UserSessionModel getUserSessionByBrokerSessionId(RealmModel realm, String brokerSessionId); /** * Return userSession of specified ID as long as the predicate passes. Otherwise returns {@code null}. * If predicate doesn't pass, implementation can do some best-effort actions to try have predicate passing (eg. download userSession from other DC) */ UserSessionModel getUserSessionWithPredicate(RealmModel realm, String id, boolean offline, Predicate<UserSessionModel> predicate); long getActiveUserSessions(RealmModel realm, ClientModel client); /** * Returns a summary of client sessions key is client.getId() * * @param realm * @param offline * @return */ Map<String, Long> getActiveClientSessionStats(RealmModel realm, boolean offline); /** This will remove attached ClientLoginSessionModels too **/ void removeUserSession(RealmModel realm, UserSessionModel session); void removeUserSessions(RealmModel realm, UserModel user); /** * Remove expired user sessions and client sessions in all the realms */ void removeAllExpired(); /** * Removes expired user sessions owned by this realm from this provider. * If this `UserSessionProvider` uses `UserSessionPersister`, the removal of the expired * {@link UserSessionModel user sessions} is also propagated to relevant `UserSessionPersister`. * * @param realm {@link RealmModel} Realm where all the expired user sessions to be removed from. */ void removeExpired(RealmModel realm); void removeUserSessions(RealmModel realm); /** * @deprecated Use {@link UserLoginFailureProvider#getUserLoginFailure(RealmModel, String) getUserLoginFailure} instead. */ @Deprecated default UserLoginFailureModel getUserLoginFailure(RealmModel realm, String userId) { return getKeycloakSession().loginFailures().getUserLoginFailure(realm, userId); } /** * @deprecated Use {@link UserLoginFailureProvider#addUserLoginFailure(RealmModel, String) addUserLoginFailure} instead. */ @Deprecated default UserLoginFailureModel addUserLoginFailure(RealmModel realm, String userId) { return getKeycloakSession().loginFailures().addUserLoginFailure(realm, userId); } /** * @deprecated Use {@link UserLoginFailureProvider#removeUserLoginFailure(RealmModel, String) removeUserLoginFailure} instead. */ @Deprecated default void removeUserLoginFailure(RealmModel realm, String userId) { getKeycloakSession().loginFailures().removeUserLoginFailure(realm, userId); } /** * @deprecated Use {@link UserLoginFailureProvider#removeAllUserLoginFailures(RealmModel) removeAllUserLoginFailures} instead. */ @Deprecated default void removeAllUserLoginFailures(RealmModel realm) { getKeycloakSession().loginFailures().removeAllUserLoginFailures(realm); } void onRealmRemoved(RealmModel realm); void onClientRemoved(RealmModel realm, ClientModel client); /** Newly created userSession won't contain attached AuthenticatedClientSessions **/ UserSessionModel createOfflineUserSession(UserSessionModel userSession); UserSessionModel getOfflineUserSession(RealmModel realm, String userSessionId); /** Removes the attached clientSessions as well **/ void removeOfflineUserSession(RealmModel realm, UserSessionModel userSession); /** Will automatically attach newly created offline client session to the offlineUserSession **/ AuthenticatedClientSessionModel createOfflineClientSession(AuthenticatedClientSessionModel clientSession, UserSessionModel offlineUserSession); /** * @deprecated Use {@link #getOfflineUserSessionsStream(RealmModel, UserModel) getOfflineUserSessionsStream} instead. */ @Deprecated default List<UserSessionModel> getOfflineUserSessions(RealmModel realm, UserModel user) { return this.getOfflineUserSessionsStream(realm, user).collect(Collectors.toList()); } /** * Obtains the offline user sessions associated with the specified user. * * @param realm a reference to the realm. * @param user the user whose offline sessions are being searched. * @return a non-null {@link Stream} of offline user sessions. */ Stream<UserSessionModel> getOfflineUserSessionsStream(RealmModel realm, UserModel user); UserSessionModel getOfflineUserSessionByBrokerSessionId(RealmModel realm, String brokerSessionId); /** * @deprecated Use {@link #getOfflineUserSessionByBrokerUserIdStream(RealmModel, String) getOfflineUserSessionByBrokerUserIdStream} * instead. */ @Deprecated default List<UserSessionModel> getOfflineUserSessionByBrokerUserId(RealmModel realm, String brokerUserId) { return this.getOfflineUserSessionByBrokerUserIdStream(realm, brokerUserId).collect(Collectors.toList()); } /** * Obtains the offline user sessions associated with the user that matches the specified {@code brokerUserId}. * * @param realm a reference to the realm. * @param brokerUserId the id of the broker user whose sessions are being searched. * @return a non-null {@link Stream} of offline user sessions. */ Stream<UserSessionModel> getOfflineUserSessionByBrokerUserIdStream(RealmModel realm, String brokerUserId); long getOfflineSessionsCount(RealmModel realm, ClientModel client); /** * @deprecated use {@link #getOfflineUserSessionsStream(RealmModel, ClientModel, Integer, Integer) getOfflineUserSessionsStream} * instead. */ @Deprecated default List<UserSessionModel> getOfflineUserSessions(RealmModel realm, ClientModel client, int first, int max) { return this.getOfflineUserSessionsStream(realm, client, first, max).collect(Collectors.toList()); } /** * Obtains the offline user sessions associated with the specified client, starting from the {@code firstResult} and * containing at most {@code maxResults}. * * @param realm a reference tot he realm. * @param client the client whose user sessions are being searched. * @param firstResult first result to return. Ignored if negative or {@code null}. * @param maxResults maximum number of results to return. Ignored if negative or {@code null}. * @return a non-null {@link Stream} of offline user sessions. */ Stream<UserSessionModel> getOfflineUserSessionsStream(RealmModel realm, ClientModel client, Integer firstResult, Integer maxResults); /** Triggered by persister during pre-load. It imports authenticatedClientSessions too **/ void importUserSessions(Collection<UserSessionModel> persistentUserSessions, boolean offline); void close(); }
abstractj/keycloak
server-spi/src/main/java/org/keycloak/models/UserSessionProvider.java
Java
apache-2.0
12,612
/* * * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.carbon.humantask.core.integration.jmx; import org.apache.axis2.databinding.types.URI; import org.wso2.carbon.humantask.client.api.IllegalAccessFault; import org.wso2.carbon.humantask.client.api.IllegalArgumentFault; import org.wso2.carbon.humantask.client.api.IllegalOperationFault; import org.wso2.carbon.humantask.client.api.IllegalStateFault; import org.wso2.carbon.humantask.skeleton.mgt.services.PackageManagementException; /** * Task Status monitoring MBean */ public interface HTTaskStatusMonitorMXBean { //@DescriptorKey("number of cache slots in use") /** * @return String[] contains all deployed tasks details (task instances count, tenant ID, task def name, task name, operation, port name) for all tenants */ public String[] showAllTaskDefinitions() throws IllegalAccessFault, IllegalArgumentFault, IllegalStateFault, IllegalOperationFault, PackageManagementException; /** * @param taskName can be a task name or task def name, based on that the result will be given, preferred: task def name * @return String[] of task instances' details ( task instances count for each status) * @throws IllegalAccessFault * @throws IllegalArgumentFault * @throws IllegalStateFault * @throws IllegalOperationFault */ public String[] getInstanceCountForTaskDefinition(String taskName) throws IllegalAccessFault, IllegalArgumentFault, IllegalStateFault, IllegalOperationFault; /** * @param status give a valid status to search the task instances in that status * @return String[] of all task instances for the given status * @throws IllegalStateFault * @throws IllegalOperationFault * @throws IllegalArgumentFault * @throws IllegalAccessFault */ public String[] getInstancesListForTaskState(String status) throws IllegalStateFault, IllegalOperationFault, IllegalArgumentFault, IllegalAccessFault; /** * @param taskID taskId of the task instance which details should be displayed * @return all the available details of the task instance * @throws IllegalAccessFault * @throws IllegalArgumentFault * @throws IllegalStateFault * @throws IllegalOperationFault * @throws URI.MalformedURIException */ public String[] getTaskInstanceDetails(String taskID) throws IllegalAccessFault, IllegalArgumentFault, IllegalStateFault, IllegalOperationFault, URI.MalformedURIException; public String getName(); }
chathurace/carbon-business-process
components/humantask/org.wso2.carbon.humantask/src/main/java/org/wso2/carbon/humantask/core/integration/jmx/HTTaskStatusMonitorMXBean.java
Java
apache-2.0
3,304
/* * Copyright 2012-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.boot.autoconfigure.data.jpa; import java.lang.annotation.Annotation; import java.util.Locale; import org.springframework.boot.autoconfigure.data.AbstractRepositoryConfigurationSourceSupport; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.env.Environment; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.data.jpa.repository.config.JpaRepositoryConfigExtension; import org.springframework.data.repository.config.BootstrapMode; import org.springframework.data.repository.config.RepositoryConfigurationExtension; import org.springframework.util.StringUtils; /** * {@link ImportBeanDefinitionRegistrar} used to auto-configure Spring Data JPA * Repositories. * * @author Phillip Webb * @author Dave Syer * @author Scott Frederick */ class JpaRepositoriesRegistrar extends AbstractRepositoryConfigurationSourceSupport { private BootstrapMode bootstrapMode = null; @Override protected Class<? extends Annotation> getAnnotation() { return EnableJpaRepositories.class; } @Override protected Class<?> getConfiguration() { return EnableJpaRepositoriesConfiguration.class; } @Override protected RepositoryConfigurationExtension getRepositoryConfigurationExtension() { return new JpaRepositoryConfigExtension(); } @Override protected BootstrapMode getBootstrapMode() { return (this.bootstrapMode == null) ? BootstrapMode.DEFAULT : this.bootstrapMode; } @Override public void setEnvironment(Environment environment) { super.setEnvironment(environment); configureBootstrapMode(environment); } private void configureBootstrapMode(Environment environment) { String property = environment.getProperty("spring.data.jpa.repositories.bootstrap-mode"); if (StringUtils.hasText(property)) { this.bootstrapMode = BootstrapMode.valueOf(property.toUpperCase(Locale.ENGLISH)); } } @EnableJpaRepositories private static class EnableJpaRepositoriesConfiguration { } }
aahlenst/spring-boot
spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesRegistrar.java
Java
apache-2.0
2,669
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets 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 io.druid.query.extraction; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Preconditions; import com.ibm.icu.text.SimpleDateFormat; import com.metamx.common.StringUtils; import java.nio.ByteBuffer; import java.text.ParseException; import java.util.Date; /** */ public class TimeDimExtractionFn extends DimExtractionFn { private final String timeFormat; private final SimpleDateFormat timeFormatter; private final String resultFormat; private final SimpleDateFormat resultFormatter; @JsonCreator public TimeDimExtractionFn( @JsonProperty("timeFormat") String timeFormat, @JsonProperty("resultFormat") String resultFormat ) { Preconditions.checkNotNull(timeFormat, "timeFormat must not be null"); Preconditions.checkNotNull(resultFormat, "resultFormat must not be null"); this.timeFormat = timeFormat; this.timeFormatter = new SimpleDateFormat(timeFormat); this.timeFormatter.setLenient(true); this.resultFormat = resultFormat; this.resultFormatter = new SimpleDateFormat(resultFormat); } @Override public byte[] getCacheKey() { byte[] timeFormatBytes = StringUtils.toUtf8(timeFormat); return ByteBuffer.allocate(1 + timeFormatBytes.length) .put(ExtractionCacheHelper.CACHE_TYPE_ID_TIME_DIM) .put(timeFormatBytes) .array(); } @Override public String apply(String dimValue) { Date date; try { date = timeFormatter.parse(dimValue); } catch (ParseException e) { return dimValue; } return resultFormatter.format(date); } @JsonProperty("timeFormat") public String getTimeFormat() { return timeFormat; } @JsonProperty("resultFormat") public String getResultFormat() { return resultFormat; } @Override public boolean preservesOrdering() { return false; } @Override public ExtractionType getExtractionType() { return ExtractionType.MANY_TO_ONE; } @Override public String toString() { return "TimeDimExtractionFn{" + "timeFormat='" + timeFormat + '\'' + ", resultFormat='" + resultFormat + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TimeDimExtractionFn that = (TimeDimExtractionFn) o; if (!resultFormat.equals(that.resultFormat)) { return false; } if (!timeFormat.equals(that.timeFormat)) { return false; } return true; } @Override public int hashCode() { int result = timeFormat.hashCode(); result = 31 * result + resultFormat.hashCode(); return result; } }
tubemogul/druid
processing/src/main/java/io/druid/query/extraction/TimeDimExtractionFn.java
Java
apache-2.0
3,647
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.client.ml; import org.elasticsearch.client.ml.filestructurefinder.FileStructure; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.ObjectParser; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.test.AbstractXContentTestCase; import java.io.IOException; import java.nio.charset.Charset; import java.util.Arrays; public class FindFileStructureRequestTests extends AbstractXContentTestCase<FindFileStructureRequest> { private static final ObjectParser<FindFileStructureRequest, Void> PARSER = new ObjectParser<>("find_file_structure_request", FindFileStructureRequest::new); static { PARSER.declareInt(FindFileStructureRequest::setLinesToSample, FindFileStructureRequest.LINES_TO_SAMPLE); PARSER.declareInt(FindFileStructureRequest::setLineMergeSizeLimit, FindFileStructureRequest.LINE_MERGE_SIZE_LIMIT); PARSER.declareString((p, c) -> p.setTimeout(TimeValue.parseTimeValue(c, FindFileStructureRequest.TIMEOUT.getPreferredName())), FindFileStructureRequest.TIMEOUT); PARSER.declareString(FindFileStructureRequest::setCharset, FindFileStructureRequest.CHARSET); PARSER.declareString(FindFileStructureRequest::setFormat, FindFileStructureRequest.FORMAT); PARSER.declareStringArray(FindFileStructureRequest::setColumnNames, FindFileStructureRequest.COLUMN_NAMES); PARSER.declareBoolean(FindFileStructureRequest::setHasHeaderRow, FindFileStructureRequest.HAS_HEADER_ROW); PARSER.declareString(FindFileStructureRequest::setDelimiter, FindFileStructureRequest.DELIMITER); PARSER.declareString(FindFileStructureRequest::setQuote, FindFileStructureRequest.QUOTE); PARSER.declareBoolean(FindFileStructureRequest::setShouldTrimFields, FindFileStructureRequest.SHOULD_TRIM_FIELDS); PARSER.declareString(FindFileStructureRequest::setGrokPattern, FindFileStructureRequest.GROK_PATTERN); PARSER.declareString(FindFileStructureRequest::setTimestampFormat, FindFileStructureRequest.TIMESTAMP_FORMAT); PARSER.declareString(FindFileStructureRequest::setTimestampField, FindFileStructureRequest.TIMESTAMP_FIELD); PARSER.declareBoolean(FindFileStructureRequest::setExplain, FindFileStructureRequest.EXPLAIN); // Sample is not included in the X-Content representation } @Override protected FindFileStructureRequest doParseInstance(XContentParser parser) throws IOException { return PARSER.apply(parser, null); } @Override protected boolean supportsUnknownFields() { return false; } @Override protected FindFileStructureRequest createTestInstance() { return createTestRequestWithoutSample(); } public static FindFileStructureRequest createTestRequestWithoutSample() { FindFileStructureRequest findFileStructureRequest = new FindFileStructureRequest(); if (randomBoolean()) { findFileStructureRequest.setLinesToSample(randomIntBetween(1000, 2000)); } if (randomBoolean()) { findFileStructureRequest.setLineMergeSizeLimit(randomIntBetween(10000, 20000)); } if (randomBoolean()) { findFileStructureRequest.setTimeout(TimeValue.timeValueSeconds(randomIntBetween(10, 20))); } if (randomBoolean()) { findFileStructureRequest.setCharset(Charset.defaultCharset().toString()); } if (randomBoolean()) { findFileStructureRequest.setFormat(randomFrom(FileStructure.Format.values())); } if (randomBoolean()) { findFileStructureRequest.setColumnNames(Arrays.asList(generateRandomStringArray(10, 10, false, false))); } if (randomBoolean()) { findFileStructureRequest.setHasHeaderRow(randomBoolean()); } if (randomBoolean()) { findFileStructureRequest.setDelimiter(randomAlphaOfLength(1)); } if (randomBoolean()) { findFileStructureRequest.setQuote(randomAlphaOfLength(1)); } if (randomBoolean()) { findFileStructureRequest.setShouldTrimFields(randomBoolean()); } if (randomBoolean()) { findFileStructureRequest.setGrokPattern(randomAlphaOfLength(100)); } if (randomBoolean()) { findFileStructureRequest.setTimestampFormat(randomAlphaOfLength(10)); } if (randomBoolean()) { findFileStructureRequest.setTimestampField(randomAlphaOfLength(10)); } if (randomBoolean()) { findFileStructureRequest.setExplain(randomBoolean()); } return findFileStructureRequest; } }
gingerwizard/elasticsearch
client/rest-high-level/src/test/java/org/elasticsearch/client/ml/FindFileStructureRequestTests.java
Java
apache-2.0
5,546
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.jmonkeyengine.tests; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Filter; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public class CustomArrayAdapter extends ArrayAdapter<String> { private static final String TAG = "CustomArrayAdapter"; /* List of items */ private List<String> entries; private Context activity; /* Position of selected answer */ private int selectedPosition = -1; /* Background Color of selected item */ private int selectedBackgroundColor = 0xffff00; /* Background Color of non selected item */ private int nonselectedBackgroundColor = 0x000000; /* Background Drawable Resource ID of selected item */ private int selectedBackgroundResource = 0; /* Background Drawable Resource ID of non selected items */ private int nonselectedBackgroundResource = 0; /* Variables to support list filtering */ private ArrayList<String> filteredEntries; private Filter filter; public CustomArrayAdapter(Context context, int textViewResourceId, List<String> objects) { super(context, textViewResourceId, objects); activity = context; entries = new ArrayList<String>(objects); filteredEntries = new ArrayList<String>(objects); filter = new ClassNameFilter(); } /** Setter for selected item position */ public void setSelectedPosition(int selectedPosition) { this.selectedPosition = selectedPosition; Log.i(TAG, "Setting position to: " + this.selectedPosition); } /** Setter for selected item background color */ public void setSelectedBackgroundColor(int selectedBackgroundColor) { this.selectedBackgroundColor = selectedBackgroundColor; } /** Setter for non selected background color */ public void setNonSelectedBackgroundColor(int nonselectedBackgroundColor) { this.nonselectedBackgroundColor = nonselectedBackgroundColor; } /** Setter for selected item background resource id*/ public void setSelectedBackgroundResource(int selectedBackgroundResource) { this.selectedBackgroundResource = selectedBackgroundResource; } /** Setter for non selected background resource id*/ public void setNonSelectedBackgroundResource(int nonselectedBackgroundResource) { this.nonselectedBackgroundResource = nonselectedBackgroundResource; } @Override public View getView(int position, View convertView, ViewGroup parent) { Log.i(TAG, "getView for position: " + position + " with selectedItem: " + selectedPosition); View v = convertView; ViewHolder holder; if (v == null) { LayoutInflater vi = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.test_chooser_row, null); holder = new ViewHolder(); holder.textView = (TextView) v.findViewById(R.id.txtClassName); holder.layoutRow = (LinearLayout) v.findViewById(R.id.layoutTestChooserRow); v.setTag(holder); } else { holder=(ViewHolder)v.getTag(); } final String itemText = filteredEntries.get(position); if (itemText != null) { holder.textView.setText(itemText); if (position == selectedPosition) { Log.i(TAG, "setting Background Color to: " + selectedBackgroundColor); // holder.textView.setBackgroundColor(selectedBackgroundColor); // holder.textView.setBackgroundResource(selectedBackgroundResource); holder.layoutRow.setBackgroundResource(selectedBackgroundResource); } else { Log.i(TAG, "setting Background Color to: " + nonselectedBackgroundColor); // holder.textView.setBackgroundColor(nonselectedBackgroundColor); // holder.textView.setBackgroundResource(nonselectedBackgroundResource); holder.layoutRow.setBackgroundResource(nonselectedBackgroundResource); } } return v; } @Override public Filter getFilter(){ if(filter == null){ filter = new ClassNameFilter(); } return filter; } public static class ViewHolder{ public TextView textView; public LinearLayout layoutRow; } private class ClassNameFilter extends Filter{ @Override protected FilterResults performFiltering(CharSequence constraint){ FilterResults results = new FilterResults(); String prefix = constraint.toString().toLowerCase(); Log.i(TAG, "performFiltering: entries size: " + entries.size()); if (prefix == null || prefix.length() == 0){ ArrayList<String> list = new ArrayList<String>(entries); results.values = list; results.count = list.size(); Log.i(TAG, "clearing filter with size: " + list.size()); }else{ final ArrayList<String> list = new ArrayList<String>(entries); final ArrayList<String> nlist = new ArrayList<String>(); int count = list.size(); for (int i = 0; i<count; i++){ if(list.get(i).toLowerCase().contains(prefix)){ nlist.add(list.get(i)); } results.values = nlist; results.count = nlist.size(); } Log.i(TAG, "filtered list size: " + nlist.size() + ", entries size: " + entries.size()); } Log.i(TAG, "Returning filter count: " + results.count); return results; } @SuppressWarnings("unchecked") @Override protected void publishResults(CharSequence constraint, FilterResults results) { filteredEntries = (ArrayList<String>)results.values; notifyDataSetChanged(); clear(); int count = filteredEntries.size(); for(int i = 0; i<count; i++){ add(filteredEntries.get(i)); notifyDataSetInvalidated(); } Log.i(TAG, "publishing results with size: " + count); } } }
OpenGrabeso/jmonkeyengine
sdk/JME3TestsTemplateAndroid/mobile/src/com/jmonkeyengine/tests/CustomArrayAdapter.java
Java
bsd-3-clause
6,776
/** * Copyright (c) 2009--2015 Red Hat, Inc. * * This software is licensed to you under the GNU General Public License, * version 2 (GPLv2). There is NO WARRANTY for this software, express or * implied, including the implied warranties of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 * along with this software; if not, see * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * Red Hat trademarks are not licensed under GPLv2. No permission is * granted to use or replicate Red Hat trademarks that are incorporated * in this software or its documentation. */ package com.redhat.rhn.domain.common.test; import com.redhat.rhn.domain.common.CommonFactory; import com.redhat.rhn.domain.common.FileList; import com.redhat.rhn.domain.config.ConfigFileName; import com.redhat.rhn.domain.org.Org; import com.redhat.rhn.testing.RhnBaseTestCase; import com.redhat.rhn.testing.TestStatics; import com.redhat.rhn.testing.TestUtils; import com.redhat.rhn.testing.UserTestUtils; import java.util.Date; /** * FileListTest * @version $Rev$ */ public class FileListTest extends RhnBaseTestCase { public void testDeleteFileList() { Org o = UserTestUtils.findNewOrg(TestStatics.TESTORG); FileList f = createTestFileList(o); CommonFactory.saveFileList(f); assertNotNull(CommonFactory.lookupFileList(f.getId(), o)); f.addFileName("/tmp/dir/history/file.history"); f.addFileName("/tmp/dir/history/file2.history"); f.addFileName("/tmp/dir/history/file3.history"); flushAndEvict(f); assertEquals(CommonFactory.removeFileList(f), 1); flushAndEvict(f); assertNull(CommonFactory.lookupFileList(f.getId(), o)); } public void testFileList() throws Exception { Org o = UserTestUtils.findNewOrg(TestStatics.TESTORG); FileList f = createTestFileList(o); CommonFactory.saveFileList(f); f.addFileName("/tmp/foo.txt"); flushAndEvict(f); FileList f2 = CommonFactory.lookupFileList(f.getId(), o); assertNotNull(f2.getId()); ConfigFileName cfn = f2.getFileNames().iterator().next(); assertEquals("/tmp/foo.txt", cfn.getPath()); } public static FileList createTestFileList(Org orgIn) { FileList f = new FileList(); f.setLabel("Test FileList" + TestUtils.randomString()); f.setOrg(orgIn); f.setCreated(new Date()); f.setModified(new Date()); assertNull(f.getId()); return f; } }
xkollar/spacewalk
java/code/src/com/redhat/rhn/domain/common/test/FileListTest.java
Java
gpl-2.0
2,563
package com.temenos.interaction.core.hypermedia.expression; /* * #%L * interaction-core * %% * Copyright (C) 2012 - 2013 Temenos Holdings N.V. * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * #L% */ import java.util.Set; import com.temenos.interaction.core.command.InteractionContext; import com.temenos.interaction.core.hypermedia.Transition; import com.temenos.interaction.core.resource.EntityResource; import com.temenos.interaction.core.rim.HTTPHypermediaRIM; public interface Expression { /** * Evaluate this expression and return a boolean result. * @param pathParams * @return */ public boolean evaluate(HTTPHypermediaRIM rimHandler, InteractionContext ctx, EntityResource<?> resource); public Set<Transition> getTransitions(); }
ritumalhotra8/IRIS
interaction-core/src/main/java/com/temenos/interaction/core/hypermedia/expression/Expression.java
Java
agpl-3.0
1,383
package com.twitter.elephantbird.mapreduce.input; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.List; import java.util.PriorityQueue; import java.util.Set; import com.google.common.base.Functions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.twitter.elephantbird.util.HadoopCompat; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathFilter; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.junit.Test; import com.twitter.elephantbird.mapreduce.input.LuceneIndexInputFormat.LuceneIndexInputSplit; import com.twitter.elephantbird.mapreduce.output.LuceneIndexOutputFormat; import static org.easymock.EasyMock.createStrictMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * @author Alex Levenson */ public class TestLuceneIndexInputFormat { @Test public void testFindSplitsRecursive() throws Exception { findSplitsHelper(ImmutableList.of(new Path("src/test/resources/com/twitter/elephantbird" + "/mapreduce/input/sample_indexes/"))); } @Test public void testFindSplitsExplicit() throws Exception { findSplitsHelper(ImmutableList.of( new Path("src/test/resources/com/twitter/elephantbird/mapreduce/input/" + "sample_indexes/index-1"), new Path("src/test/resources/com/twitter/elephantbird/mapreduce/input/" + "sample_indexes/index-2"), new Path("src/test/resources/com/twitter/elephantbird/mapreduce/input/" + "sample_indexes/more-indexes/index-3"))); } private static class DummyLuceneInputFormat extends LuceneIndexInputFormat<IntWritable> { @Override public PathFilter getIndexDirPathFilter(Configuration conf) throws IOException { return LuceneIndexOutputFormat.newIndexDirFilter(conf); } @Override public RecordReader<IntWritable, IntWritable> createRecordReader(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException { return null; } } private void findSplitsHelper(List<Path> inputPaths) throws IOException { DummyLuceneInputFormat lif = new DummyLuceneInputFormat(); Configuration conf = new Configuration(); LuceneIndexInputFormat.setInputPaths(inputPaths, conf); lif.loadConfig(conf); PriorityQueue<LuceneIndexInputSplit> splits = lif.findSplits(conf); LuceneIndexInputSplit split; split = splits.poll(); assertEquals(4, split.getLength()); assertTrue(split.getIndexDirs().get(0).toString().endsWith("sample_indexes/index-1")); split = splits.poll(); assertEquals(6, split.getLength()); assertTrue(split.getIndexDirs().get(0).toString().endsWith("sample_indexes/more-indexes/index-3")); split = splits.poll(); assertEquals(20, split.getLength()); assertTrue(split.getIndexDirs().get(0).toString().endsWith("sample_indexes/index-2")); assertTrue(splits.isEmpty()); } @Test public void testGetSplits() throws Exception { DummyLuceneInputFormat lif = new DummyLuceneInputFormat(); Configuration conf = new Configuration(); LuceneIndexInputFormat.setInputPaths( ImmutableList.of(new Path("src/test/resources/com/twitter/elephantbird" + "/mapreduce/input/sample_indexes/")), conf); LuceneIndexInputFormat.setMaxCombinedIndexSizePerSplitBytes(15L, conf); JobContext jobContext = createStrictMock(JobContext.class); expect(HadoopCompat.getConfiguration(jobContext)).andStubReturn(conf); replay(jobContext); List<InputSplit> splits = lif.getSplits(jobContext); LuceneIndexInputSplit split = (LuceneIndexInputSplit) splits.get(0); assertEquals(2, split.getIndexDirs().size()); assertTrue(split.getIndexDirs().get(0).toString().endsWith("sample_indexes/index-1")); assertTrue(split.getIndexDirs().get(1).toString() .endsWith("sample_indexes/more-indexes/index-3")); split = (LuceneIndexInputSplit) splits.get(1); assertEquals(1, split.getIndexDirs().size()); assertTrue(split.getIndexDirs().get(0).toString().endsWith("sample_indexes/index-2")); } @Test public void testLuceneIndexInputSplit() throws Exception { LuceneIndexInputSplit orig = new LuceneIndexInputSplit( Lists.newArrayList(new Path("/index/test"), new Path("/index/test2"), new Path("/index/test3")), 500L); ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); DataOutputStream dataOut = new DataOutputStream(bytesOut); orig.write(dataOut); LuceneIndexInputSplit deSerialized = new LuceneIndexInputSplit(); deSerialized.readFields(new DataInputStream((new ByteArrayInputStream(bytesOut.toByteArray())))); assertEquals(orig.getIndexDirs(), deSerialized.getIndexDirs()); assertEquals(orig.getLength(), deSerialized.getLength()); assertEquals(0, orig.compareTo(deSerialized)); LuceneIndexInputSplit smaller = new LuceneIndexInputSplit( Lists.newArrayList(new Path("/index/small")), 100L); assertTrue(orig.compareTo(smaller) > 0); assertTrue(smaller.compareTo(orig) < 0); } @Test public void testCombineSplits() throws Exception { DummyLuceneInputFormat lif = new DummyLuceneInputFormat(); PriorityQueue<LuceneIndexInputSplit> splits = new PriorityQueue<LuceneIndexInputSplit>(); String[] paths = new String[] { "/index/1", "/index/2", "/index/3", "/index/4", "/index/5", "/index/6"}; Long[] sizes = new Long[]{500L, 300L, 100L, 150L, 1200L, 500L}; for (int i = 0; i < paths.length; i++) { splits.add(new LuceneIndexInputSplit(Lists.newArrayList(new Path(paths[i])), sizes[i])); } List<InputSplit> combined = lif.combineSplits(splits, 1000L, 10000L); assertEquals(3, combined.size()); List<Path> dirs = ((LuceneIndexInputSplit) combined.get(0)).getIndexDirs(); Set<String> dirsStrings = Sets.newHashSet(Iterables.transform(dirs, Functions.toStringFunction())); assertEquals(3, dirsStrings.size()); assertTrue(dirsStrings.contains("/index/2")); assertTrue(dirsStrings.contains("/index/3")); assertTrue(dirsStrings.contains("/index/4")); dirs = ((LuceneIndexInputSplit) combined.get(1)).getIndexDirs(); dirsStrings = Sets.newHashSet(Iterables.transform(dirs, Functions.toStringFunction())); assertEquals(2, dirsStrings.size()); assertTrue(dirsStrings.contains("/index/1")); assertTrue(dirsStrings.contains("/index/6")); dirs = ((LuceneIndexInputSplit) combined.get(2)).getIndexDirs(); dirsStrings = Sets.newHashSet(Iterables.transform(dirs, Functions.toStringFunction())); assertEquals(1, dirsStrings.size()); assertTrue(dirsStrings.contains("/index/5")); } @Test public void testCombineSplitsOneSplit() throws Exception { DummyLuceneInputFormat lif = new DummyLuceneInputFormat(); PriorityQueue<LuceneIndexInputSplit> splits = new PriorityQueue<LuceneIndexInputSplit>(); splits.add(new LuceneIndexInputSplit(Lists.newArrayList(new Path("/index/1")), 1500L)); List<InputSplit> combined = lif.combineSplits(splits, 1000L, 10000L); assertEquals(1, combined.size()); List<Path> dirs = ((LuceneIndexInputSplit) combined.get(0)).getIndexDirs(); Set<String> dirsStrings = Sets.newHashSet(Iterables.transform(dirs, Functions.toStringFunction())); assertEquals(1, dirsStrings.size()); assertTrue(dirsStrings.contains("/index/1")); } @Test public void testCombineSplitsAllTooBig() throws Exception { DummyLuceneInputFormat lif = new DummyLuceneInputFormat(); PriorityQueue<LuceneIndexInputSplit> splits = new PriorityQueue<LuceneIndexInputSplit>(); String[] paths = new String[]{"/index/1", "/index/2", "/index/3"}; Long[] sizes = new Long[]{1500L, 1501L, 1502L}; for (int i = 0; i < paths.length; i++) { splits.add(new LuceneIndexInputSplit(Lists.newArrayList(new Path(paths[i])), sizes[i])); } List<InputSplit> combined = lif.combineSplits(splits, 1000L, 10000L); assertEquals(3, combined.size()); for (int i=0; i < paths.length; i++) { List<Path> dirs = ((LuceneIndexInputSplit) combined.get(i)).getIndexDirs(); List<String> dirsStrings = Lists.newLinkedList(Iterables.transform(dirs, Functions.toStringFunction())); assertEquals(1, dirsStrings.size()); assertEquals("/index/" + String.valueOf(i + 1), dirsStrings.get(0)); } } @Test public void testCombineSplitsWithMaxNumberIndexesPerMapper() throws Exception { DummyLuceneInputFormat lif = new DummyLuceneInputFormat(); PriorityQueue<LuceneIndexInputSplit> splits = new PriorityQueue<LuceneIndexInputSplit>(); String[] paths = new String[1000]; long[] sizes = new long[1000]; for (int i = 0; i< 100; i++) { switch (i) { case 0: sizes[i] = 500L; paths[i] = "/index/500"; break; case 1: sizes[i] = 300L; paths[i] = "/index/300"; break; case 2: sizes[i] = 100L; paths[i] = "/index/100"; break; default: sizes[i] = 1L; paths[i] = "/index/small-" + i; } splits.add(new LuceneIndexInputSplit(Lists.newArrayList(new Path(paths[i])), sizes[i])); } List<InputSplit> combined = lif.combineSplits(splits, 150L, 10L); assertEquals(12, combined.size()); for (int i = 0; i < 9; i++) { LuceneIndexInputSplit split = (LuceneIndexInputSplit) combined.get(i); assertEquals(10L, split.getIndexDirs().size()); assertEquals(10L, split.getLength()); for (Path p : split.getIndexDirs()) { assertTrue(p.toString().startsWith("/index/small-")); } } LuceneIndexInputSplit split = (LuceneIndexInputSplit) combined.get(9); assertEquals(8, split.getIndexDirs().size()); assertEquals(107, split.getLength()); for (int i = 0; i < 7; i++) { assertTrue(split.getIndexDirs().get(i).toString().startsWith("/index/small-")); } assertEquals("/index/100", split.getIndexDirs().get(7).toString()); split = (LuceneIndexInputSplit) combined.get(10); assertEquals(1, split.getIndexDirs().size()); assertEquals(300, split.getLength()); assertEquals("/index/300", split.getIndexDirs().get(0).toString()); split = (LuceneIndexInputSplit) combined.get(11); assertEquals(1, split.getIndexDirs().size()); assertEquals(500, split.getLength()); assertEquals("/index/500", split.getIndexDirs().get(0).toString()); } @Test public void testQuerySerialization() throws Exception { Configuration conf = new Configuration(); List<String> queries = ImmutableList.of( "+one -two", "something, with, commas", "something 東京 with unicode", "\"something with quotes\""); LuceneIndexInputFormat.setQueries(queries, conf); assertEquals(queries, LuceneIndexInputFormat.getQueries(conf)); } }
canojim/elephant-bird
lucene/src/test/java/com/twitter/elephantbird/mapreduce/input/TestLuceneIndexInputFormat.java
Java
apache-2.0
11,502
/* * Copyright 2015 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.jbpm.bpmn2.persistence; import org.drools.core.command.impl.CommandBasedStatefulKnowledgeSession; import org.drools.core.command.impl.GenericCommand; import org.drools.core.command.impl.KnowledgeCommandContext; import org.jbpm.bpmn2.JbpmBpmn2TestCase; import org.jbpm.compiler.xml.XmlRuleFlowProcessDumper; import org.jbpm.persistence.session.objects.TestWorkItemHandler; import org.jbpm.process.instance.impl.ProcessInstanceImpl; import org.jbpm.ruleflow.core.RuleFlowProcess; import org.jbpm.ruleflow.core.RuleFlowProcessFactory; import org.jbpm.workflow.core.impl.ConnectionImpl; import org.jbpm.workflow.core.impl.NodeImpl; import org.jbpm.workflow.core.node.HumanTaskNode; import org.junit.BeforeClass; import org.junit.Test; import org.kie.api.KieBase; import org.kie.api.definition.process.Connection; import org.kie.api.event.process.ProcessCompletedEvent; import org.kie.api.event.process.ProcessEventListener; import org.kie.api.event.process.ProcessNodeLeftEvent; import org.kie.api.event.process.ProcessNodeTriggeredEvent; import org.kie.api.event.process.ProcessStartedEvent; import org.kie.api.event.process.ProcessVariableChangedEvent; import org.kie.api.io.Resource; import org.kie.internal.command.Context; import org.kie.internal.io.ResourceFactory; import org.kie.internal.runtime.StatefulKnowledgeSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This is a sample file to launch a process. */ public class DynamicProcessTest extends JbpmBpmn2TestCase { private static final Logger logger = LoggerFactory.getLogger(DynamicProcessTest.class); @BeforeClass public static void setup() throws Exception { if (PERSISTENCE) { setUpDataSource(); } } @Test public void testDynamicProcess() throws Exception { RuleFlowProcessFactory factory = RuleFlowProcessFactory.createProcess("org.jbpm.HelloWorld"); factory // Header .name("HelloWorldProcess") .version("1.0") .packageName("org.jbpm") // Nodes .startNode(1).name("Start").done() .humanTaskNode(2).name("Task1").actorId("krisv").taskName("MyTask").done() .endNode(3).name("End").done() // Connections .connection(1, 2) .connection(2, 3); final RuleFlowProcess process = factory.validate().getProcess(); Resource resource = ResourceFactory .newByteArrayResource(XmlRuleFlowProcessDumper.INSTANCE.dump( process).getBytes()); resource.setSourcePath("/tmp/dynamicProcess.bpmn2"); // source path or target path must be set to be added into kbase KieBase kbase = createKnowledgeBaseFromResources(resource); StatefulKnowledgeSession ksession = createKnowledgeSession(kbase); TestWorkItemHandler testHandler = new TestWorkItemHandler(); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", testHandler); ksession.addEventListener(new ProcessEventListener() { public void beforeVariableChanged(ProcessVariableChangedEvent arg0) { } public void beforeProcessStarted(ProcessStartedEvent arg0) { logger.info("{}", arg0); } public void beforeProcessCompleted(ProcessCompletedEvent arg0) { logger.info("{}", arg0); } public void beforeNodeTriggered(ProcessNodeTriggeredEvent arg0) { logger.info("{}", arg0); } public void beforeNodeLeft(ProcessNodeLeftEvent arg0) { logger.info("{}", arg0); } public void afterVariableChanged(ProcessVariableChangedEvent arg0) { } public void afterProcessStarted(ProcessStartedEvent arg0) { } public void afterProcessCompleted(ProcessCompletedEvent arg0) { } public void afterNodeTriggered(ProcessNodeTriggeredEvent arg0) { } public void afterNodeLeft(ProcessNodeLeftEvent arg0) { } }); final ProcessInstanceImpl processInstance = (ProcessInstanceImpl) ksession.startProcess("org.jbpm.HelloWorld"); HumanTaskNode node = new HumanTaskNode(); node.setName("Task2"); node.setId(4); insertNodeInBetween(process, 2, 3, node); ((CommandBasedStatefulKnowledgeSession) ksession).getCommandService().execute(new GenericCommand<Void>() { public Void execute(Context context) { StatefulKnowledgeSession ksession = (StatefulKnowledgeSession) ((KnowledgeCommandContext) context).getKieSession(); ((ProcessInstanceImpl) ksession.getProcessInstance(processInstance.getId())).updateProcess(process); return null; } }); assertProcessInstanceActive(processInstance); ksession.getWorkItemManager().completeWorkItem(testHandler.getWorkItem().getId(), null); assertProcessInstanceActive(processInstance); ksession.getWorkItemManager().completeWorkItem(testHandler.getWorkItem().getId(), null); assertProcessInstanceFinished(processInstance, ksession); ksession.dispose(); } private static void insertNodeInBetween(RuleFlowProcess process, long startNodeId, long endNodeId, NodeImpl node) { if (process == null) { throw new IllegalArgumentException("Process may not be null"); } NodeImpl selectedNode = (NodeImpl) process.getNode(startNodeId); if (selectedNode == null) { throw new IllegalArgumentException("Node " + startNodeId + " not found in process " + process.getId()); } for (Connection connection: selectedNode.getDefaultOutgoingConnections()) { if (connection.getTo().getId() == endNodeId) { process.addNode(node); NodeImpl endNode = (NodeImpl) connection.getTo(); ((ConnectionImpl) connection).terminate(); new ConnectionImpl(selectedNode, NodeImpl.CONNECTION_DEFAULT_TYPE, node, NodeImpl.CONNECTION_DEFAULT_TYPE); new ConnectionImpl(node, NodeImpl.CONNECTION_DEFAULT_TYPE, endNode, NodeImpl.CONNECTION_DEFAULT_TYPE); return; } } throw new IllegalArgumentException("Connection to node " + endNodeId + " not found in process " + process.getId()); } }
OnePaaS/jbpm
jbpm-bpmn2/src/test/java/org/jbpm/bpmn2/persistence/DynamicProcessTest.java
Java
apache-2.0
6,398
/** * Copyright © 2002 Instituto Superior Técnico * * This file is part of FenixEdu Academic. * * FenixEdu Academic 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. * * FenixEdu Academic 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 FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>. */ package org.fenixedu.academic.servlet.taglib.sop.v3.colorPickers; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import org.fenixedu.academic.domain.DomainObjectUtil; import org.fenixedu.academic.domain.ExecutionCourse; import org.fenixedu.academic.domain.Lesson; import org.fenixedu.academic.domain.WrittenEvaluation; import org.fenixedu.academic.dto.InfoLesson; import org.fenixedu.academic.dto.InfoLessonInstance; import org.fenixedu.academic.dto.InfoLessonInstanceAggregation; import org.fenixedu.academic.dto.InfoShowOccupation; import org.fenixedu.academic.dto.InfoWrittenEvaluation; import org.fenixedu.academic.servlet.taglib.sop.v3.ColorPicker; public class ClassTimeTableColorPicker extends ColorPicker { @Override protected String getColorKeyFromInfoLesson(final InfoShowOccupation infoShowOccupation) { if (infoShowOccupation instanceof InfoLesson) { return key((InfoLesson) infoShowOccupation); } if (infoShowOccupation instanceof InfoLessonInstance) { return key((InfoLessonInstance) infoShowOccupation); } if (infoShowOccupation instanceof InfoLessonInstanceAggregation) { return key((InfoLessonInstanceAggregation) infoShowOccupation); } if (infoShowOccupation instanceof InfoWrittenEvaluation) { return key((InfoWrittenEvaluation) infoShowOccupation); } else { return "GenericEvent"; } } private String key(final Lesson lesson) { return lesson.getExecutionCourse().getExternalId(); } private String key(final InfoLesson infoLesson) { return key(infoLesson.getLesson()); } private String key(final InfoLessonInstance infoLessonInstance) { return key(infoLessonInstance.getLessonInstance().getLesson()); } private String key(final InfoLessonInstanceAggregation infoLessonInstanceAggregation) { return infoLessonInstanceAggregation.getShift().getExecutionCourse().getExternalId(); } private String key(final InfoWrittenEvaluation infoWrittenEvaluation) { final StringBuilder stringBuilder = new StringBuilder(); final WrittenEvaluation writtenEvaluation = infoWrittenEvaluation.getWrittenEvaluation(); for (final ExecutionCourse executionCourse : sort(writtenEvaluation.getAssociatedExecutionCoursesSet())) { stringBuilder.append(executionCourse.getExternalId()); } return stringBuilder.toString(); } private SortedSet<ExecutionCourse> sort(final Set<ExecutionCourse> associatedExecutionCoursesSet) { final SortedSet<ExecutionCourse> result = new TreeSet<ExecutionCourse>(DomainObjectUtil.COMPARATOR_BY_ID); result.addAll(associatedExecutionCoursesSet); return result; } }
cfscosta/fenix
src/main/java/org/fenixedu/academic/servlet/taglib/sop/v3/colorPickers/ClassTimeTableColorPicker.java
Java
lgpl-3.0
3,615
/* * 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.facebook.presto.spi.block; import com.facebook.presto.spi.type.Type; import io.airlift.slice.DynamicSliceOutput; import io.airlift.slice.Slice; import io.airlift.slice.SliceOutput; import org.openjdk.jol.info.ClassLayout; import static java.util.Objects.requireNonNull; public class ArrayBlockBuilder extends AbstractArrayBlock implements BlockBuilder { private static final int INSTANCE_SIZE = ClassLayout.parseClass(ArrayBlockBuilder.class).instanceSize() + BlockBuilderStatus.INSTANCE_SIZE; private final BlockBuilderStatus blockBuilderStatus; private final BlockBuilder values; private final SliceOutput offsets; private final SliceOutput valueIsNull; private static final int OFFSET_BASE = 0; private int currentEntrySize; /** * Caller of this constructor is responsible for making sure `valuesBlock` is constructed with the same `blockBuilderStatus` as the one in the argument */ public ArrayBlockBuilder(BlockBuilder valuesBlock, BlockBuilderStatus blockBuilderStatus, int expectedEntries) { this( blockBuilderStatus, valuesBlock, new DynamicSliceOutput(expectedEntries * 4), new DynamicSliceOutput(expectedEntries)); } public ArrayBlockBuilder(Type elementType, BlockBuilderStatus blockBuilderStatus, int expectedEntries, int expectedBytesPerEntry) { this( blockBuilderStatus, elementType.createBlockBuilder(blockBuilderStatus, expectedEntries, expectedBytesPerEntry), new DynamicSliceOutput(expectedEntries * 4), new DynamicSliceOutput(expectedEntries)); } public ArrayBlockBuilder(Type elementType, BlockBuilderStatus blockBuilderStatus, int expectedEntries) { this( blockBuilderStatus, elementType.createBlockBuilder(blockBuilderStatus, expectedEntries), new DynamicSliceOutput(expectedEntries * 4), new DynamicSliceOutput(expectedEntries)); } /** * Caller of this private constructor is responsible for making sure `values` is constructed with the same `blockBuilderStatus` as the one in the argument */ private ArrayBlockBuilder(BlockBuilderStatus blockBuilderStatus, BlockBuilder values, SliceOutput offsets, SliceOutput valueIsNull) { this.blockBuilderStatus = requireNonNull(blockBuilderStatus, "blockBuilderStatus is null"); this.values = requireNonNull(values, "values is null"); this.offsets = requireNonNull(offsets, "offset is null"); this.valueIsNull = requireNonNull(valueIsNull); } @Override public int getPositionCount() { return valueIsNull.size(); } @Override public int getSizeInBytes() { return values.getSizeInBytes() + offsets.size() + valueIsNull.size(); } @Override public int getRetainedSizeInBytes() { return INSTANCE_SIZE + values.getRetainedSizeInBytes() + offsets.getRetainedSize() + valueIsNull.getRetainedSize(); } @Override protected Block getValues() { return values; } @Override protected Slice getOffsets() { return offsets.getUnderlyingSlice(); } @Override protected int getOffsetBase() { return OFFSET_BASE; } @Override protected Slice getValueIsNull() { return valueIsNull.getUnderlyingSlice(); } @Override public void assureLoaded() { } @Override public BlockBuilder writeByte(int value) { throw new UnsupportedOperationException(); } @Override public BlockBuilder writeShort(int value) { throw new UnsupportedOperationException(); } @Override public BlockBuilder writeInt(int value) { throw new UnsupportedOperationException(); } @Override public BlockBuilder writeLong(long value) { throw new UnsupportedOperationException(); } @Override public BlockBuilder writeFloat(float value) { throw new UnsupportedOperationException(); } @Override public BlockBuilder writeDouble(double value) { throw new UnsupportedOperationException(); } @Override public BlockBuilder writeBytes(Slice source, int sourceIndex, int length) { throw new UnsupportedOperationException(); } @Override public BlockBuilder writeObject(Object value) { if (currentEntrySize != 0) { throw new IllegalStateException("Expected entry size to be exactly " + 0 + " but was " + currentEntrySize); } Block block = (Block) value; for (int i = 0; i < block.getPositionCount(); i++) { if (block.isNull(i)) { values.appendNull(); } else { block.writePositionTo(i, values); values.closeEntry(); } } currentEntrySize++; return this; } @Override public ArrayElementBlockWriter beginBlockEntry() { if (currentEntrySize != 0) { throw new IllegalStateException("Expected current entry size to be exactly 0 but was " + currentEntrySize); } currentEntrySize++; return new ArrayElementBlockWriter(values, values.getPositionCount()); } @Override public BlockBuilder closeEntry() { if (currentEntrySize != 1) { throw new IllegalStateException("Expected entry size to be exactly 1 but was " + currentEntrySize); } entryAdded(false); currentEntrySize = 0; return this; } @Override public BlockBuilder appendNull() { if (currentEntrySize > 0) { throw new IllegalStateException("Current entry must be closed before a null can be written"); } entryAdded(true); return this; } private void entryAdded(boolean isNull) { offsets.appendInt(values.getPositionCount()); valueIsNull.appendByte(isNull ? 1 : 0); blockBuilderStatus.addBytes(Integer.BYTES + Byte.BYTES); } @Override public ArrayBlock build() { if (currentEntrySize > 0) { throw new IllegalStateException("Current entry must be closed before the block can be built"); } return new ArrayBlock(values.build(), offsets.slice(), OFFSET_BASE, valueIsNull.slice()); } @Override public String toString() { StringBuilder sb = new StringBuilder("ArrayBlockBuilder{"); sb.append("positionCount=").append(getPositionCount()); sb.append('}'); return sb.toString(); } }
sunchao/presto
presto-spi/src/main/java/com/facebook/presto/spi/block/ArrayBlockBuilder.java
Java
apache-2.0
7,336
/* * 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.facebook.presto; import com.facebook.presto.execution.TaskId; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableMap; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import static com.google.common.base.MoreObjects.toStringHelper; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static java.util.Objects.requireNonNull; public final class OutputBuffers { public static final int BROADCAST_PARTITION_ID = 0; public static final OutputBuffers INITIAL_EMPTY_OUTPUT_BUFFERS = new OutputBuffers(0, false, ImmutableMap.<TaskId, Integer>of()); private final long version; private final boolean noMoreBufferIds; private final Map<TaskId, Integer> buffers; // Visible only for Jackson... Use the "with" methods instead @JsonCreator public OutputBuffers( @JsonProperty("version") long version, @JsonProperty("noMoreBufferIds") boolean noMoreBufferIds, @JsonProperty("buffers") Map<TaskId, Integer> buffers) { this.version = version; this.buffers = ImmutableMap.copyOf(requireNonNull(buffers, "buffers is null")); this.noMoreBufferIds = noMoreBufferIds; } @JsonProperty public long getVersion() { return version; } @JsonProperty public boolean isNoMoreBufferIds() { return noMoreBufferIds; } @JsonProperty public Map<TaskId, Integer> getBuffers() { return buffers; } public void checkValidTransition(OutputBuffers newOutputBuffers) { requireNonNull(newOutputBuffers, "newOutputBuffers is null"); if (version > newOutputBuffers.version) { throw new IllegalArgumentException("newOutputBuffers version is older"); } if (version == newOutputBuffers.version) { checkArgument(this.equals(newOutputBuffers), "newOutputBuffers is the same version but contains different information"); } // assure we are not removing the no more buffers flag if (noMoreBufferIds && !newOutputBuffers.noMoreBufferIds) { throw new IllegalArgumentException("Expected newOutputBuffers to have noMoreBufferIds set"); } // assure we have not changed the buffer assignments for (Entry<TaskId, Integer> entry : buffers.entrySet()) { if (!entry.getValue().equals(newOutputBuffers.buffers.get(entry.getKey()))) { throw new IllegalArgumentException("newOutputBuffers has changed the assignment for task " + entry.getKey()); } } } @Override public int hashCode() { return Objects.hash(version, noMoreBufferIds, buffers); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } final OutputBuffers other = (OutputBuffers) obj; return Objects.equals(this.version, other.version) && Objects.equals(this.noMoreBufferIds, other.noMoreBufferIds) && Objects.equals(this.buffers, other.buffers); } @Override public String toString() { return toStringHelper(this) .add("version", version) .add("noMoreBufferIds", noMoreBufferIds) .add("bufferIds", buffers) .toString(); } public OutputBuffers withBuffer(TaskId bufferId, int partition) { requireNonNull(bufferId, "bufferId is null"); if (buffers.containsKey(bufferId)) { checkHasBuffer(bufferId, partition); return this; } // verify no new buffers is not set checkState(!noMoreBufferIds, "No more buffer ids already set"); return new OutputBuffers( version + 1, false, ImmutableMap.<TaskId, Integer>builder() .putAll(buffers) .put(bufferId, partition) .build()); } public OutputBuffers withBuffers(Map<TaskId, Integer> buffers) { requireNonNull(buffers, "buffers is null"); Map<TaskId, Integer> newBuffers = new HashMap<>(); for (Entry<TaskId, Integer> entry : buffers.entrySet()) { TaskId bufferId = entry.getKey(); int partition = entry.getValue(); // it is ok to have a duplicate buffer declaration but it must have the same page partition if (this.buffers.containsKey(bufferId)) { checkHasBuffer(bufferId, partition); continue; } newBuffers.put(bufferId, partition); } // if we don't have new buffers, don't update if (newBuffers.isEmpty()) { return this; } // verify no new buffers is not set checkState(!noMoreBufferIds, "No more buffer ids already set"); // add the existing buffers newBuffers.putAll(this.buffers); return new OutputBuffers(version + 1, false, newBuffers); } public OutputBuffers withNoMoreBufferIds() { if (noMoreBufferIds) { return this; } return new OutputBuffers(version + 1, true, buffers); } private void checkHasBuffer(TaskId bufferId, int partition) { checkArgument(Objects.equals(buffers.get(bufferId), partition), "OutputBuffers already contains task %s, but partition is set to %s not %s", bufferId, buffers.get(bufferId), partition); } }
ipros-team/presto
presto-main/src/main/java/com/facebook/presto/OutputBuffers.java
Java
apache-2.0
6,445
/** * Copyright The Apache Software Foundation * * 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.hbase.master; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.io.IOException; import java.util.List; import java.util.Map; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.MediumTests; import org.apache.hadoop.hbase.MiniHBaseCluster; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.zookeeper.ZKAssign; import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher; import org.apache.zookeeper.KeeperException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; /** * Test cases for master to recover from ZK session expiry. */ @Category(MediumTests.class) public class TestMasterZKSessionRecovery { private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility(); /** * The default timeout is 5 minutes. * Shorten it so that the test won't wait for too long. */ static { Configuration conf = TEST_UTIL.getConfiguration(); conf.setLong("hbase.master.zksession.recover.timeout", 50000); conf.setClass(HConstants.HBASE_MASTER_LOADBALANCER_CLASS, MockLoadBalancer.class, LoadBalancer.class); } @Before public void setUp() throws Exception { // Start a cluster of one regionserver. TEST_UTIL.startMiniCluster(1); } @After public void tearDown() throws Exception { TEST_UTIL.shutdownMiniCluster(); } /** * Tests that the master does not call retainAssignment after recovery from * expired zookeeper session. Without the HBASE-6046 fix master always tries * to assign all the user regions by calling retainAssignment. */ @Test public void testRegionAssignmentAfterMasterRecoveryDueToZKExpiry() throws Exception { MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster(); cluster.startRegionServer(); HMaster m = cluster.getMaster(); ZooKeeperWatcher zkw = m.getZooKeeperWatcher(); int expectedNumOfListeners = zkw.getNumberOfListeners(); // now the cluster is up. So assign some regions. HBaseAdmin admin = new HBaseAdmin(TEST_UTIL.getConfiguration()); byte[][] SPLIT_KEYS = new byte[][] { Bytes.toBytes("a"), Bytes.toBytes("b"), Bytes.toBytes("c"), Bytes.toBytes("d"), Bytes.toBytes("e"), Bytes.toBytes("f"), Bytes.toBytes("g"), Bytes.toBytes("h"), Bytes.toBytes("i"), Bytes.toBytes("j") }; String tableName = "testRegionAssignmentAfterMasterRecoveryDueToZKExpiry"; admin.createTable(new HTableDescriptor(tableName), SPLIT_KEYS); ZooKeeperWatcher zooKeeperWatcher = HBaseTestingUtility.getZooKeeperWatcher(TEST_UTIL); ZKAssign.blockUntilNoRIT(zooKeeperWatcher); m.getZooKeeperWatcher().close(); MockLoadBalancer.retainAssignCalled = false; m.abort("Test recovery from zk session expired", new KeeperException.SessionExpiredException()); assertFalse(m.isStopped()); // The recovered master should not call retainAssignment, as it is not a // clean startup. assertFalse("Retain assignment should not be called", MockLoadBalancer.retainAssignCalled); // number of listeners should be same as the value before master aborted assertEquals(expectedNumOfListeners, zkw.getNumberOfListeners()); } static class MockLoadBalancer extends DefaultLoadBalancer { static boolean retainAssignCalled = false; @Override public Map<ServerName, List<HRegionInfo>> retainAssignment( Map<HRegionInfo, ServerName> regions, List<ServerName> servers) { retainAssignCalled = true; return super.retainAssignment(regions, servers); } } /** * Tests whether the logs are split when master recovers from a expired * zookeeper session and an RS goes down. */ @Test(timeout = 60000) public void testLogSplittingAfterMasterRecoveryDueToZKExpiry() throws IOException, KeeperException, InterruptedException { MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster(); cluster.startRegionServer(); HMaster m = cluster.getMaster(); // now the cluster is up. So assign some regions. HBaseAdmin admin = new HBaseAdmin(TEST_UTIL.getConfiguration()); byte[][] SPLIT_KEYS = new byte[][] { Bytes.toBytes("1"), Bytes.toBytes("2"), Bytes.toBytes("3"), Bytes.toBytes("4"), Bytes.toBytes("5") }; String tableName = "testLogSplittingAfterMasterRecoveryDueToZKExpiry"; HTableDescriptor htd = new HTableDescriptor(tableName); HColumnDescriptor hcd = new HColumnDescriptor("col"); htd.addFamily(hcd); admin.createTable(htd, SPLIT_KEYS); ZooKeeperWatcher zooKeeperWatcher = HBaseTestingUtility.getZooKeeperWatcher(TEST_UTIL); ZKAssign.blockUntilNoRIT(zooKeeperWatcher); HTable table = new HTable(TEST_UTIL.getConfiguration(), tableName); Put p = null; int numberOfPuts = 0; for (numberOfPuts = 0; numberOfPuts < 6; numberOfPuts++) { p = new Put(Bytes.toBytes(numberOfPuts)); p.add(Bytes.toBytes("col"), Bytes.toBytes("ql"), Bytes.toBytes("value" + numberOfPuts)); table.put(p); } m.getZooKeeperWatcher().close(); m.abort("Test recovery from zk session expired", new KeeperException.SessionExpiredException()); assertFalse(m.isStopped()); cluster.getRegionServer(0).abort("Aborting"); // Without patch for HBASE-6046 this test case will always timeout // with patch the test case should pass. Scan scan = new Scan(); int numberOfRows = 0; ResultScanner scanner = table.getScanner(scan); Result[] result = scanner.next(1); while (result != null && result.length > 0) { numberOfRows++; result = scanner.next(1); } assertEquals("Number of rows should be equal to number of puts.", numberOfPuts, numberOfRows); } }
zqxjjj/NobidaBase
target/hbase-0.94.9/hbase-0.94.9/src/test/java/org/apache/hadoop/hbase/master/TestMasterZKSessionRecovery.java
Java
apache-2.0
7,201
/** * 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.component.rest.springboot; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Generated; import org.apache.camel.CamelContext; import org.apache.camel.component.rest.RestComponent; import org.apache.camel.spi.ComponentCustomizer; import org.apache.camel.spi.HasId; import org.apache.camel.spring.boot.CamelAutoConfiguration; import org.apache.camel.spring.boot.ComponentConfigurationProperties; import org.apache.camel.spring.boot.util.CamelPropertiesHelper; import org.apache.camel.spring.boot.util.ConditionalOnCamelContextAndAutoConfigurationBeans; import org.apache.camel.spring.boot.util.GroupCondition; import org.apache.camel.spring.boot.util.HierarchicalPropertiesEvaluator; import org.apache.camel.util.IntrospectionSupport; import org.apache.camel.util.ObjectHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; /** * Generated by camel-package-maven-plugin - do not edit this file! */ @Generated("org.apache.camel.maven.packaging.SpringBootAutoConfigurationMojo") @Configuration @Conditional({ConditionalOnCamelContextAndAutoConfigurationBeans.class, RestComponentAutoConfiguration.GroupConditions.class}) @AutoConfigureAfter(CamelAutoConfiguration.class) @EnableConfigurationProperties({ComponentConfigurationProperties.class, RestComponentConfiguration.class}) public class RestComponentAutoConfiguration { private static final Logger LOGGER = LoggerFactory .getLogger(RestComponentAutoConfiguration.class); @Autowired private ApplicationContext applicationContext; @Autowired private CamelContext camelContext; @Autowired private RestComponentConfiguration configuration; @Autowired(required = false) private List<ComponentCustomizer<RestComponent>> customizers; static class GroupConditions extends GroupCondition { public GroupConditions() { super("camel.component", "camel.component.rest"); } } @Lazy @Bean(name = "rest-component") @ConditionalOnMissingBean(RestComponent.class) public RestComponent configureRestComponent() throws Exception { RestComponent component = new RestComponent(); component.setCamelContext(camelContext); Map<String, Object> parameters = new HashMap<>(); IntrospectionSupport.getProperties(configuration, parameters, null, false); for (Map.Entry<String, Object> entry : parameters.entrySet()) { Object value = entry.getValue(); Class<?> paramClass = value.getClass(); if (paramClass.getName().endsWith("NestedConfiguration")) { Class nestedClass = null; try { nestedClass = (Class) paramClass.getDeclaredField( "CAMEL_NESTED_CLASS").get(null); HashMap<String, Object> nestedParameters = new HashMap<>(); IntrospectionSupport.getProperties(value, nestedParameters, null, false); Object nestedProperty = nestedClass.newInstance(); CamelPropertiesHelper.setCamelProperties(camelContext, nestedProperty, nestedParameters, false); entry.setValue(nestedProperty); } catch (NoSuchFieldException e) { } } } CamelPropertiesHelper.setCamelProperties(camelContext, component, parameters, false); if (ObjectHelper.isNotEmpty(customizers)) { for (ComponentCustomizer<RestComponent> customizer : customizers) { boolean useCustomizer = (customizer instanceof HasId) ? HierarchicalPropertiesEvaluator.evaluate( applicationContext.getEnvironment(), "camel.component.customizer", "camel.component.rest.customizer", ((HasId) customizer).getId()) : HierarchicalPropertiesEvaluator.evaluate( applicationContext.getEnvironment(), "camel.component.customizer", "camel.component.rest.customizer"); if (useCustomizer) { LOGGER.debug("Configure component {}, with customizer {}", component, customizer); customizer.customize(component); } } } return component; } }
curso007/camel
platforms/spring-boot/components-starter/camel-core-starter/src/main/java/org/apache/camel/component/rest/springboot/RestComponentAutoConfiguration.java
Java
apache-2.0
6,081
/** * 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.tez.runtime.library.conf; import javax.annotation.Nullable; import java.util.Map; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.tez.dag.api.UserPayload; @InterfaceAudience.Private abstract class HadoopKeyValuesBasedBaseEdgeConfig { /** * Get the payload for the configured Output * @return output configuration as a byte array */ public abstract UserPayload getOutputPayload(); /** * Get the output class name * @return the output class name */ public abstract String getOutputClassName(); /** * Get the payload for the configured Input * @return input configuration as a byte array */ public abstract UserPayload getInputPayload(); /** * Get the history text for the configured Output * @return output configuration as a string in json format */ public abstract String getOutputHistoryText(); /** * Get the history text for the configured Input * @return input configuration as a string in json format */ public abstract String getInputHistoryText(); /** * Get the input class name * @return the input class name */ public abstract String getInputClassName(); public abstract static class Builder<T extends Builder<T>> implements BaseConfigBuilder<T> { /** * Enable compression for the specific Input / Output / Edge * * @param enabled whether to enable compression or not * @param compressionCodec the codec to be used if compression is enabled. null implies using * the default * @param codecConf the codec configuration. This can be null, and is a {@link * java.util.Map} of key-value pairs. The keys should be limited to * the ones required by the comparator. * @return instance of the current builder */ public abstract T setCompression(boolean enabled, @Nullable String compressionCodec, @Nullable Map<String, String> codecConf); } }
amirsojoodi/tez
tez-runtime-library/src/main/java/org/apache/tez/runtime/library/conf/HadoopKeyValuesBasedBaseEdgeConfig.java
Java
apache-2.0
2,870
package org.nutz.mvc.view; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.nutz.lang.Files; import org.nutz.lang.Lang; import org.nutz.lang.Strings; import org.nutz.mvc.Mvcs; /** * 内部重定向视图 * <p/> * 根据传入的视图名,决定视图的路径: * <ul> * <li>如果视图名以 '/' 开头, 则被认为是一个 全路径 * <li>否则,将视图名中的 '.' 转换成 '/',并加入前缀 "/WEB-INF/" * </ul> * 通过注解映射的例子: * <ul> * <li>'@Ok("forward:abc.cbc")' => /WEB-INF/abc/cbc * <li>'@Ok("forward:/abc/cbc")' => /abc/cbc * <li>'@Ok("forward:/abc/cbc.jsp")' => /abc/cbc.jsp * </ul> * * @author mawm([email protected]) * @author zozoh([email protected]) * @author wendal([email protected]) */ public class ForwardView extends AbstractPathView { public ForwardView(String dest) { super(dest == null ? null : dest.replace('\\', '/')); } public void render(HttpServletRequest req, HttpServletResponse resp, Object obj) throws Exception { String path = evalPath(req, obj); String args = ""; if (path != null && path.contains("?")) { //将参数部分分解出来 args = path.substring(path.indexOf('?')); path = path.substring(0, path.indexOf('?')); } String ext = getExt(); // 空路径,采用默认规则 if (Strings.isBlank(path)) { path = Mvcs.getRequestPath(req); path = "/WEB-INF" + (path.startsWith("/") ? "" : "/") + Files.renameSuffix(path, ext); } // 绝对路径 : 以 '/' 开头的路径不增加 '/WEB-INF' else if (path.charAt(0) == '/') { if (!path.toLowerCase().endsWith(ext)) path += ext; } // 包名形式的路径 else { path = "/WEB-INF/" + path.replace('.', '/') + ext; } // 执行 Forward path = path + args; RequestDispatcher rd = req.getRequestDispatcher(path); if (rd == null) throw Lang.makeThrow("Fail to find Forward '%s'", path); // Do rendering rd.forward(req, resp); } /** * 子类可以覆盖这个方法,给出自己特殊的后缀,必须小写哦 * * @return 后缀 */ protected String getExt() { return ""; } }
lzxz1234/nutz
src/org/nutz/mvc/view/ForwardView.java
Java
apache-2.0
2,585
/* MouseInfo.java -- utility methods for mice. Copyright (C) 2006 Free Software Foundation This file is part of GNU Classpath. GNU Classpath 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 2, or (at your option) any later version. GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package java.awt; import gnu.java.awt.ClasspathToolkit; import java.awt.peer.MouseInfoPeer; /** * MouseInfo is a class containing utility functions for mouse information. * * @author Sven de Marothy * @since 1.5 */ public class MouseInfo { private static MouseInfoPeer peer; /** * Returns a PointerInfo object containing information about the current * location of the mouse pointer * * @throws HeadlessException if the current GraphicsEnvironment is headless. * @return a PointerInfo object. */ public static PointerInfo getPointerInfo() throws HeadlessException { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPermission( new AWTPermission("watchMousePointer") ); if( GraphicsEnvironment.isHeadless() ) throw new HeadlessException(); if( peer == null ) peer = Toolkit.getDefaultToolkit().getMouseInfoPeer(); Point p = new Point(); int screen = peer.fillPointWithCoords( p ); GraphicsDevice[] gds = GraphicsEnvironment.getLocalGraphicsEnvironment(). getScreenDevices(); return new PointerInfo( gds[ screen ], p ); } /** * Returns the number of mouse buttons, or -1 if no mouse is connected. * (mentioned in the 1.5 release notes) * * @throws HeadlessException if the current GraphicsEnvironment is headless. * @return an integer number of buttons. */ public static int getNumberOfButtons() throws HeadlessException { if( GraphicsEnvironment.isHeadless() ) throw new HeadlessException(); return ((ClasspathToolkit)Toolkit.getDefaultToolkit()). getMouseNumberOfButtons(); } }
shaotuanchen/sunflower_exp
tools/source/gcc-4.2.4/libjava/classpath/java/awt/MouseInfo.java
Java
bsd-3-clause
3,403
/** * * CobaltActivity * Cobalt * * The MIT License (MIT) * * Copyright (c) 2014 Cobaltians * * 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 fr.cobaltians.cobalt.activities; import fr.cobaltians.cobalt.Cobalt; import fr.cobaltians.cobalt.R; import fr.cobaltians.cobalt.fragments.CobaltFragment; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.NavUtils; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.LinearLayout; import java.util.ArrayList; import java.util.HashMap; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * {@link Activity} containing a {@link CobaltFragment}. * @author Diane */ public abstract class CobaltActivity extends ActionBarActivity { protected static final String TAG = CobaltActivity.class.getSimpleName(); // NAVIGATION private boolean mAnimatedTransition; // Pop private static ArrayList<CobaltActivity> sActivitiesArrayList = new ArrayList<CobaltActivity>(); // Modal private boolean mWasPushedAsModal; private static boolean sWasPushedFromModal = false; // TODO: uncomment for Bars // ACTION BAR MENU ITEMS //private HashMap<Integer, String> mMenuItemsHashMap = new HashMap<Integer, String>(); /************************************************************************************************************************ * LIFECYCLE ************************************************************************************************************************/ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getLayoutToInflate()); sActivitiesArrayList.add(0, this); Bundle bundle = getIntent().getExtras(); Bundle extras = (bundle != null) ? bundle.getBundle(Cobalt.kExtras) : null; // TODO: uncomment for Bars /* if (extras != null && extras.containsKey(Cobalt.kBars)) { try { JSONObject actionBar = new JSONObject(extras.getString(Cobalt.kBars)); setupActionBar(actionBar); } catch (JSONException exception) { if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - onCreate: action bar configuration parsing failed. " + extras.getString(Cobalt.kBars)); exception.printStackTrace(); } } */ if (savedInstanceState == null) { CobaltFragment fragment = getFragment(); if (fragment != null) { if (bundle != null) { if (extras != null) fragment.setArguments(extras); mAnimatedTransition = bundle.getBoolean(Cobalt.kJSAnimated, true); if (mAnimatedTransition) { mWasPushedAsModal = bundle.getBoolean(Cobalt.kPushAsModal, false); if (mWasPushedAsModal) { sWasPushedFromModal = true; overridePendingTransition(R.anim.modal_open_enter, android.R.anim.fade_out); } else if (bundle.getBoolean(Cobalt.kPopAsModal, false)) { sWasPushedFromModal = false; overridePendingTransition(android.R.anim.fade_in, R.anim.modal_close_exit); } else if (sWasPushedFromModal) overridePendingTransition(R.anim.modal_push_enter, R.anim.modal_push_exit); } else overridePendingTransition(0, 0); } if (findViewById(getFragmentContainerId()) != null) { getSupportFragmentManager().beginTransaction().replace(getFragmentContainerId(), fragment).commit(); } else if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - onCreate: fragment container not found"); } else if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - onCreate: getFragment() returned null"); } } @Override protected void onStart() { super.onStart(); Cobalt.getInstance(getApplicationContext()).onActivityStarted(this); } public void onAppStarted() { Fragment fragment = getSupportFragmentManager().findFragmentById(getFragmentContainerId()); if (fragment != null && CobaltFragment.class.isAssignableFrom(fragment.getClass())) { ((CobaltFragment) fragment).sendEvent(Cobalt.JSEventOnAppStarted, null, null); } else if (Cobalt.DEBUG) Log.i(Cobalt.TAG, TAG + " - onAppStarted: no fragment container found \n" + " or fragment found is not an instance of CobaltFragment. \n" + "Drop onAppStarted event."); } public void onAppForeground() { Fragment fragment = getSupportFragmentManager().findFragmentById(getFragmentContainerId()); if (fragment != null && CobaltFragment.class.isAssignableFrom(fragment.getClass())) { ((CobaltFragment) fragment).sendEvent(Cobalt.JSEventOnAppForeground, null, null); } else if (Cobalt.DEBUG) Log.i(Cobalt.TAG, TAG + " - onAppForeground: no fragment container found \n" + " or fragment found is not an instance of CobaltFragment. \n" + "Drop onAppForeground event."); } @Override public void finish() { super.finish(); if (mAnimatedTransition) { if (mWasPushedAsModal) { sWasPushedFromModal = false; overridePendingTransition(android.R.anim.fade_in, R.anim.modal_close_exit); } else if (sWasPushedFromModal) overridePendingTransition(R.anim.modal_pop_enter, R.anim.modal_pop_exit); } else overridePendingTransition(0, 0); } @Override protected void onStop() { super.onStop(); Cobalt.getInstance(getApplicationContext()).onActivityStopped(this); } public void onAppBackground() { Fragment fragment = getSupportFragmentManager().findFragmentById(getFragmentContainerId()); if (fragment != null && CobaltFragment.class.isAssignableFrom(fragment.getClass())) { ((CobaltFragment) fragment).sendEvent(Cobalt.JSEventOnAppBackground, null, null); } else if (Cobalt.DEBUG) Log.i(Cobalt.TAG, TAG + " - onAppBackground: no fragment container found \n" + " or fragment found is not an instance of CobaltFragment. \n" + "Drop onAppBackground event."); } @Override protected void onDestroy() { super.onDestroy(); sActivitiesArrayList.remove(0); } /************************************************************************************************** * MENU **************************************************************************************************/ // TODO: uncomment for Bars /* @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); Bundle bundle = getIntent().getExtras(); Bundle extras = (bundle != null) ? bundle.getBundle(Cobalt.kExtras) : null; if (extras != null && extras.containsKey(Cobalt.kBars)) { try { JSONObject actionBar = new JSONObject(extras.getString(Cobalt.kBars)); JSONArray actions = actionBar.optJSONArray(Cobalt.kActions); if (actions != null) return setupOptionsMenu(menu, actions); } catch (JSONException exception) { if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - onCreate: action bar configuration parsing failed. " + extras.getString(Cobalt.kBars)); exception.printStackTrace(); } } return false; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (mMenuItemsHashMap.containsKey(item.getItemId())) { String name = mMenuItemsHashMap.get(item.getItemId()); Fragment fragment = getSupportFragmentManager().findFragmentById(getFragmentContainerId()); if (fragment != null && CobaltFragment.class.isAssignableFrom(fragment.getClass())) { try { JSONObject data = new JSONObject(); data.put(Cobalt.kJSAction, Cobalt.JSActionButtonPressed); data.put(Cobalt.kJSBarsButton, name); JSONObject message = new JSONObject(); message.put(Cobalt.kJSType, Cobalt.JSTypeUI); message.put(Cobalt.kJSUIControl, Cobalt.JSControlBars); message.put(Cobalt.kJSData, data); ((CobaltFragment) fragment).sendMessage(message); } catch(JSONException exception) { exception.printStackTrace(); } } else if (Cobalt.DEBUG) Log.i(Cobalt.TAG, TAG + " - onOptionsItemSelected: no fragment container found \n" + " or fragment found is not an instance of CobaltFragment. \n" + "Drop " + name + "bars button pressed event."); return true; } else return super.onOptionsItemSelected(item); } */ /*************************************************************************************************************************************************************** * COBALT ***************************************************************************************************************************************************************/ /********************************************* * Ui *********************************************/ /** * Returns a new instance of the contained fragment. * This method should be overridden in subclasses. * @return a new instance of the fragment contained. */ protected abstract CobaltFragment getFragment(); protected int getLayoutToInflate() { return R.layout.activity_cobalt; } public int getFragmentContainerId() { return R.id.fragment_container; } // TODO: uncomment for Bars /* private void setupActionBar(JSONObject configuration) { ActionBar actionBar = getSupportActionBar(); LinearLayout bottomActionBar = (LinearLayout) findViewById(R.id.bottom_actionbar); if (actionBar == null) { if (Cobalt.DEBUG) Log.w(Cobalt.TAG, TAG + "setupActionBar: activity does not have an action bar."); return; } // Reset actionBar.setLogo(null); actionBar.setDisplayShowHomeEnabled(false); actionBar.setTitle(null); actionBar.setDisplayShowTitleEnabled(false); bottomActionBar.setVisibility(View.GONE); // Color String backgroundColor = configuration.optString(Cobalt.kBackgroundColor); try { if (backgroundColor.length() == 0) throw new IllegalArgumentException(); int colorInt = Color.parseColor(backgroundColor); actionBar.setBackgroundDrawable(new ColorDrawable(colorInt)); bottomActionBar.setBackgroundColor(colorInt); } catch (IllegalArgumentException exception) { if (Cobalt.DEBUG) Log.w(Cobalt.TAG, TAG + "setupActionBar: backgroundColor " + backgroundColor + " format not supported, use #RRGGBB."); exception.printStackTrace(); } // Icon String icon = configuration.optString(Cobalt.kIcon); try { if (icon.length() == 0) throw new IllegalArgumentException(); String[] split = icon.split(":"); if (split.length != 2) throw new IllegalArgumentException(); int resId = getResources().getIdentifier(split[1], "drawable", split[0]); if (resId == 0) Log.w(Cobalt.TAG, TAG + "setupActionBar: androidIcon " + icon + " not found."); else { actionBar.setLogo(resId); actionBar.setDisplayShowHomeEnabled(true); } } catch (IllegalArgumentException exception) { if (Cobalt.DEBUG) Log.w(Cobalt.TAG, TAG + "setupActionBar: androidIcon " + icon + " format not supported, use com.example.app:icon."); exception.printStackTrace(); } // Title String title = configuration.optString(Cobalt.kTitle); if (title.length() != 0) { actionBar.setTitle(title); actionBar.setDisplayShowTitleEnabled(true); } else if (Cobalt.DEBUG) Log.w(Cobalt.TAG, TAG + "setupActionBar: title is empty."); // Visibility boolean visible = configuration.optBoolean(Cobalt.kVisible, true); if (visible) actionBar.show(); else actionBar.hide(); } private boolean setupOptionsMenu(Menu menu, JSONArray actions) { ActionBar actionBar = getSupportActionBar(); LinearLayout bottomActionBar = (LinearLayout) findViewById(R.id.bottom_actionbar); boolean showBottomActionBar = false; if (actionBar == null) { if (Cobalt.DEBUG) Log.w(Cobalt.TAG, TAG + "setupOptionsMenu: activity does not have an action bar."); return false; } int menuItemsAddedToTop = 0; int menuItemsAddedToOverflow = 0; int length = actions.length(); for (int i = 0; i < length; i++) { try { JSONObject action = actions.getJSONObject(i); final String name = action.getString(Cobalt.kName); String title = action.getString(Cobalt.kTitle); String icon = action.optString(Cobalt.kIcon); String position = action.optString(Cobalt.kPosition, Cobalt.kPositionTop); boolean visible = action.optBoolean(Cobalt.kVisible, true); MenuItem menuItem; String[] split; int resId; switch(position) { case Cobalt.kPositionTop: if (icon.length() == 0) throw new JSONException("Actions positionned at top or bottom must specify an icon attribute. Current: " + icon); split = icon.split(":"); if (split.length != 2) throw new JSONException("androidIcon " + icon + " format not supported, use com.example.app:icon."); resId = getResources().getIdentifier(split[1], "drawable", split[0]); if (resId == 0) throw new JSONException("androidIcon " + icon + " not found."); menuItem = menu.add(Menu.NONE, i, menuItemsAddedToTop++, title); menuItem.setIcon(resId); if (menuItemsAddedToTop > 2) MenuItemCompat.setShowAsAction(menuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM); else MenuItemCompat.setShowAsAction(menuItem, MenuItem.SHOW_AS_ACTION_ALWAYS); menuItem.setVisible(visible); mMenuItemsHashMap.put(i, name); break; case Cobalt.kPositionOverflow: menuItem = menu.add(Menu.NONE, i, menuItemsAddedToOverflow++, title); MenuItemCompat.setShowAsAction(menuItem, MenuItem.SHOW_AS_ACTION_NEVER); menuItem.setVisible(visible); mMenuItemsHashMap.put(i, name); break; case Cobalt.kPositionBottom: if (icon.length() == 0) throw new JSONException("Actions positionned at top or bottom must specify an icon attribute. Current: " + icon); split = icon.split(":"); if (split.length != 2) throw new JSONException("androidIcon " + icon + " format not supported, use com.example.app:icon."); resId = getResources().getIdentifier(split[1], "drawable", split[0]); if (resId == 0) throw new JSONException("androidIcon " + icon + " not found."); ImageButton button = new ImageButton(this); button.setImageResource(resId); // TODO: find best background to mimic default behavior button.setBackgroundResource(android.R.drawable.menuitem_background); //button.setBackgroundResource(R.drawable.menu_item_background_dark); ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, getResources().getDimensionPixelSize(R.dimen.bottom_actionbar_button_size)); button.setLayoutParams(layoutParams); int padding = getResources().getDimensionPixelSize(R.dimen.bottom_actionBar_button_padding); button.setPadding(padding, padding, padding, padding); // TODO: add accessibility tooltip //if (title != null) button.setContentDescription(title); if (visible) { button.setVisibility(View.VISIBLE); showBottomActionBar = true; } else button.setVisibility(View.GONE); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Fragment fragment = getSupportFragmentManager().findFragmentById(getFragmentContainerId()); if (fragment != null && CobaltFragment.class.isAssignableFrom(fragment.getClass())) { try { JSONObject data = new JSONObject(); data.put(Cobalt.kJSAction, Cobalt.JSActionButtonPressed); data.put(Cobalt.kJSBarsButton, name); JSONObject message = new JSONObject(); message.put(Cobalt.kJSType, Cobalt.JSTypeUI); message.put(Cobalt.kJSUIControl, Cobalt.JSControlBars); message.put(Cobalt.kJSData, data); ((CobaltFragment) fragment).sendMessage(message); } catch(JSONException exception) { exception.printStackTrace(); } } else if (Cobalt.DEBUG) Log.i(Cobalt.TAG, TAG + " - onBarsButtonClick: no fragment container found \n" + " or fragment found is not an instance of CobaltFragment. \n" + "Drop " + name + "bars button pressed event."); } }); bottomActionBar.addView(button); break; default: throw new JSONException("androidPosition attribute must be top, overflow or bottom."); } } catch (JSONException exception) { if (Cobalt.DEBUG) Log.w(Cobalt.TAG, TAG + "setupActionBar: actions " + actions.toString() + " format not supported, use at least {\n" + "\tname: \"name\",\n" + "\ttitle: \"title\",\n" + "}"); exception.printStackTrace(); } } if (actionBar.isShowing() && showBottomActionBar) bottomActionBar.setVisibility(View.VISIBLE); // true to display menu return true; } */ /********************************************************************************************** * Back **********************************************************************************************/ /** * Called when back button is pressed. * This method should NOT be overridden in subclasses. */ @Override public void onBackPressed() { Fragment fragment = getSupportFragmentManager().findFragmentById(getFragmentContainerId()); if (fragment != null && CobaltFragment.class.isAssignableFrom(fragment.getClass())) { ((CobaltFragment) fragment).askWebViewForBackPermission(); } else { super.onBackPressed(); if (Cobalt.DEBUG) Log.i(Cobalt.TAG, TAG + " - onBackPressed: no fragment container found \n" + " or fragment found is not an instance of CobaltFragment. \n" + "Call super.onBackPressed()"); } } /** * Called from the contained {@link CobaltFragment} when the Web view has authorized the back event. * This method should NOT be overridden in subclasses. */ public void back() { runOnUiThread(new Runnable() { @Override public void run() { backWithSuper(); } }); } private void backWithSuper() { super.onBackPressed(); } /********************************************************************************************************************* * Web Layer dismiss *********************************************************************************************************************/ /** * Called when a {@link CobaltWebLayerFragment} has been dismissed. * This method may be overridden in subclasses. */ public void onWebLayerDismiss(String page, JSONObject data) { CobaltFragment fragment = (CobaltFragment) getSupportFragmentManager().findFragmentById(getFragmentContainerId()); if (fragment != null) { fragment.onWebLayerDismiss(page, data); } else if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - onWebLayerDismiss: no fragment container found"); } public void popTo(String controller, String page){ Intent intent = Cobalt.getInstance(this).getIntentForController(controller, page); if (intent != null) { Bundle bundleNewActivity = intent.getBundleExtra(Cobalt.kExtras); String newActivity = bundleNewActivity.getString(Cobalt.kActivity); ArrayList<CobaltActivity> activityToFinish = new ArrayList<CobaltActivity>(); Boolean foundPage = false; int maxPageId = -1; int oldPageId = -1; for (int i = 0; i < sActivitiesArrayList.size(); i++) { CobaltActivity activity = sActivitiesArrayList.get(i); Intent intentStack = activity.getIntent(); if (!intentStack.hasCategory(Intent.CATEGORY_LAUNCHER)) { Bundle bundle = intentStack.getBundleExtra(Cobalt.kExtras); String oldActivity = bundle.getString(Cobalt.kActivity); if (newActivity.equals(oldActivity)) { maxPageId = i; String oldPage = bundle.getString(Cobalt.kPage); if (oldPage.equals(page)) { foundPage = true; oldPageId = i; } } } } if (!foundPage) this.startActivity(intent); else { if (maxPageId == oldPageId) { for (int index = 0; index <= maxPageId ; index++) { activityToFinish.add(sActivitiesArrayList.get(index)); } this.startActivity(intent); for (CobaltActivity activity : activityToFinish) { activity.finish(); } } else { intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); NavUtils.navigateUpTo(this, intent); } } } else if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - push: Unable to push " + controller + " controller"); } }
cobaltians/Hackathon
HackAton8/cobalt/src/main/java/fr/cobaltians/cobalt/activities/CobaltActivity.java
Java
mit
26,073
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ */ package java.util.concurrent; import java.io.ObjectStreamField; import java.util.Random; import java.util.Spliterator; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.function.DoubleConsumer; import java.util.function.IntConsumer; import java.util.function.LongConsumer; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.StreamSupport; /** * A random number generator isolated to the current thread. Like the * global {@link java.util.Random} generator used by the {@link * java.lang.Math} class, a {@code ThreadLocalRandom} is initialized * with an internally generated seed that may not otherwise be * modified. When applicable, use of {@code ThreadLocalRandom} rather * than shared {@code Random} objects in concurrent programs will * typically encounter much less overhead and contention. Use of * {@code ThreadLocalRandom} is particularly appropriate when multiple * tasks (for example, each a {@link ForkJoinTask}) use random numbers * in parallel in thread pools. * * <p>Usages of this class should typically be of the form: * {@code ThreadLocalRandom.current().nextX(...)} (where * {@code X} is {@code Int}, {@code Long}, etc). * When all usages are of this form, it is never possible to * accidently share a {@code ThreadLocalRandom} across multiple threads. * * <p>This class also provides additional commonly used bounded random * generation methods. * * <p>Instances of {@code ThreadLocalRandom} are not cryptographically * secure. Consider instead using {@link java.security.SecureRandom} * in security-sensitive applications. Additionally, * default-constructed instances do not use a cryptographically random * seed unless the {@linkplain System#getProperty system property} * {@code java.util.secureRandomSeed} is set to {@code true}. * * @since 1.7 * @author Doug Lea */ public class ThreadLocalRandom extends Random { /* * This class implements the java.util.Random API (and subclasses * Random) using a single static instance that accesses random * number state held in class Thread (primarily, field * threadLocalRandomSeed). In doing so, it also provides a home * for managing package-private utilities that rely on exactly the * same state as needed to maintain the ThreadLocalRandom * instances. We leverage the need for an initialization flag * field to also use it as a "probe" -- a self-adjusting thread * hash used for contention avoidance, as well as a secondary * simpler (xorShift) random seed that is conservatively used to * avoid otherwise surprising users by hijacking the * ThreadLocalRandom sequence. The dual use is a marriage of * convenience, but is a simple and efficient way of reducing * application-level overhead and footprint of most concurrent * programs. * * Even though this class subclasses java.util.Random, it uses the * same basic algorithm as java.util.SplittableRandom. (See its * internal documentation for explanations, which are not repeated * here.) Because ThreadLocalRandoms are not splittable * though, we use only a single 64bit gamma. * * Because this class is in a different package than class Thread, * field access methods use Unsafe to bypass access control rules. * To conform to the requirements of the Random superclass * constructor, the common static ThreadLocalRandom maintains an * "initialized" field for the sake of rejecting user calls to * setSeed while still allowing a call from constructor. Note * that serialization is completely unnecessary because there is * only a static singleton. But we generate a serial form * containing "rnd" and "initialized" fields to ensure * compatibility across versions. * * Implementations of non-core methods are mostly the same as in * SplittableRandom, that were in part derived from a previous * version of this class. * * The nextLocalGaussian ThreadLocal supports the very rarely used * nextGaussian method by providing a holder for the second of a * pair of them. As is true for the base class version of this * method, this time/space tradeoff is probably never worthwhile, * but we provide identical statistical properties. */ /** Generates per-thread initialization/probe field */ private static final AtomicInteger probeGenerator = new AtomicInteger(); /** * The next seed for default constructors. */ private static final AtomicLong seeder = new AtomicLong(initialSeed()); private static long initialSeed() { String pp = java.security.AccessController.doPrivileged( new sun.security.action.GetPropertyAction( "java.util.secureRandomSeed")); if (pp != null && pp.equalsIgnoreCase("true")) { byte[] seedBytes = java.security.SecureRandom.getSeed(8); long s = (long)(seedBytes[0]) & 0xffL; for (int i = 1; i < 8; ++i) s = (s << 8) | ((long)(seedBytes[i]) & 0xffL); return s; } return (mix64(System.currentTimeMillis()) ^ mix64(System.nanoTime())); } /** * The seed increment */ private static final long GAMMA = 0x9e3779b97f4a7c15L; /** * The increment for generating probe values */ private static final int PROBE_INCREMENT = 0x9e3779b9; /** * The increment of seeder per new instance */ private static final long SEEDER_INCREMENT = 0xbb67ae8584caa73bL; // Constants from SplittableRandom private static final double DOUBLE_UNIT = 0x1.0p-53; // 1.0 / (1L << 53) private static final float FLOAT_UNIT = 0x1.0p-24f; // 1.0f / (1 << 24) /** Rarely-used holder for the second of a pair of Gaussians */ private static final ThreadLocal<Double> nextLocalGaussian = new ThreadLocal<Double>(); private static long mix64(long z) { z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL; z = (z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L; return z ^ (z >>> 33); } private static int mix32(long z) { z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL; return (int)(((z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L) >>> 32); } /** * Field used only during singleton initialization. * True when constructor completes. */ boolean initialized; /** Constructor used only for static singleton */ private ThreadLocalRandom() { initialized = true; // false during super() call } /** The common ThreadLocalRandom */ static final ThreadLocalRandom instance = new ThreadLocalRandom(); /** * Initialize Thread fields for the current thread. Called only * when Thread.threadLocalRandomProbe is zero, indicating that a * thread local seed value needs to be generated. Note that even * though the initialization is purely thread-local, we need to * rely on (static) atomic generators to initialize the values. */ static final void localInit() { int p = probeGenerator.addAndGet(PROBE_INCREMENT); int probe = (p == 0) ? 1 : p; // skip 0 long seed = mix64(seeder.getAndAdd(SEEDER_INCREMENT)); Thread t = Thread.currentThread(); UNSAFE.putLong(t, SEED, seed); UNSAFE.putInt(t, PROBE, probe); } /** * Returns the current thread's {@code ThreadLocalRandom}. * * @return the current thread's {@code ThreadLocalRandom} */ public static ThreadLocalRandom current() { if (UNSAFE.getInt(Thread.currentThread(), PROBE) == 0) localInit(); return instance; } /** * Throws {@code UnsupportedOperationException}. Setting seeds in * this generator is not supported. * * @throws UnsupportedOperationException always */ public void setSeed(long seed) { // only allow call from super() constructor if (initialized) throw new UnsupportedOperationException(); } final long nextSeed() { Thread t; long r; // read and update per-thread seed UNSAFE.putLong(t = Thread.currentThread(), SEED, r = UNSAFE.getLong(t, SEED) + GAMMA); return r; } // We must define this, but never use it. protected int next(int bits) { return (int)(mix64(nextSeed()) >>> (64 - bits)); } // IllegalArgumentException messages static final String BadBound = "bound must be positive"; static final String BadRange = "bound must be greater than origin"; static final String BadSize = "size must be non-negative"; /** * The form of nextLong used by LongStream Spliterators. If * origin is greater than bound, acts as unbounded form of * nextLong, else as bounded form. * * @param origin the least value, unless greater than bound * @param bound the upper bound (exclusive), must not equal origin * @return a pseudorandom value */ final long internalNextLong(long origin, long bound) { long r = mix64(nextSeed()); if (origin < bound) { long n = bound - origin, m = n - 1; if ((n & m) == 0L) // power of two r = (r & m) + origin; else if (n > 0L) { // reject over-represented candidates for (long u = r >>> 1; // ensure nonnegative u + m - (r = u % n) < 0L; // rejection check u = mix64(nextSeed()) >>> 1) // retry ; r += origin; } else { // range not representable as long while (r < origin || r >= bound) r = mix64(nextSeed()); } } return r; } /** * The form of nextInt used by IntStream Spliterators. * Exactly the same as long version, except for types. * * @param origin the least value, unless greater than bound * @param bound the upper bound (exclusive), must not equal origin * @return a pseudorandom value */ final int internalNextInt(int origin, int bound) { int r = mix32(nextSeed()); if (origin < bound) { int n = bound - origin, m = n - 1; if ((n & m) == 0) r = (r & m) + origin; else if (n > 0) { for (int u = r >>> 1; u + m - (r = u % n) < 0; u = mix32(nextSeed()) >>> 1) ; r += origin; } else { while (r < origin || r >= bound) r = mix32(nextSeed()); } } return r; } /** * The form of nextDouble used by DoubleStream Spliterators. * * @param origin the least value, unless greater than bound * @param bound the upper bound (exclusive), must not equal origin * @return a pseudorandom value */ final double internalNextDouble(double origin, double bound) { double r = (nextLong() >>> 11) * DOUBLE_UNIT; if (origin < bound) { r = r * (bound - origin) + origin; if (r >= bound) // correct for rounding r = Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1); } return r; } /** * Returns a pseudorandom {@code int} value. * * @return a pseudorandom {@code int} value */ public int nextInt() { return mix32(nextSeed()); } /** * Returns a pseudorandom {@code int} value between zero (inclusive) * and the specified bound (exclusive). * * @param bound the upper bound (exclusive). Must be positive. * @return a pseudorandom {@code int} value between zero * (inclusive) and the bound (exclusive) * @throws IllegalArgumentException if {@code bound} is not positive */ public int nextInt(int bound) { if (bound <= 0) throw new IllegalArgumentException(BadBound); int r = mix32(nextSeed()); int m = bound - 1; if ((bound & m) == 0) // power of two r &= m; else { // reject over-represented candidates for (int u = r >>> 1; u + m - (r = u % bound) < 0; u = mix32(nextSeed()) >>> 1) ; } return r; } /** * Returns a pseudorandom {@code int} value between the specified * origin (inclusive) and the specified bound (exclusive). * * @param origin the least value returned * @param bound the upper bound (exclusive) * @return a pseudorandom {@code int} value between the origin * (inclusive) and the bound (exclusive) * @throws IllegalArgumentException if {@code origin} is greater than * or equal to {@code bound} */ public int nextInt(int origin, int bound) { if (origin >= bound) throw new IllegalArgumentException(BadRange); return internalNextInt(origin, bound); } /** * Returns a pseudorandom {@code long} value. * * @return a pseudorandom {@code long} value */ public long nextLong() { return mix64(nextSeed()); } /** * Returns a pseudorandom {@code long} value between zero (inclusive) * and the specified bound (exclusive). * * @param bound the upper bound (exclusive). Must be positive. * @return a pseudorandom {@code long} value between zero * (inclusive) and the bound (exclusive) * @throws IllegalArgumentException if {@code bound} is not positive */ public long nextLong(long bound) { if (bound <= 0) throw new IllegalArgumentException(BadBound); long r = mix64(nextSeed()); long m = bound - 1; if ((bound & m) == 0L) // power of two r &= m; else { // reject over-represented candidates for (long u = r >>> 1; u + m - (r = u % bound) < 0L; u = mix64(nextSeed()) >>> 1) ; } return r; } /** * Returns a pseudorandom {@code long} value between the specified * origin (inclusive) and the specified bound (exclusive). * * @param origin the least value returned * @param bound the upper bound (exclusive) * @return a pseudorandom {@code long} value between the origin * (inclusive) and the bound (exclusive) * @throws IllegalArgumentException if {@code origin} is greater than * or equal to {@code bound} */ public long nextLong(long origin, long bound) { if (origin >= bound) throw new IllegalArgumentException(BadRange); return internalNextLong(origin, bound); } /** * Returns a pseudorandom {@code double} value between zero * (inclusive) and one (exclusive). * * @return a pseudorandom {@code double} value between zero * (inclusive) and one (exclusive) */ public double nextDouble() { return (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT; } /** * Returns a pseudorandom {@code double} value between 0.0 * (inclusive) and the specified bound (exclusive). * * @param bound the upper bound (exclusive). Must be positive. * @return a pseudorandom {@code double} value between zero * (inclusive) and the bound (exclusive) * @throws IllegalArgumentException if {@code bound} is not positive */ public double nextDouble(double bound) { if (!(bound > 0.0)) throw new IllegalArgumentException(BadBound); double result = (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT * bound; return (result < bound) ? result : // correct for rounding Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1); } /** * Returns a pseudorandom {@code double} value between the specified * origin (inclusive) and bound (exclusive). * * @param origin the least value returned * @param bound the upper bound (exclusive) * @return a pseudorandom {@code double} value between the origin * (inclusive) and the bound (exclusive) * @throws IllegalArgumentException if {@code origin} is greater than * or equal to {@code bound} */ public double nextDouble(double origin, double bound) { if (!(origin < bound)) throw new IllegalArgumentException(BadRange); return internalNextDouble(origin, bound); } /** * Returns a pseudorandom {@code boolean} value. * * @return a pseudorandom {@code boolean} value */ public boolean nextBoolean() { return mix32(nextSeed()) < 0; } /** * Returns a pseudorandom {@code float} value between zero * (inclusive) and one (exclusive). * * @return a pseudorandom {@code float} value between zero * (inclusive) and one (exclusive) */ public float nextFloat() { return (mix32(nextSeed()) >>> 8) * FLOAT_UNIT; } public double nextGaussian() { // Use nextLocalGaussian instead of nextGaussian field Double d = nextLocalGaussian.get(); if (d != null) { nextLocalGaussian.set(null); return d.doubleValue(); } double v1, v2, s; do { v1 = 2 * nextDouble() - 1; // between -1 and 1 v2 = 2 * nextDouble() - 1; // between -1 and 1 s = v1 * v1 + v2 * v2; } while (s >= 1 || s == 0); double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s); nextLocalGaussian.set(new Double(v2 * multiplier)); return v1 * multiplier; } // stream methods, coded in a way intended to better isolate for // maintenance purposes the small differences across forms. /** * Returns a stream producing the given {@code streamSize} number of * pseudorandom {@code int} values. * * @param streamSize the number of values to generate * @return a stream of pseudorandom {@code int} values * @throws IllegalArgumentException if {@code streamSize} is * less than zero * @since 1.8 */ public IntStream ints(long streamSize) { if (streamSize < 0L) throw new IllegalArgumentException(BadSize); return StreamSupport.intStream (new RandomIntsSpliterator (0L, streamSize, Integer.MAX_VALUE, 0), false); } /** * Returns an effectively unlimited stream of pseudorandom {@code int} * values. * * @implNote This method is implemented to be equivalent to {@code * ints(Long.MAX_VALUE)}. * * @return a stream of pseudorandom {@code int} values * @since 1.8 */ public IntStream ints() { return StreamSupport.intStream (new RandomIntsSpliterator (0L, Long.MAX_VALUE, Integer.MAX_VALUE, 0), false); } /** * Returns a stream producing the given {@code streamSize} number * of pseudorandom {@code int} values, each conforming to the given * origin (inclusive) and bound (exclusive). * * @param streamSize the number of values to generate * @param randomNumberOrigin the origin (inclusive) of each random value * @param randomNumberBound the bound (exclusive) of each random value * @return a stream of pseudorandom {@code int} values, * each with the given origin (inclusive) and bound (exclusive) * @throws IllegalArgumentException if {@code streamSize} is * less than zero, or {@code randomNumberOrigin} * is greater than or equal to {@code randomNumberBound} * @since 1.8 */ public IntStream ints(long streamSize, int randomNumberOrigin, int randomNumberBound) { if (streamSize < 0L) throw new IllegalArgumentException(BadSize); if (randomNumberOrigin >= randomNumberBound) throw new IllegalArgumentException(BadRange); return StreamSupport.intStream (new RandomIntsSpliterator (0L, streamSize, randomNumberOrigin, randomNumberBound), false); } /** * Returns an effectively unlimited stream of pseudorandom {@code * int} values, each conforming to the given origin (inclusive) and bound * (exclusive). * * @implNote This method is implemented to be equivalent to {@code * ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}. * * @param randomNumberOrigin the origin (inclusive) of each random value * @param randomNumberBound the bound (exclusive) of each random value * @return a stream of pseudorandom {@code int} values, * each with the given origin (inclusive) and bound (exclusive) * @throws IllegalArgumentException if {@code randomNumberOrigin} * is greater than or equal to {@code randomNumberBound} * @since 1.8 */ public IntStream ints(int randomNumberOrigin, int randomNumberBound) { if (randomNumberOrigin >= randomNumberBound) throw new IllegalArgumentException(BadRange); return StreamSupport.intStream (new RandomIntsSpliterator (0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound), false); } /** * Returns a stream producing the given {@code streamSize} number of * pseudorandom {@code long} values. * * @param streamSize the number of values to generate * @return a stream of pseudorandom {@code long} values * @throws IllegalArgumentException if {@code streamSize} is * less than zero * @since 1.8 */ public LongStream longs(long streamSize) { if (streamSize < 0L) throw new IllegalArgumentException(BadSize); return StreamSupport.longStream (new RandomLongsSpliterator (0L, streamSize, Long.MAX_VALUE, 0L), false); } /** * Returns an effectively unlimited stream of pseudorandom {@code long} * values. * * @implNote This method is implemented to be equivalent to {@code * longs(Long.MAX_VALUE)}. * * @return a stream of pseudorandom {@code long} values * @since 1.8 */ public LongStream longs() { return StreamSupport.longStream (new RandomLongsSpliterator (0L, Long.MAX_VALUE, Long.MAX_VALUE, 0L), false); } /** * Returns a stream producing the given {@code streamSize} number of * pseudorandom {@code long}, each conforming to the given origin * (inclusive) and bound (exclusive). * * @param streamSize the number of values to generate * @param randomNumberOrigin the origin (inclusive) of each random value * @param randomNumberBound the bound (exclusive) of each random value * @return a stream of pseudorandom {@code long} values, * each with the given origin (inclusive) and bound (exclusive) * @throws IllegalArgumentException if {@code streamSize} is * less than zero, or {@code randomNumberOrigin} * is greater than or equal to {@code randomNumberBound} * @since 1.8 */ public LongStream longs(long streamSize, long randomNumberOrigin, long randomNumberBound) { if (streamSize < 0L) throw new IllegalArgumentException(BadSize); if (randomNumberOrigin >= randomNumberBound) throw new IllegalArgumentException(BadRange); return StreamSupport.longStream (new RandomLongsSpliterator (0L, streamSize, randomNumberOrigin, randomNumberBound), false); } /** * Returns an effectively unlimited stream of pseudorandom {@code * long} values, each conforming to the given origin (inclusive) and bound * (exclusive). * * @implNote This method is implemented to be equivalent to {@code * longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}. * * @param randomNumberOrigin the origin (inclusive) of each random value * @param randomNumberBound the bound (exclusive) of each random value * @return a stream of pseudorandom {@code long} values, * each with the given origin (inclusive) and bound (exclusive) * @throws IllegalArgumentException if {@code randomNumberOrigin} * is greater than or equal to {@code randomNumberBound} * @since 1.8 */ public LongStream longs(long randomNumberOrigin, long randomNumberBound) { if (randomNumberOrigin >= randomNumberBound) throw new IllegalArgumentException(BadRange); return StreamSupport.longStream (new RandomLongsSpliterator (0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound), false); } /** * Returns a stream producing the given {@code streamSize} number of * pseudorandom {@code double} values, each between zero * (inclusive) and one (exclusive). * * @param streamSize the number of values to generate * @return a stream of {@code double} values * @throws IllegalArgumentException if {@code streamSize} is * less than zero * @since 1.8 */ public DoubleStream doubles(long streamSize) { if (streamSize < 0L) throw new IllegalArgumentException(BadSize); return StreamSupport.doubleStream (new RandomDoublesSpliterator (0L, streamSize, Double.MAX_VALUE, 0.0), false); } /** * Returns an effectively unlimited stream of pseudorandom {@code * double} values, each between zero (inclusive) and one * (exclusive). * * @implNote This method is implemented to be equivalent to {@code * doubles(Long.MAX_VALUE)}. * * @return a stream of pseudorandom {@code double} values * @since 1.8 */ public DoubleStream doubles() { return StreamSupport.doubleStream (new RandomDoublesSpliterator (0L, Long.MAX_VALUE, Double.MAX_VALUE, 0.0), false); } /** * Returns a stream producing the given {@code streamSize} number of * pseudorandom {@code double} values, each conforming to the given origin * (inclusive) and bound (exclusive). * * @param streamSize the number of values to generate * @param randomNumberOrigin the origin (inclusive) of each random value * @param randomNumberBound the bound (exclusive) of each random value * @return a stream of pseudorandom {@code double} values, * each with the given origin (inclusive) and bound (exclusive) * @throws IllegalArgumentException if {@code streamSize} is * less than zero * @throws IllegalArgumentException if {@code randomNumberOrigin} * is greater than or equal to {@code randomNumberBound} * @since 1.8 */ public DoubleStream doubles(long streamSize, double randomNumberOrigin, double randomNumberBound) { if (streamSize < 0L) throw new IllegalArgumentException(BadSize); if (!(randomNumberOrigin < randomNumberBound)) throw new IllegalArgumentException(BadRange); return StreamSupport.doubleStream (new RandomDoublesSpliterator (0L, streamSize, randomNumberOrigin, randomNumberBound), false); } /** * Returns an effectively unlimited stream of pseudorandom {@code * double} values, each conforming to the given origin (inclusive) and bound * (exclusive). * * @implNote This method is implemented to be equivalent to {@code * doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}. * * @param randomNumberOrigin the origin (inclusive) of each random value * @param randomNumberBound the bound (exclusive) of each random value * @return a stream of pseudorandom {@code double} values, * each with the given origin (inclusive) and bound (exclusive) * @throws IllegalArgumentException if {@code randomNumberOrigin} * is greater than or equal to {@code randomNumberBound} * @since 1.8 */ public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) { if (!(randomNumberOrigin < randomNumberBound)) throw new IllegalArgumentException(BadRange); return StreamSupport.doubleStream (new RandomDoublesSpliterator (0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound), false); } /** * Spliterator for int streams. We multiplex the four int * versions into one class by treating a bound less than origin as * unbounded, and also by treating "infinite" as equivalent to * Long.MAX_VALUE. For splits, it uses the standard divide-by-two * approach. The long and double versions of this class are * identical except for types. */ static final class RandomIntsSpliterator implements Spliterator.OfInt { long index; final long fence; final int origin; final int bound; RandomIntsSpliterator(long index, long fence, int origin, int bound) { this.index = index; this.fence = fence; this.origin = origin; this.bound = bound; } public RandomIntsSpliterator trySplit() { long i = index, m = (i + fence) >>> 1; return (m <= i) ? null : new RandomIntsSpliterator(i, index = m, origin, bound); } public long estimateSize() { return fence - index; } public int characteristics() { return (Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.NONNULL | Spliterator.IMMUTABLE); } public boolean tryAdvance(IntConsumer consumer) { if (consumer == null) throw new NullPointerException(); long i = index, f = fence; if (i < f) { consumer.accept(ThreadLocalRandom.current().internalNextInt(origin, bound)); index = i + 1; return true; } return false; } public void forEachRemaining(IntConsumer consumer) { if (consumer == null) throw new NullPointerException(); long i = index, f = fence; if (i < f) { index = f; int o = origin, b = bound; ThreadLocalRandom rng = ThreadLocalRandom.current(); do { consumer.accept(rng.internalNextInt(o, b)); } while (++i < f); } } } /** * Spliterator for long streams. */ static final class RandomLongsSpliterator implements Spliterator.OfLong { long index; final long fence; final long origin; final long bound; RandomLongsSpliterator(long index, long fence, long origin, long bound) { this.index = index; this.fence = fence; this.origin = origin; this.bound = bound; } public RandomLongsSpliterator trySplit() { long i = index, m = (i + fence) >>> 1; return (m <= i) ? null : new RandomLongsSpliterator(i, index = m, origin, bound); } public long estimateSize() { return fence - index; } public int characteristics() { return (Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.NONNULL | Spliterator.IMMUTABLE); } public boolean tryAdvance(LongConsumer consumer) { if (consumer == null) throw new NullPointerException(); long i = index, f = fence; if (i < f) { consumer.accept(ThreadLocalRandom.current().internalNextLong(origin, bound)); index = i + 1; return true; } return false; } public void forEachRemaining(LongConsumer consumer) { if (consumer == null) throw new NullPointerException(); long i = index, f = fence; if (i < f) { index = f; long o = origin, b = bound; ThreadLocalRandom rng = ThreadLocalRandom.current(); do { consumer.accept(rng.internalNextLong(o, b)); } while (++i < f); } } } /** * Spliterator for double streams. */ static final class RandomDoublesSpliterator implements Spliterator.OfDouble { long index; final long fence; final double origin; final double bound; RandomDoublesSpliterator(long index, long fence, double origin, double bound) { this.index = index; this.fence = fence; this.origin = origin; this.bound = bound; } public RandomDoublesSpliterator trySplit() { long i = index, m = (i + fence) >>> 1; return (m <= i) ? null : new RandomDoublesSpliterator(i, index = m, origin, bound); } public long estimateSize() { return fence - index; } public int characteristics() { return (Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.NONNULL | Spliterator.IMMUTABLE); } public boolean tryAdvance(DoubleConsumer consumer) { if (consumer == null) throw new NullPointerException(); long i = index, f = fence; if (i < f) { consumer.accept(ThreadLocalRandom.current().internalNextDouble(origin, bound)); index = i + 1; return true; } return false; } public void forEachRemaining(DoubleConsumer consumer) { if (consumer == null) throw new NullPointerException(); long i = index, f = fence; if (i < f) { index = f; double o = origin, b = bound; ThreadLocalRandom rng = ThreadLocalRandom.current(); do { consumer.accept(rng.internalNextDouble(o, b)); } while (++i < f); } } } // Within-package utilities /* * Descriptions of the usages of the methods below can be found in * the classes that use them. Briefly, a thread's "probe" value is * a non-zero hash code that (probably) does not collide with * other existing threads with respect to any power of two * collision space. When it does collide, it is pseudo-randomly * adjusted (using a Marsaglia XorShift). The nextSecondarySeed * method is used in the same contexts as ThreadLocalRandom, but * only for transient usages such as random adaptive spin/block * sequences for which a cheap RNG suffices and for which it could * in principle disrupt user-visible statistical properties of the * main ThreadLocalRandom if we were to use it. * * Note: Because of package-protection issues, versions of some * these methods also appear in some subpackage classes. */ /** * Returns the probe value for the current thread without forcing * initialization. Note that invoking ThreadLocalRandom.current() * can be used to force initialization on zero return. */ static final int getProbe() { return UNSAFE.getInt(Thread.currentThread(), PROBE); } /** * Pseudo-randomly advances and records the given probe value for the * given thread. */ static final int advanceProbe(int probe) { probe ^= probe << 13; // xorshift probe ^= probe >>> 17; probe ^= probe << 5; UNSAFE.putInt(Thread.currentThread(), PROBE, probe); return probe; } /** * Returns the pseudo-randomly initialized or updated secondary seed. */ static final int nextSecondarySeed() { int r; Thread t = Thread.currentThread(); if ((r = UNSAFE.getInt(t, SECONDARY)) != 0) { r ^= r << 13; // xorshift r ^= r >>> 17; r ^= r << 5; } else { localInit(); if ((r = (int)UNSAFE.getLong(t, SEED)) == 0) r = 1; // avoid zero } UNSAFE.putInt(t, SECONDARY, r); return r; } // Serialization support private static final long serialVersionUID = -5851777807851030925L; /** * @serialField rnd long * seed for random computations * @serialField initialized boolean * always true */ private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField("rnd", long.class), new ObjectStreamField("initialized", boolean.class), }; /** * Saves the {@code ThreadLocalRandom} to a stream (that is, serializes it). * @param s the stream * @throws java.io.IOException if an I/O error occurs */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { java.io.ObjectOutputStream.PutField fields = s.putFields(); fields.put("rnd", UNSAFE.getLong(Thread.currentThread(), SEED)); fields.put("initialized", true); s.writeFields(); } /** * Returns the {@link #current() current} thread's {@code ThreadLocalRandom}. * @return the {@link #current() current} thread's {@code ThreadLocalRandom} */ private Object readResolve() { return current(); } // Unsafe mechanics private static final sun.misc.Unsafe UNSAFE; private static final long SEED; private static final long PROBE; private static final long SECONDARY; static { try { UNSAFE = sun.misc.Unsafe.getUnsafe(); Class<?> tk = Thread.class; SEED = UNSAFE.objectFieldOffset (tk.getDeclaredField("threadLocalRandomSeed")); PROBE = UNSAFE.objectFieldOffset (tk.getDeclaredField("threadLocalRandomProbe")); SECONDARY = UNSAFE.objectFieldOffset (tk.getDeclaredField("threadLocalRandomSecondarySeed")); } catch (Exception e) { throw new Error(e); } } }
stain/jdk8u
src/share/classes/java/util/concurrent/ThreadLocalRandom.java
Java
gpl-2.0
40,574
/** * Copyright © 2002 Instituto Superior Técnico * * This file is part of FenixEdu Academic. * * FenixEdu Academic 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. * * FenixEdu Academic 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 FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>. */ package org.fenixedu.academic.ui.renderers.providers.choiceType.replacement.single; import java.util.Arrays; import pt.ist.fenixWebFramework.renderers.DataProvider; import pt.ist.fenixWebFramework.renderers.components.converters.Converter; import pt.ist.fenixWebFramework.renderers.converters.EnumConverter; public class RegimeTypeProvider implements DataProvider { @Override public Object provide(Object source, Object currentValue) { return Arrays.asList(org.fenixedu.academic.domain.degreeStructure.RegimeType.values()); } @Override public Converter getConverter() { return new EnumConverter(); } }
andre-nunes/fenixedu-academic
src/main/java/org/fenixedu/academic/ui/renderers/providers/choiceType/replacement/single/RegimeTypeProvider.java
Java
lgpl-3.0
1,436
package pack; class Ba{ }
siosio/intellij-community
java/java-tests/testData/packageSet/oneModuleStructure/src/pack/Ba.java
Java
apache-2.0
26
/* * 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.facebook.presto.connector.system; import com.facebook.presto.connector.ConnectorManager; import com.facebook.presto.spi.SystemTable; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.Scopes; import com.google.inject.multibindings.Multibinder; import javax.inject.Inject; public class SystemTablesModule implements Module { @Override public void configure(Binder binder) { Multibinder<SystemTable> globalTableBinder = Multibinder.newSetBinder(binder, SystemTable.class); globalTableBinder.addBinding().to(NodeSystemTable.class).in(Scopes.SINGLETON); globalTableBinder.addBinding().to(QuerySystemTable.class).in(Scopes.SINGLETON); globalTableBinder.addBinding().to(TaskSystemTable.class).in(Scopes.SINGLETON); globalTableBinder.addBinding().to(CatalogSystemTable.class).in(Scopes.SINGLETON); globalTableBinder.addBinding().to(TablePropertiesSystemTable.class).in(Scopes.SINGLETON); binder.bind(SystemConnector.class).in(Scopes.SINGLETON); binder.bind(SystemTablesRegistrar.class).asEagerSingleton(); } private static class SystemTablesRegistrar { @Inject public SystemTablesRegistrar(ConnectorManager manager, SystemConnector connector) { manager.createConnection(SystemConnector.NAME, connector); } } }
deciament/presto
presto-main/src/main/java/com/facebook/presto/connector/system/SystemTablesModule.java
Java
apache-2.0
1,966
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.email; import org.keycloak.events.Event; import org.keycloak.models.RealmModel; import org.keycloak.models.UserModel; import org.keycloak.provider.Provider; import org.keycloak.sessions.AuthenticationSessionModel; import java.util.List; import java.util.Map; /** * @author <a href="mailto:[email protected]">Stian Thorgersen</a> */ public interface EmailTemplateProvider extends Provider { String IDENTITY_PROVIDER_BROKER_CONTEXT = "identityProviderBrokerCtx"; EmailTemplateProvider setAuthenticationSession(AuthenticationSessionModel authenticationSession); EmailTemplateProvider setRealm(RealmModel realm); EmailTemplateProvider setUser(UserModel user); EmailTemplateProvider setAttribute(String name, Object value); void sendEvent(Event event) throws EmailException; /** * Reset password sent from forgot password link on login * * @param link * @param expirationInMinutes * @throws EmailException */ void sendPasswordReset(String link, long expirationInMinutes) throws EmailException; /** * Test SMTP connection with current logged in user * * @param config SMTP server configuration * @param user SMTP recipient * @throws EmailException */ void sendSmtpTestEmail(Map<String, String> config, UserModel user) throws EmailException; /** * Send to confirm that user wants to link his account with identity broker link */ void sendConfirmIdentityBrokerLink(String link, long expirationInMinutes) throws EmailException; /** * Change password email requested by admin * * @param link * @param expirationInMinutes * @throws EmailException */ void sendExecuteActions(String link, long expirationInMinutes) throws EmailException; void sendVerifyEmail(String link, long expirationInMinutes) throws EmailException; /** * Send formatted email * * @param subjectFormatKey message property that will be used to format email subject * @param bodyTemplate freemarker template file * @param bodyAttributes attributes used to fill template * @throws EmailException */ void send(String subjectFormatKey, String bodyTemplate, Map<String, Object> bodyAttributes) throws EmailException; /** * Send formatted email * * @param subjectFormatKey message property that will be used to format email subject * @param subjectAttributes attributes used to fill subject format message * @param bodyTemplate freemarker template file * @param bodyAttributes attributes used to fill template * @throws EmailException */ void send(String subjectFormatKey, List<Object> subjectAttributes, String bodyTemplate, Map<String, Object> bodyAttributes) throws EmailException; }
abstractj/keycloak
server-spi-private/src/main/java/org/keycloak/email/EmailTemplateProvider.java
Java
apache-2.0
3,510
package org.zstack.test.storage.primary; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import org.zstack.core.cloudbus.CloudBus; import org.zstack.core.componentloader.ComponentLoader; import org.zstack.core.db.DatabaseFacade; import org.zstack.header.cluster.ClusterInventory; import org.zstack.header.query.QueryOp; import org.zstack.header.storage.primary.APIQueryPrimaryStorageMsg; import org.zstack.header.storage.primary.APIQueryPrimaryStorageReply; import org.zstack.header.storage.primary.PrimaryStorageInventory; import org.zstack.test.Api; import org.zstack.test.ApiSenderException; import org.zstack.test.DBUtil; import org.zstack.test.deployer.Deployer; import org.zstack.test.search.QueryTestValidator; import org.zstack.utils.Utils; import org.zstack.utils.logging.CLogger; public class TestQueryPrimaryStorage { CLogger logger = Utils.getLogger(TestQueryPrimaryStorage.class); Deployer deployer; Api api; ComponentLoader loader; CloudBus bus; DatabaseFacade dbf; @Before public void setUp() throws Exception { DBUtil.reDeployDB(); deployer = new Deployer("deployerXml/primaryStorage/TestQueryPrimaryStorage.xml"); deployer.build(); api = deployer.getApi(); loader = deployer.getComponentLoader(); bus = loader.getComponent(CloudBus.class); dbf = loader.getComponent(DatabaseFacade.class); } @Test public void test() throws ApiSenderException, InterruptedException { PrimaryStorageInventory inv = deployer.primaryStorages.get("TestPrimaryStorage1"); QueryTestValidator.validateEQ(new APIQueryPrimaryStorageMsg(), api, APIQueryPrimaryStorageReply.class, inv); QueryTestValidator.validateRandomEQConjunction(new APIQueryPrimaryStorageMsg(), api, APIQueryPrimaryStorageReply.class, inv, 3); ClusterInventory cluster2 = deployer.clusters.get("cluster2"); APIQueryPrimaryStorageMsg msg = new APIQueryPrimaryStorageMsg(); msg.addQueryCondition("attachedClusterUuids", QueryOp.NOT_IN, cluster2.getUuid()); APIQueryPrimaryStorageReply reply = api.query(msg, APIQueryPrimaryStorageReply.class); Assert.assertEquals(2, reply.getInventories().size()); } }
zstackorg/zstack
test/src/test/java/org/zstack/test/storage/primary/TestQueryPrimaryStorage.java
Java
apache-2.0
2,265
/* * 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.runtime.operators.udf; import org.apache.flink.api.common.functions.MapFunction; import org.apache.flink.api.java.tuple.Tuple2; public class RemoveRangeIndex<T> implements MapFunction<Tuple2<Integer, T>, T> { @Override public T map(Tuple2<Integer, T> value) throws Exception { return value.f1; } }
tillrohrmann/flink
flink-runtime/src/main/java/org/apache/flink/runtime/operators/udf/RemoveRangeIndex.java
Java
apache-2.0
1,152
/** * 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. */ /** * Autogenerated by Thrift Compiler (0.7.0) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING */ package backtype.storm.generated; import org.apache.commons.lang.builder.HashCodeBuilder; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class KillOptions implements org.apache.thrift7.TBase<KillOptions, KillOptions._Fields>, java.io.Serializable, Cloneable { private static final org.apache.thrift7.protocol.TStruct STRUCT_DESC = new org.apache.thrift7.protocol.TStruct("KillOptions"); private static final org.apache.thrift7.protocol.TField WAIT_SECS_FIELD_DESC = new org.apache.thrift7.protocol.TField("wait_secs", org.apache.thrift7.protocol.TType.I32, (short)1); private int wait_secs; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift7.TFieldIdEnum { WAIT_SECS((short)1, "wait_secs"); private static final Map<String, _Fields> byName = new HashMap<String, _Fields>(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // WAIT_SECS return WAIT_SECS; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __WAIT_SECS_ISSET_ID = 0; private BitSet __isset_bit_vector = new BitSet(1); public static final Map<_Fields, org.apache.thrift7.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift7.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift7.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.WAIT_SECS, new org.apache.thrift7.meta_data.FieldMetaData("wait_secs", org.apache.thrift7.TFieldRequirementType.OPTIONAL, new org.apache.thrift7.meta_data.FieldValueMetaData(org.apache.thrift7.protocol.TType.I32))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift7.meta_data.FieldMetaData.addStructMetaDataMap(KillOptions.class, metaDataMap); } public KillOptions() { } /** * Performs a deep copy on <i>other</i>. */ public KillOptions(KillOptions other) { __isset_bit_vector.clear(); __isset_bit_vector.or(other.__isset_bit_vector); this.wait_secs = other.wait_secs; } public KillOptions deepCopy() { return new KillOptions(this); } @Override public void clear() { set_wait_secs_isSet(false); this.wait_secs = 0; } public int get_wait_secs() { return this.wait_secs; } public void set_wait_secs(int wait_secs) { this.wait_secs = wait_secs; set_wait_secs_isSet(true); } public void unset_wait_secs() { __isset_bit_vector.clear(__WAIT_SECS_ISSET_ID); } /** Returns true if field wait_secs is set (has been assigned a value) and false otherwise */ public boolean is_set_wait_secs() { return __isset_bit_vector.get(__WAIT_SECS_ISSET_ID); } public void set_wait_secs_isSet(boolean value) { __isset_bit_vector.set(__WAIT_SECS_ISSET_ID, value); } public void setFieldValue(_Fields field, Object value) { switch (field) { case WAIT_SECS: if (value == null) { unset_wait_secs(); } else { set_wait_secs((Integer)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case WAIT_SECS: return Integer.valueOf(get_wait_secs()); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case WAIT_SECS: return is_set_wait_secs(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof KillOptions) return this.equals((KillOptions)that); return false; } public boolean equals(KillOptions that) { if (that == null) return false; boolean this_present_wait_secs = true && this.is_set_wait_secs(); boolean that_present_wait_secs = true && that.is_set_wait_secs(); if (this_present_wait_secs || that_present_wait_secs) { if (!(this_present_wait_secs && that_present_wait_secs)) return false; if (this.wait_secs != that.wait_secs) return false; } return true; } @Override public int hashCode() { HashCodeBuilder builder = new HashCodeBuilder(); boolean present_wait_secs = true && (is_set_wait_secs()); builder.append(present_wait_secs); if (present_wait_secs) builder.append(wait_secs); return builder.toHashCode(); } public int compareTo(KillOptions other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; KillOptions typedOther = (KillOptions)other; lastComparison = Boolean.valueOf(is_set_wait_secs()).compareTo(typedOther.is_set_wait_secs()); if (lastComparison != 0) { return lastComparison; } if (is_set_wait_secs()) { lastComparison = org.apache.thrift7.TBaseHelper.compareTo(this.wait_secs, typedOther.wait_secs); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift7.protocol.TProtocol iprot) throws org.apache.thrift7.TException { org.apache.thrift7.protocol.TField field; iprot.readStructBegin(); while (true) { field = iprot.readFieldBegin(); if (field.type == org.apache.thrift7.protocol.TType.STOP) { break; } switch (field.id) { case 1: // WAIT_SECS if (field.type == org.apache.thrift7.protocol.TType.I32) { this.wait_secs = iprot.readI32(); set_wait_secs_isSet(true); } else { org.apache.thrift7.protocol.TProtocolUtil.skip(iprot, field.type); } break; default: org.apache.thrift7.protocol.TProtocolUtil.skip(iprot, field.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); validate(); } public void write(org.apache.thrift7.protocol.TProtocol oprot) throws org.apache.thrift7.TException { validate(); oprot.writeStructBegin(STRUCT_DESC); if (is_set_wait_secs()) { oprot.writeFieldBegin(WAIT_SECS_FIELD_DESC); oprot.writeI32(this.wait_secs); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } @Override public String toString() { StringBuilder sb = new StringBuilder("KillOptions("); boolean first = true; if (is_set_wait_secs()) { sb.append("wait_secs:"); sb.append(this.wait_secs); first = false; } sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift7.TException { // check for required fields } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift7.protocol.TCompactProtocol(new org.apache.thrift7.transport.TIOStreamTransport(out))); } catch (org.apache.thrift7.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bit_vector = new BitSet(1); read(new org.apache.thrift7.protocol.TCompactProtocol(new org.apache.thrift7.transport.TIOStreamTransport(in))); } catch (org.apache.thrift7.TException te) { throw new java.io.IOException(te); } } }
konfer/storm
storm-core/src/jvm/backtype/storm/generated/KillOptions.java
Java
apache-2.0
10,202
/* * 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.api.common; import org.apache.flink.annotation.PublicEvolving; import org.apache.flink.api.common.typeutils.TypeSerializerConfigSnapshot; import org.apache.flink.api.java.typeutils.runtime.PojoSerializer; /** * @deprecated The code analysis code has been removed and this enum has no effect. <b>NOTE</b> It * can not be removed from the codebase for now, because it had been serialized as part of the * {@link ExecutionConfig} which in turn had been serialized as part of the {@link * PojoSerializer}. * <p>This class can be removed when we drop support for pre 1.8 serializer snapshots that * contained java serialized serializers ({@link TypeSerializerConfigSnapshot}). */ @PublicEvolving @Deprecated public enum CodeAnalysisMode { /** Code analysis does not take place. */ DISABLE, /** Hints for improvement of the program are printed to the log. */ HINT, /** The program will be automatically optimized with knowledge from code analysis. */ OPTIMIZE; }
wwjiang007/flink
flink-core/src/main/java/org/apache/flink/api/common/CodeAnalysisMode.java
Java
apache-2.0
1,845
/* * Copyright 2000-2014 Vaadin Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.vaadin.shared.ui.ui; import com.vaadin.shared.communication.ClientRpc; public interface PageClientRpc extends ClientRpc { public void reload(); }
jdahlstrom/vaadin.react
shared/src/main/java/com/vaadin/shared/ui/ui/PageClientRpc.java
Java
apache-2.0
766
/*************************** GO-LICENSE-START********************************* * Copyright 2016 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. * ************************GO-LICENSE-END***********************************/ package com.thoughtworks.go.buildsession; import com.thoughtworks.go.domain.BuildCommand; public interface BuildCommandExecutor { boolean execute(BuildCommand command, BuildSession buildSession); }
varshavaradarajan/gocd
common/src/main/java/com/thoughtworks/go/buildsession/BuildCommandExecutor.java
Java
apache-2.0
952
/* * Copyright 2004,2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.webapp.deployer; import org.apache.axis2.context.ConfigurationContext; import org.apache.axis2.deployment.DeploymentException; import org.apache.axis2.deployment.repository.util.DeploymentFileData; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.webapp.mgt.AbstractWebappDeployer; import org.wso2.carbon.webapp.mgt.TomcatGenericWebappsDeployer; import org.wso2.carbon.webapp.mgt.WebappsConstants; /** * Axis2 deployer for deploying Web applications */ public class WebappDeployer extends AbstractWebappDeployer { private static final Log log = LogFactory.getLog(WebappDeployer.class); @Override public void init(ConfigurationContext configCtx) { super.init(configCtx); configCtx.setProperty(WebappsConstants.TOMCAT_GENERIC_WEBAPP_DEPLOYER, tomcatWebappDeployer); } @Override public void deploy(DeploymentFileData deploymentFileData) throws DeploymentException { super.deploy(deploymentFileData); } public void setDirectory(String repoDir) { this.webappsDir = repoDir; } public void setExtension(String extension) { this.extension = extension; } @Override protected TomcatGenericWebappsDeployer createTomcatGenericWebappDeployer( String webContextPrefix, int tenantId, String tenantDomain) { return new TomcatGenericWebappsDeployer(webContextPrefix, tenantId, tenantDomain, webApplicationsHolderMap, configContext); } @Override protected String getType() { return WebappsConstants.WEBAPP_FILTER_PROP; } }
Priya-Kishok/carbon-deployment
components/webapp-mgt/org.wso2.carbon.webapp.deployer/src/main/java/org/wso2/carbon/webapp/deployer/WebappDeployer.java
Java
apache-2.0
2,759
/** * Copyright 2005-2015 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @javax.xml.bind.annotation.XmlSchema(namespace = CoreConstants.Namespaces.CORE_NAMESPACE_2_0, elementFormDefault = XmlNsForm.QUALIFIED) package org.kuali.rice.core.impl.jaxb; import javax.xml.bind.annotation.XmlNsForm; import org.kuali.rice.core.api.CoreConstants;
bhutchinson/rice
rice-middleware/client-contrib/src/main/java/org/kuali/rice/core/impl/jaxb/package-info.java
Java
apache-2.0
910
// "Join declaration and assignment" "GENERIC_ERROR_OR_WARNING" class C { int foo() { var <caret>a = 0; a = 1; return a; } }
zdary/intellij-community
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/joinDeclaration/beforeVar.java
Java
apache-2.0
156
/******************************************************************************* * Copyright (c) 2007, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.fix; import org.eclipse.jdt.internal.corext.fix.CleanUpConstants; import org.eclipse.jdt.ui.cleanup.CleanUpOptions; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.Set; public class MapCleanUpOptions extends CleanUpOptions { private final Map<String, String> fOptions; /** * Create new CleanUpOptions instance. <code>options</code> * maps named clean ups keys to {@link CleanUpOptions#TRUE}, * {@link CleanUpOptions#FALSE} or any String value * * @param options map from String to String * @see CleanUpConstants */ public MapCleanUpOptions(Map<String, String> options) { super(options); fOptions= options; } public MapCleanUpOptions() { this(new Hashtable<String, String>()); } /** * @return all options as map, modifying the map modifies this object */ public Map<String, String> getMap() { return fOptions; } /** * @param options the options to add to this options */ public void addAll(CleanUpOptions options) { if (options instanceof MapCleanUpOptions) { fOptions.putAll(((MapCleanUpOptions)options).getMap()); } else { Set<String> keys= options.getKeys(); for (Iterator<String> iterator= keys.iterator(); iterator.hasNext();) { String key= iterator.next(); fOptions.put(key, options.getValue(key)); } } } }
dhuebner/che
plugins/plugin-java/che-plugin-java-ext-jdt/org-eclipse-jdt-ui/src/main/java/org/eclipse/jdt/internal/ui/fix/MapCleanUpOptions.java
Java
epl-1.0
1,912
package com.engc.smartedu.ui.actionmenu; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import com.engc.smartedu.R; import com.engc.smartedu.bean.CommentBean; import com.engc.smartedu.support.utils.GlobalContext; import com.engc.smartedu.ui.browser.BrowserWeiboMsgActivity; import com.engc.smartedu.ui.send.WriteReplyToCommentActivity; /** * User: qii * Date: 12-12-6 */ @SuppressLint({ "NewApi", "ValidFragment" }) public class CommentFloatingMenu extends DialogFragment { private CommentBean bean; @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable("bean", bean); } public CommentFloatingMenu() { } public CommentFloatingMenu(CommentBean bean) { this.bean = bean; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { if (savedInstanceState != null) { bean = (CommentBean) savedInstanceState.get("bean"); } AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(this.bean.getUser().getScreen_name()); String[] str = {getString(R.string.view), getString(R.string.reply_to_comment)}; builder.setItems(str, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent; switch (which) { case 0: intent = new Intent(getActivity(), BrowserWeiboMsgActivity.class); intent.putExtra("msg", bean.getStatus()); intent.putExtra("token", GlobalContext.getInstance().getSpecialToken()); startActivity(intent); break; case 1: intent = new Intent(getActivity(), WriteReplyToCommentActivity.class); intent.putExtra("token", GlobalContext.getInstance().getSpecialToken()); intent.putExtra("msg", bean); getActivity().startActivity(intent); break; } } }); return builder.create(); } @Override public void onDetach() { super.onDetach(); } }
giserh/smartedu
src/com/engc/smartedu/ui/actionmenu/CommentFloatingMenu.java
Java
gpl-3.0
2,534
/* * 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.druid.query.groupby; import org.apache.druid.guice.annotations.ExtensionPoint; import org.apache.druid.guice.annotations.PublicApi; import org.apache.druid.query.QueryMetrics; /** * Specialization of {@link QueryMetrics} for {@link GroupByQuery}. */ @ExtensionPoint public interface GroupByQueryMetrics extends QueryMetrics<GroupByQuery> { /** * Sets the size of {@link GroupByQuery#getDimensions()} of the given query as dimension. */ @PublicApi void numDimensions(GroupByQuery query); /** * Sets the number of metrics of the given groupBy query as dimension. */ @PublicApi void numMetrics(GroupByQuery query); /** * Sets the number of "complex" metrics of the given groupBy query as dimension. By default it is assumed that * "complex" metric is a metric of not long or double type, but it could be redefined in the implementation of this * method. */ @PublicApi void numComplexMetrics(GroupByQuery query); /** * Sets the granularity of {@link GroupByQuery#getGranularity()} of the given query as dimension. */ @PublicApi void granularity(GroupByQuery query); }
deltaprojects/druid
processing/src/main/java/org/apache/druid/query/groupby/GroupByQueryMetrics.java
Java
apache-2.0
1,953
/* * Copyright 2012-2017 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 * * 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.springframework.boot.autoconfigure.cache; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.springframework.util.Assert; /** * Mappings between {@link CacheType} and {@code @Configuration}. * * @author Phillip Webb * @author Eddú Meléndez */ final class CacheConfigurations { private static final Map<CacheType, Class<?>> MAPPINGS; static { Map<CacheType, Class<?>> mappings = new HashMap<>(); mappings.put(CacheType.GENERIC, GenericCacheConfiguration.class); mappings.put(CacheType.EHCACHE, EhCacheCacheConfiguration.class); mappings.put(CacheType.HAZELCAST, HazelcastCacheConfiguration.class); mappings.put(CacheType.INFINISPAN, InfinispanCacheConfiguration.class); mappings.put(CacheType.JCACHE, JCacheCacheConfiguration.class); mappings.put(CacheType.COUCHBASE, CouchbaseCacheConfiguration.class); mappings.put(CacheType.REDIS, RedisCacheConfiguration.class); mappings.put(CacheType.CAFFEINE, CaffeineCacheConfiguration.class); mappings.put(CacheType.SIMPLE, SimpleCacheConfiguration.class); mappings.put(CacheType.NONE, NoOpCacheConfiguration.class); MAPPINGS = Collections.unmodifiableMap(mappings); } private CacheConfigurations() { } public static String getConfigurationClass(CacheType cacheType) { Class<?> configurationClass = MAPPINGS.get(cacheType); Assert.state(configurationClass != null, "Unknown cache type " + cacheType); return configurationClass.getName(); } public static CacheType getType(String configurationClassName) { for (Map.Entry<CacheType, Class<?>> entry : MAPPINGS.entrySet()) { if (entry.getValue().getName().equals(configurationClassName)) { return entry.getKey(); } } throw new IllegalStateException( "Unknown configuration class " + configurationClassName); } }
vakninr/spring-boot
spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheConfigurations.java
Java
apache-2.0
2,446
/** * 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.storm.serialization; import java.util.Map; import java.util.zip.GZIPInputStream; /** * Always writes gzip out, but tests incoming to see if it's gzipped. If it is, deserializes with gzip. If not, uses * {@link org.apache.storm.serialization.DefaultSerializationDelegate} to deserialize. Any logic needing to be enabled * via {@link #prepare(java.util.Map)} is passed through to both delegates. */ @Deprecated public class GzipBridgeSerializationDelegate implements SerializationDelegate { private DefaultSerializationDelegate defaultDelegate = new DefaultSerializationDelegate(); private GzipSerializationDelegate gzipDelegate = new GzipSerializationDelegate(); @Override public void prepare(Map<String, Object> topoConf) { defaultDelegate.prepare(topoConf); gzipDelegate.prepare(topoConf); } @Override public byte[] serialize(Object object) { return gzipDelegate.serialize(object); } @Override public <T> T deserialize(byte[] bytes, Class<T> clazz) { if (isGzipped(bytes)) { return gzipDelegate.deserialize(bytes, clazz); } else { return defaultDelegate.deserialize(bytes,clazz); } } // Split up GZIP_MAGIC into readable bytes private static final byte GZIP_MAGIC_FIRST_BYTE = (byte) GZIPInputStream.GZIP_MAGIC; private static final byte GZIP_MAGIC_SECOND_BYTE = (byte) (GZIPInputStream.GZIP_MAGIC >> 8); /** * Looks ahead to see if the GZIP magic constant is heading {@code bytes} */ private boolean isGzipped(byte[] bytes) { return (bytes.length > 1) && (bytes[0] == GZIP_MAGIC_FIRST_BYTE) && (bytes[1] == GZIP_MAGIC_SECOND_BYTE); } }
carl34/storm
storm-client/src/jvm/org/apache/storm/serialization/GzipBridgeSerializationDelegate.java
Java
apache-2.0
2,545
/** * 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.yarn.server.resourcemanager.security; import static org.mockito.Mockito.isA; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import java.io.IOException; import java.net.InetSocketAddress; import java.security.PrivilegedAction; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.atomic.AtomicReference; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeysPublic; import org.apache.hadoop.io.Text; import org.apache.hadoop.security.Credentials; import org.apache.hadoop.security.SecurityUtil; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.security.token.TokenIdentifier; import org.apache.hadoop.yarn.api.ApplicationMasterProtocol; import org.apache.hadoop.yarn.api.protocolrecords.AllocateRequest; import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse; import org.apache.hadoop.yarn.api.protocolrecords.FinishApplicationMasterRequest; import org.apache.hadoop.yarn.api.protocolrecords.RegisterApplicationMasterRequest; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ContainerState; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.ipc.YarnRPC; import org.apache.hadoop.yarn.security.AMRMTokenIdentifier; import org.apache.hadoop.yarn.server.resourcemanager.MockAM; import org.apache.hadoop.yarn.server.resourcemanager.MockNM; import org.apache.hadoop.yarn.server.resourcemanager.MockRM; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.RMSecretManagerService; import org.apache.hadoop.yarn.server.resourcemanager.TestAMAuthorization.MockRMWithAMS; import org.apache.hadoop.yarn.server.resourcemanager.TestAMAuthorization.MyContainerManager; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.event.RMAppAttemptContainerFinishedEvent; import org.apache.hadoop.yarn.server.security.MasterKeyData; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.ConverterUtils; import org.apache.hadoop.yarn.util.Records; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class TestAMRMTokens { private static final Log LOG = LogFactory.getLog(TestAMRMTokens.class); private final Configuration conf; private static final int maxWaitAttempts = 50; private static final int rolling_interval_sec = 13; private static final long am_expire_ms = 4000; @Parameters public static Collection<Object[]> configs() { Configuration conf = new Configuration(); Configuration confWithSecurity = new Configuration(); confWithSecurity.set( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos"); return Arrays.asList(new Object[][] {{ conf }, { confWithSecurity } }); } public TestAMRMTokens(Configuration conf) { this.conf = conf; UserGroupInformation.setConfiguration(conf); } /** * Validate that application tokens are unusable after the * application-finishes. * * @throws Exception */ @SuppressWarnings("unchecked") @Test public void testTokenExpiry() throws Exception { MyContainerManager containerManager = new MyContainerManager(); final MockRMWithAMS rm = new MockRMWithAMS(conf, containerManager); rm.start(); final Configuration conf = rm.getConfig(); final YarnRPC rpc = YarnRPC.create(conf); ApplicationMasterProtocol rmClient = null; try { MockNM nm1 = rm.registerNode("localhost:1234", 5120); RMApp app = rm.submitApp(1024); nm1.nodeHeartbeat(true); int waitCount = 0; while (containerManager.containerTokens == null && waitCount++ < 20) { LOG.info("Waiting for AM Launch to happen.."); Thread.sleep(1000); } Assert.assertNotNull(containerManager.containerTokens); RMAppAttempt attempt = app.getCurrentAppAttempt(); ApplicationAttemptId applicationAttemptId = attempt.getAppAttemptId(); // Create a client to the RM. UserGroupInformation currentUser = UserGroupInformation .createRemoteUser(applicationAttemptId.toString()); Credentials credentials = containerManager.getContainerCredentials(); final InetSocketAddress rmBindAddress = rm.getApplicationMasterService().getBindAddress(); Token<? extends TokenIdentifier> amRMToken = MockRMWithAMS.setupAndReturnAMRMToken(rmBindAddress, credentials.getAllTokens()); currentUser.addToken(amRMToken); rmClient = createRMClient(rm, conf, rpc, currentUser); RegisterApplicationMasterRequest request = Records.newRecord(RegisterApplicationMasterRequest.class); rmClient.registerApplicationMaster(request); FinishApplicationMasterRequest finishAMRequest = Records.newRecord(FinishApplicationMasterRequest.class); finishAMRequest .setFinalApplicationStatus(FinalApplicationStatus.SUCCEEDED); finishAMRequest.setDiagnostics("diagnostics"); finishAMRequest.setTrackingUrl("url"); rmClient.finishApplicationMaster(finishAMRequest); // Send RMAppAttemptEventType.CONTAINER_FINISHED to transit RMAppAttempt // from Finishing state to Finished State. Both AMRMToken and // ClientToAMToken will be removed. ContainerStatus containerStatus = BuilderUtils.newContainerStatus(attempt.getMasterContainer().getId(), ContainerState.COMPLETE, "AM Container Finished", 0); rm.getRMContext() .getDispatcher() .getEventHandler() .handle( new RMAppAttemptContainerFinishedEvent(applicationAttemptId, containerStatus, nm1.getNodeId())); // Make sure the RMAppAttempt is at Finished State. // Both AMRMToken and ClientToAMToken have been removed. int count = 0; while (attempt.getState() != RMAppAttemptState.FINISHED && count < maxWaitAttempts) { Thread.sleep(100); count++; } Assert.assertTrue(attempt.getState() == RMAppAttemptState.FINISHED); // Now simulate trying to allocate. RPC call itself should throw auth // exception. rpc.stopProxy(rmClient, conf); // To avoid using cached client rmClient = createRMClient(rm, conf, rpc, currentUser); AllocateRequest allocateRequest = Records.newRecord(AllocateRequest.class); try { rmClient.allocate(allocateRequest); Assert.fail("You got to be kidding me! " + "Using App tokens after app-finish should fail!"); } catch (Throwable t) { LOG.info("Exception found is ", t); // The exception will still have the earlier appAttemptId as it picks it // up from the token. Assert.assertTrue(t.getCause().getMessage().contains( applicationAttemptId.toString() + " not found in AMRMTokenSecretManager.")); } } finally { rm.stop(); if (rmClient != null) { rpc.stopProxy(rmClient, conf); // To avoid using cached client } } } /** * Validate master-key-roll-over and that tokens are usable even after * master-key-roll-over. * * @throws Exception */ @Test public void testMasterKeyRollOver() throws Exception { conf.setLong( YarnConfiguration.RM_AMRM_TOKEN_MASTER_KEY_ROLLING_INTERVAL_SECS, rolling_interval_sec); conf.setLong(YarnConfiguration.RM_AM_EXPIRY_INTERVAL_MS, am_expire_ms); MyContainerManager containerManager = new MyContainerManager(); final MockRMWithAMS rm = new MockRMWithAMS(conf, containerManager); rm.start(); Long startTime = System.currentTimeMillis(); final Configuration conf = rm.getConfig(); final YarnRPC rpc = YarnRPC.create(conf); ApplicationMasterProtocol rmClient = null; AMRMTokenSecretManager appTokenSecretManager = rm.getRMContext().getAMRMTokenSecretManager(); MasterKeyData oldKey = appTokenSecretManager.getMasterKey(); Assert.assertNotNull(oldKey); try { MockNM nm1 = rm.registerNode("localhost:1234", 5120); RMApp app = rm.submitApp(1024); nm1.nodeHeartbeat(true); int waitCount = 0; while (containerManager.containerTokens == null && waitCount++ < maxWaitAttempts) { LOG.info("Waiting for AM Launch to happen.."); Thread.sleep(1000); } Assert.assertNotNull(containerManager.containerTokens); RMAppAttempt attempt = app.getCurrentAppAttempt(); ApplicationAttemptId applicationAttemptId = attempt.getAppAttemptId(); // Create a client to the RM. UserGroupInformation currentUser = UserGroupInformation .createRemoteUser(applicationAttemptId.toString()); Credentials credentials = containerManager.getContainerCredentials(); final InetSocketAddress rmBindAddress = rm.getApplicationMasterService().getBindAddress(); Token<? extends TokenIdentifier> amRMToken = MockRMWithAMS.setupAndReturnAMRMToken(rmBindAddress, credentials.getAllTokens()); currentUser.addToken(amRMToken); rmClient = createRMClient(rm, conf, rpc, currentUser); RegisterApplicationMasterRequest request = Records.newRecord(RegisterApplicationMasterRequest.class); rmClient.registerApplicationMaster(request); // One allocate call. AllocateRequest allocateRequest = Records.newRecord(AllocateRequest.class); Assert.assertTrue( rmClient.allocate(allocateRequest).getAMCommand() == null); // Wait for enough time and make sure the roll_over happens // At mean time, the old AMRMToken should continue to work while(System.currentTimeMillis() - startTime < rolling_interval_sec*1000) { rmClient.allocate(allocateRequest); Thread.sleep(500); } MasterKeyData newKey = appTokenSecretManager.getMasterKey(); Assert.assertNotNull(newKey); Assert.assertFalse("Master key should have changed!", oldKey.equals(newKey)); // Another allocate call with old AMRMToken. Should continue to work. rpc.stopProxy(rmClient, conf); // To avoid using cached client rmClient = createRMClient(rm, conf, rpc, currentUser); Assert .assertTrue(rmClient.allocate(allocateRequest).getAMCommand() == null); waitCount = 0; while(waitCount++ <= maxWaitAttempts) { if (appTokenSecretManager.getCurrnetMasterKeyData() != oldKey) { break; } try { rmClient.allocate(allocateRequest); } catch (Exception ex) { break; } Thread.sleep(200); } // active the nextMasterKey, and replace the currentMasterKey Assert.assertTrue(appTokenSecretManager.getCurrnetMasterKeyData().equals(newKey)); Assert.assertTrue(appTokenSecretManager.getMasterKey().equals(newKey)); Assert.assertTrue(appTokenSecretManager.getNextMasterKeyData() == null); // Create a new Token Token<AMRMTokenIdentifier> newToken = appTokenSecretManager.createAndGetAMRMToken(applicationAttemptId); SecurityUtil.setTokenService(newToken, rmBindAddress); currentUser.addToken(newToken); // Another allocate call. Should continue to work. rpc.stopProxy(rmClient, conf); // To avoid using cached client rmClient = createRMClient(rm, conf, rpc, currentUser); allocateRequest = Records.newRecord(AllocateRequest.class); Assert .assertTrue(rmClient.allocate(allocateRequest).getAMCommand() == null); // Should not work by using the old AMRMToken. rpc.stopProxy(rmClient, conf); // To avoid using cached client try { currentUser.addToken(amRMToken); rmClient = createRMClient(rm, conf, rpc, currentUser); allocateRequest = Records.newRecord(AllocateRequest.class); Assert .assertTrue(rmClient.allocate(allocateRequest).getAMCommand() == null); Assert.fail("The old Token should not work"); } catch (Exception ex) { // expect exception } } finally { rm.stop(); if (rmClient != null) { rpc.stopProxy(rmClient, conf); // To avoid using cached client } } } @Test (timeout = 20000) public void testAMRMMasterKeysUpdate() throws Exception { final AtomicReference<AMRMTokenSecretManager> spySecretMgrRef = new AtomicReference<AMRMTokenSecretManager>(); MockRM rm = new MockRM(conf) { @Override protected void doSecureLogin() throws IOException { // Skip the login. } @Override protected RMSecretManagerService createRMSecretManagerService() { return new RMSecretManagerService(conf, rmContext) { @Override protected AMRMTokenSecretManager createAMRMTokenSecretManager( Configuration conf, RMContext rmContext) { AMRMTokenSecretManager spySecretMgr = spy( super.createAMRMTokenSecretManager(conf, rmContext)); spySecretMgrRef.set(spySecretMgr); return spySecretMgr; } }; } }; rm.start(); MockNM nm = rm.registerNode("127.0.0.1:1234", 8000); RMApp app = rm.submitApp(200); MockAM am = MockRM.launchAndRegisterAM(app, rm, nm); AMRMTokenSecretManager spySecretMgr = spySecretMgrRef.get(); // Do allocate. Should not update AMRMToken AllocateResponse response = am.allocate(Records.newRecord(AllocateRequest.class)); Assert.assertNull(response.getAMRMToken()); Token<AMRMTokenIdentifier> oldToken = rm.getRMContext().getRMApps() .get(app.getApplicationId()) .getRMAppAttempt(am.getApplicationAttemptId()).getAMRMToken(); // roll over the master key // Do allocate again. the AM should get the latest AMRMToken rm.getRMContext().getAMRMTokenSecretManager().rollMasterKey(); response = am.allocate(Records.newRecord(AllocateRequest.class)); Assert.assertNotNull(response.getAMRMToken()); Token<AMRMTokenIdentifier> amrmToken = ConverterUtils.convertFromYarn(response.getAMRMToken(), new Text( response.getAMRMToken().getService())); Assert.assertEquals(amrmToken.decodeIdentifier().getKeyId(), rm .getRMContext().getAMRMTokenSecretManager().getMasterKey().getMasterKey() .getKeyId()); // Do allocate again with the same old token and verify the RM sends // back the last generated token instead of generating it again. reset(spySecretMgr); UserGroupInformation ugi = UserGroupInformation.createUserForTesting( am.getApplicationAttemptId().toString(), new String[0]); ugi.addTokenIdentifier(oldToken.decodeIdentifier()); response = am.doAllocateAs(ugi, Records.newRecord(AllocateRequest.class)); Assert.assertNotNull(response.getAMRMToken()); verify(spySecretMgr, never()).createAndGetAMRMToken(isA(ApplicationAttemptId.class)); // Do allocate again with the updated token and verify we do not // receive a new token to use. response = am.allocate(Records.newRecord(AllocateRequest.class)); Assert.assertNull(response.getAMRMToken()); // Activate the next master key. Since there is new master key generated // in AMRMTokenSecretManager. The AMRMToken will not get updated for AM rm.getRMContext().getAMRMTokenSecretManager().activateNextMasterKey(); response = am.allocate(Records.newRecord(AllocateRequest.class)); Assert.assertNull(response.getAMRMToken()); rm.stop(); } private ApplicationMasterProtocol createRMClient(final MockRM rm, final Configuration conf, final YarnRPC rpc, UserGroupInformation currentUser) { return currentUser.doAs(new PrivilegedAction<ApplicationMasterProtocol>() { @Override public ApplicationMasterProtocol run() { return (ApplicationMasterProtocol) rpc.getProxy(ApplicationMasterProtocol.class, rm .getApplicationMasterService().getBindAddress(), conf); } }); } }
VicoWu/hadoop-2.7.3
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/security/TestAMRMTokens.java
Java
apache-2.0
17,741
/* * Copyright 2014 The Netty Project * * The Netty Project 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 io.netty.handler.codec; import java.util.Map.Entry; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; import io.netty.util.AsciiString; import io.netty.util.CharsetUtil; public final class AsciiHeadersEncoder { /** * The separator characters to insert between a header name and a header value. */ public enum SeparatorType { /** * {@code ':'} */ COLON, /** * {@code ': '} */ COLON_SPACE, } /** * The newline characters to insert between header entries. */ public enum NewlineType { /** * {@code '\n'} */ LF, /** * {@code '\r\n'} */ CRLF } private final ByteBuf buf; private final SeparatorType separatorType; private final NewlineType newlineType; public AsciiHeadersEncoder(ByteBuf buf) { this(buf, SeparatorType.COLON_SPACE, NewlineType.CRLF); } public AsciiHeadersEncoder(ByteBuf buf, SeparatorType separatorType, NewlineType newlineType) { if (buf == null) { throw new NullPointerException("buf"); } if (separatorType == null) { throw new NullPointerException("separatorType"); } if (newlineType == null) { throw new NullPointerException("newlineType"); } this.buf = buf; this.separatorType = separatorType; this.newlineType = newlineType; } public void encode(Entry<CharSequence, CharSequence> entry) { final CharSequence name = entry.getKey(); final CharSequence value = entry.getValue(); final ByteBuf buf = this.buf; final int nameLen = name.length(); final int valueLen = value.length(); final int entryLen = nameLen + valueLen + 4; int offset = buf.writerIndex(); buf.ensureWritable(entryLen); writeAscii(buf, offset, name); offset += nameLen; switch (separatorType) { case COLON: buf.setByte(offset ++, ':'); break; case COLON_SPACE: buf.setByte(offset ++, ':'); buf.setByte(offset ++, ' '); break; default: throw new Error(); } writeAscii(buf, offset, value); offset += valueLen; switch (newlineType) { case LF: buf.setByte(offset ++, '\n'); break; case CRLF: buf.setByte(offset ++, '\r'); buf.setByte(offset ++, '\n'); break; default: throw new Error(); } buf.writerIndex(offset); } private static void writeAscii(ByteBuf buf, int offset, CharSequence value) { if (value instanceof AsciiString) { ByteBufUtil.copy((AsciiString) value, 0, buf, offset, value.length()); } else { buf.setCharSequence(offset, value, CharsetUtil.US_ASCII); } } }
wangcy6/storm_app
frame/java/netty-4.1/codec/src/main/java/io/netty/handler/codec/AsciiHeadersEncoder.java
Java
apache-2.0
3,720
// Copyright 2015 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // 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.devtools.build.lib.actions; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.devtools.build.lib.vfs.PathFragment; import java.io.IOException; import java.util.Map; /** Convenience wrapper around runfiles allowing lazy expansion. */ public interface RunfilesSupplier { /** @return the contained artifacts */ Iterable<Artifact> getArtifacts(); /** @return the runfiles' root directories. */ ImmutableSet<PathFragment> getRunfilesDirs(); /** * Returns mappings from runfiles directories to artifact mappings in that directory. * * @return runfiles' mappings * @throws IOException */ ImmutableMap<PathFragment, Map<PathFragment, Artifact>> getMappings() throws IOException; }
iamthearm/bazel
src/main/java/com/google/devtools/build/lib/actions/RunfilesSupplier.java
Java
apache-2.0
1,403
/* * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.corba.se.impl.dynamicany; import org.omg.CORBA.Any; import org.omg.CORBA.LocalObject; import org.omg.CORBA.TypeCode; import org.omg.CORBA.TCKind; import org.omg.DynamicAny.*; import org.omg.DynamicAny.DynAnyFactoryPackage.*; import com.sun.corba.se.spi.orb.ORB ; import com.sun.corba.se.spi.logging.CORBALogDomains ; import com.sun.corba.se.impl.logging.ORBUtilSystemException ; public class DynAnyFactoryImpl extends org.omg.CORBA.LocalObject implements org.omg.DynamicAny.DynAnyFactory { // // Instance variables // private ORB orb; // // Constructors // private DynAnyFactoryImpl() { this.orb = null; } public DynAnyFactoryImpl(ORB orb) { this.orb = orb; } // // DynAnyFactory interface methods // // Returns the most derived DynAny type based on the Anys TypeCode. public org.omg.DynamicAny.DynAny create_dyn_any (org.omg.CORBA.Any any) throws org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCode { return DynAnyUtil.createMostDerivedDynAny(any, orb, true); } // Returns the most derived DynAny type based on the TypeCode. public org.omg.DynamicAny.DynAny create_dyn_any_from_type_code (org.omg.CORBA.TypeCode type) throws org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCode { return DynAnyUtil.createMostDerivedDynAny(type, orb); } // Needed for org.omg.CORBA.Object private String[] __ids = { "IDL:omg.org/DynamicAny/DynAnyFactory:1.0" }; public String[] _ids() { return __ids; } }
rokn/Count_Words_2015
testing/openjdk/corba/src/share/classes/com/sun/corba/se/impl/dynamicany/DynAnyFactoryImpl.java
Java
mit
2,817
/* * Copyright 2012 GitHub 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.github.mobile.ui.user; import static com.github.mobile.Intents.EXTRA_USER; import android.os.Bundle; import android.support.v4.content.Loader; import android.view.View; import android.widget.ListView; import com.github.kevinsawicki.wishlist.SingleTypeAdapter; import com.github.mobile.R; import com.github.mobile.ThrowableLoader; import com.github.mobile.accounts.AccountUtils; import com.github.mobile.ui.ItemListFragment; import com.github.mobile.util.AvatarLoader; import com.google.inject.Inject; import java.util.List; import org.eclipse.egit.github.core.User; import org.eclipse.egit.github.core.service.OrganizationService; /** * Fragment to display the members of an org. */ public class MembersFragment extends ItemListFragment<User> implements OrganizationSelectionListener { private User org; @Inject private OrganizationService service; @Inject private AvatarLoader avatars; public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (org != null) outState.putSerializable(EXTRA_USER, org); } @Override public void onDetach() { OrganizationSelectionProvider selectionProvider = (OrganizationSelectionProvider) getActivity(); if (selectionProvider != null) selectionProvider.removeListener(this); super.onDetach(); } @Override public void onActivityCreated(Bundle savedInstanceState) { org = ((OrganizationSelectionProvider) getActivity()).addListener(this); if (org == null && savedInstanceState != null) org = (User) savedInstanceState.getSerializable(EXTRA_USER); setEmptyText(R.string.no_members); super.onActivityCreated(savedInstanceState); } @Override public Loader<List<User>> onCreateLoader(int id, Bundle args) { return new ThrowableLoader<List<User>>(getActivity(), items) { @Override public List<User> loadData() throws Exception { return service.getMembers(org.getLogin()); } }; } @Override protected SingleTypeAdapter<User> createAdapter(List<User> items) { User[] users = items.toArray(new User[items.size()]); return new UserListAdapter(getActivity().getLayoutInflater(), users, avatars); } @Override public void onOrganizationSelected(User organization) { int previousOrgId = org != null ? org.getId() : -1; org = organization; // Only hard refresh if view already created and org is changing if (previousOrgId != org.getId()) refreshWithProgress(); } @Override public void onListItemClick(ListView l, View v, int position, long id) { User user = (User) l.getItemAtPosition(position); if (!AccountUtils.isUser(getActivity(), user)) startActivity(UserViewActivity.createIntent(user)); } @Override protected int getErrorMessage(Exception exception) { return R.string.error_members_load; } }
samuelralak/ForkHub
app/src/main/java/com/github/mobile/ui/user/MembersFragment.java
Java
apache-2.0
3,683
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.indices.settings; import org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.test.ESIntegTestCase; import java.util.Collection; import java.util.Collections; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasToString; public class InternalSettingsIT extends ESIntegTestCase { @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return Collections.singleton(InternalOrPrivateSettingsPlugin.class); } @Override protected Collection<Class<? extends Plugin>> transportClientPlugins() { return Collections.singletonList(InternalOrPrivateSettingsPlugin.class); } public void testSetInternalIndexSettingOnCreate() { final Settings settings = Settings.builder().put("index.internal", "internal").build(); createIndex("index", settings); final GetSettingsResponse response = client().admin().indices().prepareGetSettings("index").get(); assertThat(response.getSetting("index", "index.internal"), equalTo("internal")); } public void testUpdateInternalIndexSettingViaSettingsAPI() { final Settings settings = Settings.builder().put("index.internal", "internal").build(); createIndex("test", settings); final GetSettingsResponse response = client().admin().indices().prepareGetSettings("test").get(); assertThat(response.getSetting("test", "index.internal"), equalTo("internal")); // we can not update the setting via the update settings API final IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> client().admin() .indices() .prepareUpdateSettings("test") .setSettings(Settings.builder().put("index.internal", "internal-update")) .get()); final String message = "can not update internal setting [index.internal]; this setting is managed via a dedicated API"; assertThat(e, hasToString(containsString(message))); final GetSettingsResponse responseAfterAttemptedUpdate = client().admin().indices().prepareGetSettings("test").get(); assertThat(responseAfterAttemptedUpdate.getSetting("test", "index.internal"), equalTo("internal")); } public void testUpdateInternalIndexSettingViaDedicatedAPI() { final Settings settings = Settings.builder().put("index.internal", "internal").build(); createIndex("test", settings); final GetSettingsResponse response = client().admin().indices().prepareGetSettings("test").get(); assertThat(response.getSetting("test", "index.internal"), equalTo("internal")); client().execute( InternalOrPrivateSettingsPlugin.UpdateInternalOrPrivateAction.INSTANCE, new InternalOrPrivateSettingsPlugin.UpdateInternalOrPrivateAction.Request("test", "index.internal", "internal-update")) .actionGet(); final GetSettingsResponse responseAfterUpdate = client().admin().indices().prepareGetSettings("test").get(); assertThat(responseAfterUpdate.getSetting("test", "index.internal"), equalTo("internal-update")); } }
strapdata/elassandra
server/src/test/java/org/elasticsearch/indices/settings/InternalSettingsIT.java
Java
apache-2.0
4,207
package org.apache.cordova.test; /* * * 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. * */ import org.apache.cordova.CordovaWebView; import org.apache.cordova.test.actions.backbuttonmultipage; import android.test.ActivityInstrumentationTestCase2; import android.view.KeyEvent; import android.view.inputmethod.BaseInputConnection; import android.widget.FrameLayout; import android.widget.LinearLayout; public class BackButtonMultiPageTest extends ActivityInstrumentationTestCase2<backbuttonmultipage> { private int TIMEOUT = 1000; backbuttonmultipage testActivity; private FrameLayout containerView; private LinearLayout innerContainer; private CordovaWebView testView; public BackButtonMultiPageTest() { super("org.apache.cordova.test", backbuttonmultipage.class); } protected void setUp() throws Exception { super.setUp(); testActivity = this.getActivity(); containerView = (FrameLayout) testActivity.findViewById(android.R.id.content); innerContainer = (LinearLayout) containerView.getChildAt(0); testView = (CordovaWebView) innerContainer.getChildAt(0); } public void testPreconditions(){ assertNotNull(innerContainer); assertNotNull(testView); } public void testViaHref() { testView.sendJavascript("window.location = 'sample2.html';"); sleep(); String url = testView.getUrl(); assertTrue(url.endsWith("sample2.html")); testView.sendJavascript("window.location = 'sample3.html';"); sleep(); url = testView.getUrl(); assertTrue(url.endsWith("sample3.html")); boolean didGoBack = testView.backHistory(); sleep(); url = testView.getUrl(); assertTrue(url.endsWith("sample2.html")); assertTrue(didGoBack); didGoBack = testView.backHistory(); sleep(); url = testView.getUrl(); assertTrue(url.endsWith("index.html")); assertTrue(didGoBack); } public void testViaLoadUrl() { testView.loadUrl("file:///android_asset/www/backbuttonmultipage/sample2.html"); sleep(); String url = testView.getUrl(); assertTrue(url.endsWith("sample2.html")); testView.loadUrl("file:///android_asset/www/backbuttonmultipage/sample3.html"); sleep(); url = testView.getUrl(); assertTrue(url.endsWith("sample3.html")); boolean didGoBack = testView.backHistory(); sleep(); url = testView.getUrl(); assertTrue(url.endsWith("sample2.html")); assertTrue(didGoBack); didGoBack = testView.backHistory(); sleep(); url = testView.getUrl(); assertTrue(url.endsWith("index.html")); assertTrue(didGoBack); } public void testViaBackButtonOnView() { testView.loadUrl("file:///android_asset/www/backbuttonmultipage/sample2.html"); sleep(); String url = testView.getUrl(); assertTrue(url.endsWith("sample2.html")); testView.loadUrl("file:///android_asset/www/backbuttonmultipage/sample3.html"); sleep(); url = testView.getUrl(); assertTrue(url.endsWith("sample3.html")); BaseInputConnection viewConnection = new BaseInputConnection(testView, true); KeyEvent backDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK); KeyEvent backUp = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK); viewConnection.sendKeyEvent(backDown); viewConnection.sendKeyEvent(backUp); sleep(); url = testView.getUrl(); assertTrue(url.endsWith("sample2.html")); viewConnection.sendKeyEvent(backDown); viewConnection.sendKeyEvent(backUp); sleep(); url = testView.getUrl(); assertTrue(url.endsWith("index.html")); } public void testViaBackButtonOnLayout() { testView.loadUrl("file:///android_asset/www/backbuttonmultipage/sample2.html"); sleep(); String url = testView.getUrl(); assertTrue(url.endsWith("sample2.html")); testView.loadUrl("file:///android_asset/www/backbuttonmultipage/sample3.html"); sleep(); url = testView.getUrl(); assertTrue(url.endsWith("sample3.html")); BaseInputConnection viewConnection = new BaseInputConnection(containerView, true); KeyEvent backDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK); KeyEvent backUp = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK); viewConnection.sendKeyEvent(backDown); viewConnection.sendKeyEvent(backUp); sleep(); url = testView.getUrl(); assertTrue(url.endsWith("sample2.html")); viewConnection.sendKeyEvent(backDown); viewConnection.sendKeyEvent(backUp); sleep(); url = testView.getUrl(); assertTrue(url.endsWith("index.html")); } private void sleep() { try { Thread.sleep(TIMEOUT); } catch (InterruptedException e) { fail("Unexpected Timeout"); } } }
tkerg/mark-three
test/src/org/apache/cordova/test/BackButtonMultiPageTest.java
Java
apache-2.0
5,660
/* * 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.logging.log4j.samples.app; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import org.apache.logging.log4j.EventLogger; import org.apache.logging.log4j.message.StructuredDataMessage; import org.apache.logging.log4j.samples.dto.AuditEvent; import org.apache.logging.log4j.samples.dto.Constraint; import org.apache.logging.log4j.samples.util.NamingUtils; /** * */ public class LogEventFactory { @SuppressWarnings("unchecked") public static <T extends AuditEvent> T getEvent(final Class<T> intrface) { final String eventId = NamingUtils.lowerFirst(intrface.getSimpleName()); final StructuredDataMessage msg = new StructuredDataMessage(eventId, null, "Audit"); return (T)Proxy.newProxyInstance(intrface .getClassLoader(), new Class<?>[]{intrface}, new AuditProxy(msg, intrface)); } private static class AuditProxy implements InvocationHandler { private final StructuredDataMessage msg; private final Class<?> intrface; public AuditProxy(final StructuredDataMessage msg, final Class<?> intrface) { this.msg = msg; this.intrface = intrface; } @Override public Object invoke(final Object o, final Method method, final Object[] objects) throws Throwable { if (method.getName().equals("logEvent")) { final StringBuilder missing = new StringBuilder(); final Method[] methods = intrface.getMethods(); for (final Method _method : methods) { final String name = NamingUtils.lowerFirst(NamingUtils .getMethodShortName(_method.getName())); final Annotation[] annotations = _method.getDeclaredAnnotations(); for (final Annotation annotation : annotations) { final Constraint constraint = (Constraint) annotation; if (constraint.required() && msg.get(name) == null) { if (missing.length() > 0) { missing.append(", "); } missing.append(name); } } } if (missing.length() > 0) { throw new IllegalStateException("Event " + msg.getId().getName() + " is missing required attributes " + missing); } EventLogger.logEvent(msg); } if (method.getName().equals("setCompletionStatus")) { final String name = NamingUtils.lowerFirst(NamingUtils.getMethodShortName(method.getName())); msg.put(name, objects[0].toString()); } if (method.getName().startsWith("set")) { final String name = NamingUtils.lowerFirst(NamingUtils.getMethodShortName(method.getName())); /* * Perform any validation here. Currently the catalog doesn't * contain any information on validation rules. */ msg.put(name, objects[0].toString()); } return null; } } }
apache/logging-log4j2
log4j-samples/log4j-samples-flume-common/src/main/java/org/apache/logging/log4j/samples/app/LogEventFactory.java
Java
apache-2.0
4,153
/* * 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.deltaspike.core.util.metadata.builder; import org.apache.deltaspike.core.util.HierarchyDiscovery; import javax.enterprise.inject.spi.Annotated; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * The base class for all New Annotated types. */ abstract class AnnotatedImpl implements Annotated { private final Type type; private final Set<Type> typeClosure; private final AnnotationStore annotations; protected AnnotatedImpl(Class<?> type, AnnotationStore annotations, Type genericType, Type overriddenType) { if (overriddenType == null) { if (genericType != null) { typeClosure = new HierarchyDiscovery(genericType).getTypeClosure(); this.type = genericType; } else { typeClosure = new HierarchyDiscovery(type).getTypeClosure(); this.type = type; } } else { this.type = overriddenType; typeClosure = Collections.singleton(overriddenType); } if (annotations == null) { this.annotations = new AnnotationStore(); } else { this.annotations = annotations; } } /** * {@inheritDoc} */ @Override public <T extends Annotation> T getAnnotation(Class<T> annotationType) { return annotations.getAnnotation(annotationType); } /** * {@inheritDoc} */ @Override public Set<Annotation> getAnnotations() { return annotations.getAnnotations(); } /** * {@inheritDoc} */ @Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) { return annotations.isAnnotationPresent(annotationType); } /** * {@inheritDoc} */ @Override public Set<Type> getTypeClosure() { return new HashSet<Type>(typeClosure); } /** * {@inheritDoc} */ @Override public Type getBaseType() { return type; } }
idontgotit/deltaspike
deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/metadata/builder/AnnotatedImpl.java
Java
apache-2.0
3,021
package org.nutz.lang.born; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import org.nutz.castor.Castors; import org.nutz.lang.Lang; import org.nutz.lang.MatchType; import org.nutz.lang.Mirror; /** * 关于创建对象的一些帮助方法 * * @author zozoh([email protected]) */ public abstract class Borns { /** * 根据参数类型数组获取一个对象的构建信息 * * @param <T> * 对象类型信息 * @param type * 对象类型 * @param argTypes * 构造参数类型数组 * @return 构建信息对象 */ public static <T> BornContext<T> evalByArgTypes(Class<T> type, Class<?>... argTypes) { BornContext<T> re; if (argTypes.length == 0) { re = evalWithoutArgs(type); } else { re = evalWithArgTypes(true, type, argTypes, null); } return re; } /** * 根据参数类型数组获取一个对象的构建信息 * * @param <T> * 对象类型信息 * @param type * 对象类型 * @param args * 构造参数数组 * @return 构建信息对象 * @throws NullPointerException * when args is null */ public static <T> BornContext<T> eval(Class<T> type, Object... args) { BornContext<T> re; if (args.length == 0) { re = evalWithoutArgs(type); } else { re = evalWithArgs(type, args); } return re; } /** * 根据一个调用参数数组,获取一个对象的构建信息 * * @param <T> * 对象类型信息 * @param type * 对象类型 * @param args * 参考构建参数 * @return 构建信息对象 */ private static <T> BornContext<T> evalWithArgs(Class<T> type, Object[] args) { // 准备变参数组 Object dynaArg = Mirror.evalArgToSameTypeRealArray(args); // 准备好参数类型 Class<?>[] argTypes = Mirror.evalToTypes(args); BornContext<T> re = evalWithArgTypes(false, type, argTypes, dynaArg); if (null == re) return null; if (MatchType.LACK == re.getMatchType()) { re.setArgs(Lang.arrayLast(args, re.getLackArg())); } else { re.setArgs(args); } switch (re.getMatchType()) { case LACK: re.setArgs(Lang.arrayLast(args, re.getLackArg())); break; case NEED_CAST: re.setArgs(Lang.array2ObjectArray(args, re.getCastType())); break; default: re.setArgs(args); } return re; } /** * 根据一个调用参数类型数组,获取一个对象的构建信息 * * @param <T> * 对象类型信息 * @param accurate * 是否需要精确匹配 * @param type * 对象类型 * @param argTypes * 参考参数类型数组 * @param dynaAry * 参考参数类型信息是否是一个变参数组 * @return 构建信息对象 */ @SuppressWarnings({"rawtypes", "unchecked"}) private static <T> BornContext<T> evalWithArgTypes(boolean accurate, Class<T> type, Class<?>[] argTypes, Object dynaArg) { // 准备好返回对象 BornContext<T> re = new BornContext<T>(); // 先看看有没对应的构造函数 Mirror<T> mirror = Mirror.me(type); for (Constructor<?> cc : type.getConstructors()) { Class<?>[] pts = cc.getParameterTypes(); MatchType mt = Mirror.matchParamTypes(pts, argTypes); re.setMatchType(mt); // 正好合适 if (MatchType.YES == mt) { return re.setBorning(new ConstructorBorning(cc)); } // 差一个参数,说明这个构造函数有变参数组 else if (MatchType.LACK == mt) { re.setLackArg(Mirror.blankArrayArg(pts)); return re.setBorning(new ConstructorBorning(cc)); } // 看看整个输入的参数是不是变参 else if (null != dynaArg && pts.length == 1 && pts[0] == dynaArg.getClass()) { return re.setBorning(new DynamicConstructorBorning(cc)); } } // 看看有没有对应静态工厂函数 Method[] sms = mirror.getStaticMethods(); for (Method m : sms) { Class<?>[] pts = m.getParameterTypes(); MatchType mt = Mirror.matchParamTypes(pts, argTypes); re.setMatchType(mt); if (MatchType.YES == mt) { return re.setBorning(new MethodBorning<T>(m)); } else if (MatchType.LACK == mt) { re.setLackArg(Mirror.blankArrayArg(pts)); return re.setBorning(new MethodBorning<T>(m)); } else if (null != dynaArg && pts.length == 1) { if (pts[0] == dynaArg.getClass()) { return re.setBorning(new DynaMethodBorning<T>(m)); } } } // 如果不是要精确查找的话 if (!accurate) { // 找到一个长度合适的构造函数,准备转换 try { for (Constructor<?> cc : type.getConstructors()) { Class<?>[] pts = cc.getParameterTypes(); if (canBeCasted(argTypes, pts)) { re.setMatchType(MatchType.NEED_CAST); re.setCastType(pts); return re.setBorning(new ConstructorCastingBorning(cc)); } } } catch (RuntimeException e) {} // 有没有变参的静态构造方法 try { for (Method m : sms) { Class<?>[] pts = m.getParameterTypes(); if (canBeCasted(argTypes, pts)) { re.setMatchType(MatchType.NEED_CAST); re.setCastType(pts); return re.setBorning(new MethodCastingBorning<T>(m)); } } } catch (Exception e) {} } return null; } private static boolean canBeCasted(Class<?>[] argTypes, Class<?>[] pts) { if (pts.length != argTypes.length) return false; for (int i = 0; i < pts.length; i++) { if (!Castors.me().canCast(argTypes[i], pts[i])) return false; } return true; } /** * 为一个给定类,寻找一个不需要参数的构造方法 * * @param <T> * 类 * @param type * 类实例 * @return 构造信息 */ @SuppressWarnings({"rawtypes", "unchecked"}) private static <T> BornContext<T> evalWithoutArgs(Class<T> type) { // 准备好返回对象 BornContext<T> re = new BornContext<T>(); Mirror<T> mirror = Mirror.me(type); boolean isAbstract = Modifier.isAbstract(type.getModifiers()); // 先看看有没有默认构造函数 try { if (!isAbstract) { re.setBorning(new EmptyArgsConstructorBorning<T>(type.getConstructor())); return re.setArgs(new Object[0]); } } // 如果没有默认构造函数 ... catch (Exception e) {} // 看看有没有默认静态工厂函数 Method[] stMethods = mirror.getStaticMethods(); for (Method m : stMethods) { if (m.getReturnType().equals(type) && m.getParameterTypes().length == 0) { return re.setBorning(new EmptyArgsMethodBorning<T>(m)).setArgs(new Object[0]); } } // 看看有没有带一个动态参数的构造函数 if (!isAbstract) { for (Constructor<?> cons : type.getConstructors()) { Class<?>[] pts = cons.getParameterTypes(); if (pts.length == 1 && pts[0].isArray()) { Object[] args = new Object[1]; args[0] = Mirror.blankArrayArg(pts); return re.setBorning(new ConstructorBorning(cons)).setArgs(args); } } } // 看看有没有带一个动态参数的静态工厂函数 for (Method m : stMethods) { Class<?>[] pts = m.getParameterTypes(); if (m.getReturnType() == type && m.getParameterTypes().length == 1 && pts[0].isArray()) { Object[] args = new Object[1]; args[0] = Mirror.blankArrayArg(pts); return re.setBorning(new MethodBorning<T>(m)).setArgs(args); } } return null; } }
lzxz1234/nutz
src/org/nutz/lang/born/Borns.java
Java
apache-2.0
7,435
/* * Copyright (C) 2008 The Guava 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 * * 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.common.collect.testing.features; import static com.google.common.truth.Truth.assertThat; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Method; import java.util.Collections; import java.util.Set; import junit.framework.TestCase; /** @author George van den Driessche */ // Enum values use constructors with generic varargs. @SuppressWarnings("unchecked") public class FeatureUtilTest extends TestCase { interface ExampleBaseInterface { void behave(); } interface ExampleDerivedInterface extends ExampleBaseInterface { void misbehave(); } enum ExampleBaseFeature implements Feature<ExampleBaseInterface> { BASE_FEATURE_1, BASE_FEATURE_2; @Override public Set<Feature<? super ExampleBaseInterface>> getImpliedFeatures() { return Collections.emptySet(); } @Retention(RetentionPolicy.RUNTIME) @Inherited @TesterAnnotation @interface Require { ExampleBaseFeature[] value() default {}; ExampleBaseFeature[] absent() default {}; } } enum ExampleDerivedFeature implements Feature<ExampleDerivedInterface> { DERIVED_FEATURE_1, DERIVED_FEATURE_2(ExampleBaseFeature.BASE_FEATURE_1), DERIVED_FEATURE_3, COMPOUND_DERIVED_FEATURE( DERIVED_FEATURE_1, DERIVED_FEATURE_2, ExampleBaseFeature.BASE_FEATURE_2); private Set<Feature<? super ExampleDerivedInterface>> implied; ExampleDerivedFeature(Feature<? super ExampleDerivedInterface>... implied) { this.implied = ImmutableSet.copyOf(implied); } @Override public Set<Feature<? super ExampleDerivedInterface>> getImpliedFeatures() { return implied; } @Retention(RetentionPolicy.RUNTIME) @Inherited @TesterAnnotation @interface Require { ExampleDerivedFeature[] value() default {}; ExampleDerivedFeature[] absent() default {}; } } @Retention(RetentionPolicy.RUNTIME) @interface NonTesterAnnotation {} @ExampleBaseFeature.Require({ExampleBaseFeature.BASE_FEATURE_1}) private abstract static class ExampleBaseInterfaceTester extends TestCase { protected final void doNotActuallyRunThis() { fail("Nobody's meant to actually run this!"); } } @AndroidIncompatible // Android attempts to run directly @NonTesterAnnotation @ExampleDerivedFeature.Require({ExampleDerivedFeature.DERIVED_FEATURE_2}) private static class ExampleDerivedInterfaceTester extends ExampleBaseInterfaceTester { // Exists to test that our framework doesn't run it: @SuppressWarnings("unused") @ExampleDerivedFeature.Require({ ExampleDerivedFeature.DERIVED_FEATURE_1, ExampleDerivedFeature.DERIVED_FEATURE_2 }) public void testRequiringTwoExplicitDerivedFeatures() throws Exception { doNotActuallyRunThis(); } // Exists to test that our framework doesn't run it: @SuppressWarnings("unused") @ExampleDerivedFeature.Require({ ExampleDerivedFeature.DERIVED_FEATURE_1, ExampleDerivedFeature.DERIVED_FEATURE_3 }) public void testRequiringAllThreeDerivedFeatures() { doNotActuallyRunThis(); } // Exists to test that our framework doesn't run it: @SuppressWarnings("unused") @ExampleBaseFeature.Require(absent = {ExampleBaseFeature.BASE_FEATURE_1}) public void testRequiringConflictingFeatures() throws Exception { doNotActuallyRunThis(); } } @ExampleDerivedFeature.Require(absent = {ExampleDerivedFeature.DERIVED_FEATURE_2}) private static class ConflictingRequirementsExampleDerivedInterfaceTester extends ExampleBaseInterfaceTester {} public void testTestFeatureEnums() throws Exception { // Haha! Let's test our own test rig! FeatureEnumTest.assertGoodFeatureEnum(FeatureUtilTest.ExampleBaseFeature.class); FeatureEnumTest.assertGoodFeatureEnum(FeatureUtilTest.ExampleDerivedFeature.class); } public void testAddImpliedFeatures_returnsSameSetInstance() throws Exception { Set<Feature<?>> features = Sets.<Feature<?>>newHashSet(ExampleBaseFeature.BASE_FEATURE_1); assertSame(features, FeatureUtil.addImpliedFeatures(features)); } public void testAddImpliedFeatures_addsImpliedFeatures() throws Exception { Set<Feature<?>> features; features = Sets.<Feature<?>>newHashSet(ExampleDerivedFeature.DERIVED_FEATURE_1); assertThat(FeatureUtil.addImpliedFeatures(features)) .contains(ExampleDerivedFeature.DERIVED_FEATURE_1); features = Sets.<Feature<?>>newHashSet(ExampleDerivedFeature.DERIVED_FEATURE_2); assertThat(FeatureUtil.addImpliedFeatures(features)) .containsExactly( ExampleDerivedFeature.DERIVED_FEATURE_2, ExampleBaseFeature.BASE_FEATURE_1); features = Sets.<Feature<?>>newHashSet(ExampleDerivedFeature.COMPOUND_DERIVED_FEATURE); assertThat(FeatureUtil.addImpliedFeatures(features)) .containsExactly( ExampleDerivedFeature.COMPOUND_DERIVED_FEATURE, ExampleDerivedFeature.DERIVED_FEATURE_1, ExampleDerivedFeature.DERIVED_FEATURE_2, ExampleBaseFeature.BASE_FEATURE_1, ExampleBaseFeature.BASE_FEATURE_2); } public void testImpliedFeatures_returnsNewSetInstance() throws Exception { Set<Feature<?>> features = Sets.<Feature<?>>newHashSet(ExampleBaseFeature.BASE_FEATURE_1); assertNotSame(features, FeatureUtil.impliedFeatures(features)); } public void testImpliedFeatures_returnsImpliedFeatures() throws Exception { Set<Feature<?>> features; features = Sets.<Feature<?>>newHashSet(ExampleDerivedFeature.DERIVED_FEATURE_1); assertTrue(FeatureUtil.impliedFeatures(features).isEmpty()); features = Sets.<Feature<?>>newHashSet(ExampleDerivedFeature.DERIVED_FEATURE_2); assertThat(FeatureUtil.impliedFeatures(features)).contains(ExampleBaseFeature.BASE_FEATURE_1); features = Sets.<Feature<?>>newHashSet(ExampleDerivedFeature.COMPOUND_DERIVED_FEATURE); assertThat(FeatureUtil.impliedFeatures(features)) .containsExactly( ExampleDerivedFeature.DERIVED_FEATURE_1, ExampleDerivedFeature.DERIVED_FEATURE_2, ExampleBaseFeature.BASE_FEATURE_1, ExampleBaseFeature.BASE_FEATURE_2); } @AndroidIncompatible // Android runs ExampleDerivedInterfaceTester directly if it exists public void testBuildTesterRequirements_class() throws Exception { assertEquals( FeatureUtil.buildTesterRequirements(ExampleBaseInterfaceTester.class), new TesterRequirements( Sets.<Feature<?>>newHashSet(ExampleBaseFeature.BASE_FEATURE_1), Collections.<Feature<?>>emptySet())); assertEquals( FeatureUtil.buildTesterRequirements(ExampleDerivedInterfaceTester.class), new TesterRequirements( Sets.<Feature<?>>newHashSet( ExampleBaseFeature.BASE_FEATURE_1, ExampleDerivedFeature.DERIVED_FEATURE_2), Collections.<Feature<?>>emptySet())); } @AndroidIncompatible // Android runs ExampleDerivedInterfaceTester directly if it exists public void testBuildTesterRequirements_method() throws Exception { assertEquals( FeatureUtil.buildTesterRequirements( ExampleDerivedInterfaceTester.class.getMethod( "testRequiringTwoExplicitDerivedFeatures")), new TesterRequirements( Sets.<Feature<?>>newHashSet( ExampleBaseFeature.BASE_FEATURE_1, ExampleDerivedFeature.DERIVED_FEATURE_1, ExampleDerivedFeature.DERIVED_FEATURE_2), Collections.<Feature<?>>emptySet())); assertEquals( FeatureUtil.buildTesterRequirements( ExampleDerivedInterfaceTester.class.getMethod("testRequiringAllThreeDerivedFeatures")), new TesterRequirements( Sets.<Feature<?>>newHashSet( ExampleBaseFeature.BASE_FEATURE_1, ExampleDerivedFeature.DERIVED_FEATURE_1, ExampleDerivedFeature.DERIVED_FEATURE_2, ExampleDerivedFeature.DERIVED_FEATURE_3), Collections.<Feature<?>>emptySet())); } @AndroidIncompatible // Android runs ExampleDerivedInterfaceTester directly if it exists public void testBuildTesterRequirements_classClassConflict() throws Exception { try { FeatureUtil.buildTesterRequirements( ConflictingRequirementsExampleDerivedInterfaceTester.class); fail("Expected ConflictingRequirementsException"); } catch (ConflictingRequirementsException e) { assertThat(e.getConflicts()).contains(ExampleBaseFeature.BASE_FEATURE_1); assertEquals(ConflictingRequirementsExampleDerivedInterfaceTester.class, e.getSource()); } } @AndroidIncompatible // Android runs ExampleDerivedInterfaceTester directly if it exists public void testBuildTesterRequirements_methodClassConflict() throws Exception { final Method method = ExampleDerivedInterfaceTester.class.getMethod("testRequiringConflictingFeatures"); try { FeatureUtil.buildTesterRequirements(method); fail("Expected ConflictingRequirementsException"); } catch (ConflictingRequirementsException e) { assertThat(e.getConflicts()).contains(ExampleBaseFeature.BASE_FEATURE_1); assertEquals(method, e.getSource()); } } @AndroidIncompatible // Android runs ExampleDerivedInterfaceTester directly if it exists public void testBuildDeclaredTesterRequirements() throws Exception { assertEquals( FeatureUtil.buildDeclaredTesterRequirements( ExampleDerivedInterfaceTester.class.getMethod( "testRequiringTwoExplicitDerivedFeatures")), new TesterRequirements( FeatureUtil.addImpliedFeatures( Sets.<Feature<?>>newHashSet( ExampleDerivedFeature.DERIVED_FEATURE_1, ExampleDerivedFeature.DERIVED_FEATURE_2)), Collections.<Feature<?>>emptySet())); } }
rgoldberg/guava
guava-testlib/test/com/google/common/collect/testing/features/FeatureUtilTest.java
Java
apache-2.0
10,710
/* ******************************************************************************* * Copyright (C) 2006-2008, International Business Machines Corporation and * * others. All Rights Reserved. * ******************************************************************************* */ package com.ibm.icu.charset; /** * Defines the UConverterSharedData struct, the immutable, shared part of * UConverter. */ final class UConverterSharedData { // uint32_t structSize; /* Size of this structure */ // int structSize; /* Size of this structure */ /** * used to count number of clients, 0xffffffff for static SharedData */ int referenceCounter; // agljport:todo const void *dataMemory; /* from udata_openChoice() - for cleanup */ // agljport:todo void *table; /* Unused. This used to be a UConverterTable - Pointer to conversion data - see mbcs below */ // const UConverterStaticData *staticData; /* pointer to the static (non changing) data. */ /** * pointer to the static (non changing) * data. */ UConverterStaticData staticData; // UBool sharedDataCached; /* TRUE: shared data is in cache, don't destroy // on close() if 0 ref. FALSE: shared data isn't in the cache, do attempt to // clean it up if the ref is 0 */ /** * TRUE: shared data is in cache, don't destroy * on close() if 0 ref. FALSE: shared data isn't * in the cache, do attempt to clean it up if * the ref is 0 */ boolean sharedDataCached; /* * UBool staticDataOwned; TRUE if static data owned by shared data & should * be freed with it, NEVER true for udata() loaded statics. This ignored * variable was removed to make space for sharedDataCached. */ // const UConverterImpl *impl; /* vtable-style struct of mostly function pointers */ // UConverterImpl impl; /* vtable-style struct of mostly function pointers */ /** initial values of some members of the mutable part of object */ long toUnicodeStatus; /** * Shared data structures currently come in two flavors: * - readonly for built-in algorithmic converters * - allocated for MBCS, with a pointer to an allocated UConverterTable * which always has a UConverterMBCSTable * * To eliminate one allocation, I am making the UConverterMBCSTable a member * of the shared data. It is the last member so that static definitions of * UConverterSharedData work as before. The table field above also remains * to avoid updating all static definitions, but is now unused. * */ CharsetMBCS.UConverterMBCSTable mbcs; UConverterSharedData() { mbcs = new CharsetMBCS.UConverterMBCSTable(); } UConverterSharedData(int referenceCounter_, UConverterStaticData staticData_, boolean sharedDataCached_, long toUnicodeStatus_) { this(); referenceCounter = referenceCounter_; staticData = staticData_; sharedDataCached = sharedDataCached_; // impl = impl_; toUnicodeStatus = toUnicodeStatus_; } /** * UConverterImpl contains all the data and functions for a converter type. * Its function pointers work much like a C++ vtable. Many converter types * need to define only a subset of the functions; when a function pointer is * NULL, then a default action will be performed. * * Every converter type must implement toUnicode, fromUnicode, and * getNextUChar, otherwise the converter may crash. Every converter type * that has variable-length codepage sequences should also implement * toUnicodeWithOffsets and fromUnicodeWithOffsets for correct offset * handling. All other functions may or may not be implemented - it depends * only on whether the converter type needs them. * * When open() fails, then close() will be called, if present. */ /* class UConverterImpl { UConverterType type; UConverterToUnicode toUnicode; protected void doToUnicode(UConverterToUnicodeArgs args, int[] pErrorCode) { } final void toUnicode(UConverterToUnicodeArgs args, int[] pErrorCode) { doToUnicode(args, pErrorCode); } //UConverterFromUnicode fromUnicode; protected void doFromUnicode(UConverterFromUnicodeArgs args, int[] pErrorCode) { } final void fromUnicode(UConverterFromUnicodeArgs args, int[] pErrorCode) { doFromUnicode(args, pErrorCode); } protected int doGetNextUChar(UConverterToUnicodeArgs args, int[] pErrorCode) { return 0; } //UConverterGetNextUChar getNextUChar; final int getNextUChar(UConverterToUnicodeArgs args, int[] pErrorCode) { return doGetNextUChar(args, pErrorCode); } // interface UConverterImplLoadable extends UConverterImpl protected void doLoad(UConverterLoadArgs pArgs, short[] raw, int[] pErrorCode) { } protected void doUnload() { } // interface UConverterImplOpenable extends UConverterImpl protected void doOpen(UConverter cnv, String name, String locale, long options, int[] pErrorCode) { } //UConverterOpen open; final void open(UConverter cnv, String name, String locale, long options, int[] pErrorCode) { doOpen(cnv, name, locale, options, pErrorCode); } protected void doClose(UConverter cnv) { } //UConverterClose close; final void close(UConverter cnv) { doClose(cnv); } protected void doReset(UConverter cnv, int choice) { } //typedef void (*UConverterReset) (UConverter *cnv, UConverterResetChoice choice); //UConverterReset reset; final void reset(UConverter cnv, int choice) { doReset(cnv, choice); } // interface UConverterImplVariableLength extends UConverterImpl protected void doToUnicodeWithOffsets(UConverterToUnicodeArgs args, int[] pErrorCode) { } //UConverterToUnicode toUnicodeWithOffsets; final void toUnicodeWithOffsets(UConverterToUnicodeArgs args, int[] pErrorCode) { doToUnicodeWithOffsets(args, pErrorCode); } protected void doFromUnicodeWithOffsets(UConverterFromUnicodeArgs args, int[] pErrorCode) { } //UConverterFromUnicode fromUnicodeWithOffsets; final void fromUnicodeWithOffsets(UConverterFromUnicodeArgs args, int[] pErrorCode) { doFromUnicodeWithOffsets(args, pErrorCode); } // interface UConverterImplMisc extends UConverterImpl protected void doGetStarters(UConverter converter, boolean starters[], int[] pErrorCode) { } //UConverterGetStarters getStarters; final void getStarters(UConverter converter, boolean starters[], int[] pErrorCode) { doGetStarters(converter, starters, pErrorCode); } protected String doGetName(UConverter cnv) { return ""; } //UConverterGetName getName; final String getName(UConverter cnv) { return doGetName(cnv); } protected void doWriteSub(UConverterFromUnicodeArgs pArgs, long offsetIndex, int[] pErrorCode) { } //UConverterWriteSub writeSub; final void writeSub(UConverterFromUnicodeArgs pArgs, long offsetIndex, int[] pErrorCode) { doWriteSub(pArgs, offsetIndex, pErrorCode); } protected UConverter doSafeClone(UConverter cnv, byte[] stackBuffer, int[] pBufferSize, int[] status) { return new UConverter(); } //UConverterSafeClone safeClone; final UConverter safeClone(UConverter cnv, byte[] stackBuffer, int[] pBufferSize, int[] status) { return doSafeClone(cnv, stackBuffer, pBufferSize, status); } protected void doGetUnicodeSet(UConverter cnv, UnicodeSet /*USetAdder* / sa, int /*UConverterUnicodeSet* / which, int[] pErrorCode) { } //UConverterGetUnicodeSet getUnicodeSet; // final void getUnicodeSet(UConverter cnv, UnicodeSet /*USetAdder* / sa, int /*UConverterUnicodeSet* / which, int[] pErrorCode) //{ // doGetUnicodeSet(cnv, sa, which, pErrorCode); //} //} static final String DATA_TYPE = "cnv"; private static final int CNV_DATA_BUFFER_SIZE = 25000; static final int sizeofUConverterSharedData = 100; //static UDataMemoryIsAcceptable isCnvAcceptable; /** * Load a non-algorithmic converter. * If pkg==NULL, then this function must be called inside umtx_lock(&cnvCacheMutex). // UConverterSharedData * load(UConverterLoadArgs *pArgs, UErrorCode *err) static final UConverterSharedData load(UConverterLoadArgs pArgs, int[] err) { UConverterSharedData mySharedConverterData = null; if(err == null || ErrorCode.isFailure(err[0])) { return null; } if(pArgs.pkg != null && pArgs.pkg.length() != 0) { application-provided converters are not currently cached return UConverterSharedData.createConverterFromFile(pArgs, err); } //agljport:fix mySharedConverterData = getSharedConverterData(pArgs.name); if (mySharedConverterData == null) { Not cached, we need to stream it in from file mySharedConverterData = UConverterSharedData.createConverterFromFile(pArgs, err); if (ErrorCode.isFailure(err[0]) || (mySharedConverterData == null)) { return null; } else { share it with other library clients //agljport:fix shareConverterData(mySharedConverterData); } } else { The data for this converter was already in the cache. Update the reference counter on the shared data: one more client mySharedConverterData.referenceCounter++; } return mySharedConverterData; } Takes an alias name gets an actual converter file name *goes to disk and opens it. *allocates the memory and returns a new UConverter object //static UConverterSharedData *createConverterFromFile(UConverterLoadArgs *pArgs, UErrorCode * err) static final UConverterSharedData createConverterFromFile(UConverterLoadArgs pArgs, int[] err) { UDataMemory data = null; UConverterSharedData sharedData = null; //agljport:todo UTRACE_ENTRY_OC(UTRACE_LOAD); if (err == null || ErrorCode.isFailure(err[0])) { //agljport:todo UTRACE_EXIT_STATUS(*err); return null; } //agljport:todo UTRACE_DATA2(UTRACE_OPEN_CLOSE, "load converter %s from package %s", pArgs->name, pArgs->pkg); //agljport:fix data = udata_openChoice(pArgs.pkgArray, DATA_TYPE.getBytes(), pArgs.name, isCnvAcceptable, null, err); if(ErrorCode.isFailure(err[0])) { //agljport:todo UTRACE_EXIT_STATUS(*err); return null; } sharedData = data_unFlattenClone(pArgs, data, err); if(ErrorCode.isFailure(err[0])) { //agljport:fix udata_close(data); //agljport:todo UTRACE_EXIT_STATUS(*err); return null; } * TODO Store pkg in a field in the shared data so that delta-only converters * can load base converters from the same package. * If the pkg name is longer than the field, then either do not load the converter * in the first place, or just set the pkg field to "". return sharedData; } */ UConverterDataReader dataReader = null; /* * returns a converter type from a string */ /* static final UConverterSharedData getAlgorithmicTypeFromName(String realName) { long mid, start, limit; long lastMid; int result; StringBuffer strippedName = new StringBuffer(UConverterConstants.MAX_CONVERTER_NAME_LENGTH); // Lower case and remove ignoreable characters. UConverterAlias.stripForCompare(strippedName, realName); // do a binary search for the alias start = 0; limit = cnvNameType.length; mid = limit; lastMid = -1; for (;;) { mid = (long)((start + limit) / 2); if (lastMid == mid) { // Have we moved? break; // We haven't moved, and it wasn't found. } lastMid = mid; result = strippedName.substring(0).compareTo(cnvNameType[(int)mid].name); if (result < 0) { limit = mid; } else if (result > 0) { start = mid; } else { return converterData[cnvNameType[(int)mid].type]; } } return null; }*/ /* * Enum for specifying basic types of converters */ static final class UConverterType { static final int UNSUPPORTED_CONVERTER = -1; static final int SBCS = 0; static final int DBCS = 1; static final int MBCS = 2; static final int LATIN_1 = 3; static final int UTF8 = 4; static final int UTF16_BigEndian = 5; static final int UTF16_LittleEndian = 6; static final int UTF32_BigEndian = 7; static final int UTF32_LittleEndian = 8; static final int EBCDIC_STATEFUL = 9; static final int ISO_2022 = 10; static final int LMBCS_1 = 11; static final int LMBCS_2 = LMBCS_1 + 1; // 12 static final int LMBCS_3 = LMBCS_2 + 1; // 13 static final int LMBCS_4 = LMBCS_3 + 1; // 14 static final int LMBCS_5 = LMBCS_4 + 1; // 15 static final int LMBCS_6 = LMBCS_5 + 1; // 16 static final int LMBCS_8 = LMBCS_6 + 1; // 17 static final int LMBCS_11 = LMBCS_8 + 1; // 18 static final int LMBCS_16 = LMBCS_11 + 1; // 19 static final int LMBCS_17 = LMBCS_16 + 1; // 20 static final int LMBCS_18 = LMBCS_17 + 1; // 21 static final int LMBCS_19 = LMBCS_18 + 1; // 22 static final int LMBCS_LAST = LMBCS_19; // 22 static final int HZ = LMBCS_LAST + 1; // 23 static final int SCSU = HZ + 1; // 24 static final int ISCII = SCSU + 1; // 25 static final int US_ASCII = ISCII + 1; // 26 static final int UTF7 = US_ASCII + 1; // 27 static final int BOCU1 = UTF7 + 1; // 28 static final int UTF16 = BOCU1 + 1; // 29 static final int UTF32 = UTF16 + 1; // 30 static final int CESU8 = UTF32 + 1; // 31 static final int IMAP_MAILBOX = CESU8 + 1; // 32 // Number of converter types for which we have conversion routines. static final int NUMBER_OF_SUPPORTED_CONVERTER_TYPES = IMAP_MAILBOX + 1; } /** * Enum for specifying which platform a converter ID refers to. The use of * platform/CCSID is not recommended. See openCCSID(). */ static final class UConverterPlatform { static final int UNKNOWN = -1; static final int IBM = 0; } // static UConverterSharedData[] converterData; /* static class cnvNameTypeClass { String name; int type; cnvNameTypeClass(String name_, int type_) { name = name_; type = type_; } } static cnvNameTypeClass cnvNameType[];*/ static final String DATA_TYPE = "cnv"; //static final int CNV_DATA_BUFFER_SIZE = 25000; //static final int SIZE_OF_UCONVERTER_SHARED_DATA = 228; }
Miracle121/quickdic-dictionary.dictionary
jars/icu4j-52_1/main/classes/charset/src/com/ibm/icu/charset/UConverterSharedData.java
Java
apache-2.0
15,686
/* * Copyright (C) 2012 Glencoe Software, Inc. All rights reserved. * * 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 2 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, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package ome.services.blitz.repo; import java.util.List; import omero.grid.ImportLocation; /** * Server-side implementation of {@link ImportLocation} for also storing the * {@link CheckedPath} instances for each used file. */ public class ManagedImportLocationI extends ImportLocation { private static final long serialVersionUID = 5067747111899744272L; public List<CheckedPath> checkedPaths; public CheckedPath logFile; /** * Return the server-side {@link CheckedPath} instance which can be passed to * a Bio-Formats reader. */ public CheckedPath getTarget() { return checkedPaths.get(0); } /** * Return the server-side {@link CheckedPath} instance which can be used * for writing a log file for a fileset. */ public CheckedPath getLogFile() { return logFile; } }
simleo/openmicroscopy
components/blitz/src/ome/services/blitz/repo/ManagedImportLocationI.java
Java
gpl-2.0
1,647
/** * 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.hdfs; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.DataOutputStream; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.server.namenode.NameNodeAdapter; import org.junit.Test; public class TestDFSRename { static int countLease(MiniDFSCluster cluster) { return NameNodeAdapter.getLeaseManager(cluster.getNamesystem()).countLease(); } final Path dir = new Path("/test/rename/"); void list(FileSystem fs, String name) throws IOException { FileSystem.LOG.info("\n\n" + name); for(FileStatus s : fs.listStatus(dir)) { FileSystem.LOG.info("" + s.getPath()); } } static void createFile(FileSystem fs, Path f) throws IOException { DataOutputStream a_out = fs.create(f); a_out.writeBytes("something"); a_out.close(); } @Test public void testRename() throws Exception { Configuration conf = new HdfsConfiguration(); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build(); try { FileSystem fs = cluster.getFileSystem(); assertTrue(fs.mkdirs(dir)); { //test lease Path a = new Path(dir, "a"); Path aa = new Path(dir, "aa"); Path b = new Path(dir, "b"); createFile(fs, a); //should not have any lease assertEquals(0, countLease(cluster)); DataOutputStream aa_out = fs.create(aa); aa_out.writeBytes("something"); //should have 1 lease assertEquals(1, countLease(cluster)); list(fs, "rename0"); fs.rename(a, b); list(fs, "rename1"); aa_out.writeBytes(" more"); aa_out.close(); list(fs, "rename2"); //should not have any lease assertEquals(0, countLease(cluster)); } { // test non-existent destination Path dstPath = new Path("/c/d"); assertFalse(fs.exists(dstPath)); assertFalse(fs.rename(dir, dstPath)); } { // dst cannot be a file or directory under src // test rename /a/b/foo to /a/b/c Path src = new Path("/a/b"); Path dst = new Path("/a/b/c"); createFile(fs, new Path(src, "foo")); // dst cannot be a file under src assertFalse(fs.rename(src, dst)); // dst cannot be a directory under src assertFalse(fs.rename(src.getParent(), dst.getParent())); } { // dst can start with src, if it is not a directory or file under src // test rename /test /testfile Path src = new Path("/testPrefix"); Path dst = new Path("/testPrefixfile"); createFile(fs, src); assertTrue(fs.rename(src, dst)); } { // dst should not be same as src test rename /a/b/c to /a/b/c Path src = new Path("/a/b/c"); createFile(fs, src); assertTrue(fs.rename(src, src)); assertFalse(fs.rename(new Path("/a/b"), new Path("/a/b/"))); assertTrue(fs.rename(src, new Path("/a/b/c/"))); } fs.delete(dir, true); } finally { if (cluster != null) {cluster.shutdown();} } } }
tseen/Federated-HDFS
tseenliu/FedHDFS-hadoop-src/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSRename.java
Java
apache-2.0
4,202
/** * Copyright 2007-2016, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.kaazing.gateway.service.amqp.amqp091.codec; import static org.kaazing.gateway.service.amqp.amqp091.message.AmqpConnectionMessage.AMQP_AUTHENTICATION_MECHANISM; import static org.kaazing.gateway.service.amqp.amqp091.message.AmqpProtocolHeaderMessage.PROTOCOL_0_9_1_DEFAULT_HEADER; import java.nio.ByteBuffer; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolCodecException; import org.apache.mina.filter.codec.ProtocolDecoderException; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.kaazing.gateway.service.amqp.amqp091.AmqpFrame; import org.kaazing.gateway.service.amqp.amqp091.AmqpProperty; import org.kaazing.gateway.service.amqp.amqp091.AmqpTable; import org.kaazing.gateway.service.amqp.amqp091.AmqpTable.AmqpTableEntry; import org.kaazing.gateway.service.amqp.amqp091.AmqpType; import org.kaazing.gateway.service.amqp.amqp091.message.AmqpClassMessage; import org.kaazing.gateway.service.amqp.amqp091.message.AmqpClassMessage.ClassKind; import org.kaazing.gateway.service.amqp.amqp091.message.AmqpCloseMessage; import org.kaazing.gateway.service.amqp.amqp091.message.AmqpCloseOkMessage; import org.kaazing.gateway.service.amqp.amqp091.message.AmqpConnectionMessage; import org.kaazing.gateway.service.amqp.amqp091.message.AmqpConnectionMessage.ConnectionMethodKind; import org.kaazing.gateway.service.amqp.amqp091.message.AmqpOpenMessage; import org.kaazing.gateway.service.amqp.amqp091.message.AmqpOpenOkMessage; import org.kaazing.gateway.service.amqp.amqp091.message.AmqpProtocolHeaderMessage; import org.kaazing.gateway.service.amqp.amqp091.message.AmqpSecureMessage; import org.kaazing.gateway.service.amqp.amqp091.message.AmqpSecureOkMessage; import org.kaazing.gateway.service.amqp.amqp091.message.AmqpStartMessage; import org.kaazing.gateway.service.amqp.amqp091.message.AmqpStartOkMessage; import org.kaazing.gateway.service.amqp.amqp091.message.AmqpTuneMessage; import org.kaazing.gateway.service.amqp.amqp091.message.AmqpTuneOkMessage; import org.kaazing.mina.core.buffer.IoBufferAllocatorEx; import org.kaazing.mina.core.buffer.IoBufferEx; import org.kaazing.mina.filter.codec.CumulativeProtocolDecoderEx; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AmqpMessageDecoder extends CumulativeProtocolDecoderEx { private static final String CLASS_NAME = AmqpMessageDecoder.class.getName(); private static final String SERVICE_AMQP_PROXY_LOGGER = "service.amqp.proxy"; private static final Map<Character, AmqpType> typeIdentifierMap = new HashMap<>(); private static final Map<AmqpType, String> typeMap = new HashMap<>(); enum DecoderState { READ_PROTOCOL_HEADER, READ_FRAME, AFTER_CONNECTION } static { typeIdentifierMap.put('F', AmqpType.FIELDTABLE); typeIdentifierMap.put('I', AmqpType.INT); typeIdentifierMap.put('L', AmqpType.LONGLONG); typeIdentifierMap.put('S', AmqpType.LONGSTRING); typeIdentifierMap.put('s', AmqpType.SHORTSTRING); typeIdentifierMap.put('T', AmqpType.TIMESTAMP); typeIdentifierMap.put('U', AmqpType.SHORT); typeIdentifierMap.put('V', AmqpType.VOID); typeMap.put(AmqpType.FIELDTABLE, "F"); typeMap.put(AmqpType.INT, "I"); typeMap.put(AmqpType.LONGLONG, "L"); typeMap.put(AmqpType.LONGSTRING, "S"); typeMap.put(AmqpType.SHORTSTRING, "s"); typeMap.put(AmqpType.TIMESTAMP, "T"); typeMap.put(AmqpType.SHORT, "U"); typeMap.put(AmqpType.VOID, "V"); } private DecoderState currentState; public AmqpMessageDecoder(IoBufferAllocatorEx<?> allocator, boolean client) { this(allocator, client, null); } public AmqpMessageDecoder(IoBufferAllocatorEx<?> allocator, boolean client, DecoderState initial) { this(allocator, (initial != null) ? initial : client ? DecoderState.READ_FRAME : DecoderState.READ_PROTOCOL_HEADER); } AmqpMessageDecoder(IoBufferAllocatorEx<?> allocator, DecoderState initialState) { super(allocator); this.currentState = initialState; Logger logger = LoggerFactory.getLogger(SERVICE_AMQP_PROXY_LOGGER); if (logger.isDebugEnabled()) { String s = ".AmqpMessageDecoder(): Initial State = " + initialState; logger.debug(CLASS_NAME + s); } } @Override protected boolean doDecode(IoSession session, IoBufferEx in, ProtocolDecoderOutput out) throws Exception { Logger logger = LoggerFactory.getLogger(SERVICE_AMQP_PROXY_LOGGER); if (logger.isDebugEnabled()) { String s = ".doDecode(): Current State - " + currentState; logger.debug(CLASS_NAME + s); } switch (currentState) { case READ_PROTOCOL_HEADER: return decodeProtocolHeader(session, in, out); case READ_FRAME: return decodeFrame(session, in, out); case AFTER_CONNECTION: out.write(in.duplicate()); in.skip(in.remaining()); session.getFilterChain().remove(AmqpCodecFilter.NAME); return true; default: return false; } } private boolean decodeProtocolHeader(IoSession session, IoBufferEx in, ProtocolDecoderOutput out) throws Exception { Logger logger = LoggerFactory.getLogger(SERVICE_AMQP_PROXY_LOGGER); if (in.remaining() < 8) { if (logger.isDebugEnabled()) { String s = ".decodeProtocolHeader(): Not enough bytes to decode " + "AMQP 0.9.1 protocol header - " + getHexDump(in); logger.debug(CLASS_NAME + s); } return false; } if (in.remaining() > 8) { // ### TODO: Perhaps, we should just consume 8bytes and not worry // about throwing an exception. For time being, let's be // conservative. if (logger.isDebugEnabled()) { String s = ".decodeProtocolHeader(): Too many bytes to decode " + "AMQP 0.9.1 protocol header - " + getHexDump(in); logger.debug(CLASS_NAME + s); } throw new ProtocolCodecException("Invalid AMQP 0.9.1 Protocol Header"); } byte[] bytes = new byte[in.remaining()]; for (int i = 0; i < bytes.length; i++) { bytes[i] = in.get(); } if (!Arrays.equals(PROTOCOL_0_9_1_DEFAULT_HEADER, bytes)) { String s = "Invalid AMQP 0.9.1 Protocol Header: " + getHexDump(bytes); throw new ProtocolCodecException(s); } AmqpProtocolHeaderMessage message = new AmqpProtocolHeaderMessage(); message.setProtocolHeader(PROTOCOL_0_9_1_DEFAULT_HEADER); out.write(message); if (logger.isDebugEnabled()) { String s = ".decodeProtocolHeader(): AMQP 0.9.1 Protocol Header " + "successfully decoded"; logger.debug(CLASS_NAME + s); } currentState = DecoderState.READ_FRAME; if (logger.isDebugEnabled()) { String s = ".decodeFrame(): Transitioning to READ_FRAME state"; logger.debug(CLASS_NAME + s); } return true; } private boolean decodeFrame(IoSession session, IoBufferEx in, ProtocolDecoderOutput out) throws Exception { Logger logger = LoggerFactory.getLogger(SERVICE_AMQP_PROXY_LOGGER); if (in.remaining() < 7) { if (logger.isDebugEnabled()) { String s = ".decodeFrame(): Cannot decode a frame without the " + "first seven bytes"; logger.debug(CLASS_NAME + s); } return false; } /* // This can be used to log the raw bytes for the entire frame for // all the messages. But, we don't want the logs to contain even raw // bytes for the password. That's why we invoke the logger in individual // decode methods appropriately. For START_OK and and SECURE_OK, we will // make sure that error.log does not contain even the raw password // bytes. This code can be used for debugging purposes. if (logger.isDebugEnabled()) { String s = ".decodeFrame(): Raw bytes - " + getHexDump(in); logger.debug(CLASS_NAME + s); } */ // Mark the buffer's position. This way, we can easily reset. in.mark(); // Read the first seven bytes to get the size of the payload. byte frameType = (byte)in.getUnsigned(); AmqpFrame frameKind = AmqpFrame.get(frameType); short channelId = (short) getUnsignedShort(in); long payloadSize = getUnsignedInt(in); // 8 bytes are used for constructing the frame around the payload -- // frame-type (1) + // channel-id (2) + // payload-size (4) + len([payload]) + end-of-frame (1) if (in.remaining() < payloadSize + 1) { // The frame is not complete yet. Reset the buffer to the previously // marked position and return false so that we called again when // more data arrives. in.reset(); if (logger.isDebugEnabled()) { String s = ".decodeFrame(): Fragmentation may have resulted " + "in an incomplete frame - " + getHexDump(in); logger.debug(CLASS_NAME + s); } return false; } AmqpClassMessage message; short classIndex = (short) getUnsignedShort(in); ClassKind classKind = ClassKind.get(classIndex); switch (classKind) { case CONNECTION: assert(frameKind == AmqpFrame.METHOD); message = decodeConnection(session, in); message.setChannelId(channelId); break; default: String s = "Unhandled class kind - " + classKind; throw new ProtocolDecoderException(s); } byte frameEnd = (byte) in.getUnsigned(); if ((frameEnd & 0xFF) != AmqpClassMessage.FRAME_END) { String s = Integer.toHexString(frameEnd & 0xFF); throw new ProtocolCodecException("Invalid end of AMQP Frame - " + s); } out.write(message); if (logger.isDebugEnabled()) { logger.debug(CLASS_NAME + ".decodeFrame(): Message - " + message); } switch (classKind) { case CONNECTION: AmqpConnectionMessage connection = (AmqpConnectionMessage) message; switch (connection.getMethodKind()) { case OPEN: case OPEN_OK: currentState = DecoderState.AFTER_CONNECTION; if (logger.isDebugEnabled()) { String s = ".decodeFrame(): Transitioning to AFTER_CONNECTION state"; logger.debug(CLASS_NAME + s); } break; } break; } return true; } // ------------------ Private Methods ----------------------------------- // Returns an array of length 2. The 0th element contains the userid and // the 1st element is the password. private static String[] decodeAuthAmqPlain(String response) { Logger logger = LoggerFactory.getLogger(SERVICE_AMQP_PROXY_LOGGER); String[] credentials = null; if ((response != null) && (response.trim().length() > 0)) { ByteBuffer buffer = ByteBuffer.wrap(response.getBytes()); @SuppressWarnings("unused") String loginKey = getShortString(buffer); @SuppressWarnings("unused") AmqpType ltype = getType(buffer); String username = getLongString(buffer); @SuppressWarnings("unused") String passwordKey = getShortString(buffer); @SuppressWarnings("unused") AmqpType ptype = getType(buffer); String password = getLongString(buffer); if (logger.isDebugEnabled()) { String s = ".decodeAuthAmqPlain(): Username = " + username; logger.debug(CLASS_NAME + s); } credentials = new String[] { username, password }; } return credentials; } private static String[] decodeAuthPlain(String response) { String[] credentials = null; if ((response != null) && (response.trim().length() > 0)) { // PLAIN mechanism response - NUL + username + NUL + password int firstIndexOfNULChar = response.indexOf('\0'); int secondIndexOfNULChar = response.indexOf('\0', firstIndexOfNULChar + 1); String username = response.substring(firstIndexOfNULChar + 1, secondIndexOfNULChar); String password = response.substring(secondIndexOfNULChar + 1); credentials = new String[] {username, password}; } return credentials; } private static AmqpConnectionMessage decodeConnection(IoSession session, IoBufferEx in) throws ProtocolDecoderException { AmqpConnectionMessage message; short methodId = (short) getUnsignedShort(in); ConnectionMethodKind methodKind = ConnectionMethodKind.get(methodId); switch (methodKind) { case CLOSE: message = decodeClose(in); break; case CLOSE_OK: message = decodeCloseOk(in); break; case OPEN: message = decodeOpen(in); break; case OPEN_OK: message = decodeOpenOk(in); break; case SECURE: message = decodeSecure(in); break; case SECURE_OK: message = decodeSecureOk(session, in); break; case START: message = decodeStart(in); break; case START_OK: message = decodeStartOk(session, in); break; case TUNE: message = decodeTune(in); break; case TUNE_OK: message = decodeTuneOk(in); break; default: String s = "Invalid method index: " + methodId; throw new ProtocolDecoderException(s); } return message; } private static AmqpCloseMessage decodeClose(IoBufferEx in) { Logger logger = LoggerFactory.getLogger(SERVICE_AMQP_PROXY_LOGGER); AmqpCloseMessage message = new AmqpCloseMessage(); if (logger.isDebugEnabled()) { String s = ".decodeClose(): Raw bytes - " + getHexDump(in); logger.debug(CLASS_NAME + s); } // Decode the parameters. int replyCode = getUnsignedShort(in); String replyText = getShortString(in); int classId = getUnsignedShort(in); int methodId = getUnsignedShort(in); message.setReplyCode(replyCode); message.setReplyText(replyText); ClassKind classKind = (classId == 0) ? null : ClassKind.get((short)classId); message.setReasonClassKind(classKind); message.setReasonMethodId(methodId); if (logger.isDebugEnabled()) { logger.debug(CLASS_NAME + ".decodeClose(): " + message); } return message; } private static AmqpCloseOkMessage decodeCloseOk(IoBufferEx in) { return new AmqpCloseOkMessage(); } private static AmqpOpenMessage decodeOpen(IoBufferEx in) { Logger logger = LoggerFactory.getLogger(SERVICE_AMQP_PROXY_LOGGER); AmqpOpenMessage message = new AmqpOpenMessage(); if (logger.isDebugEnabled()) { String s = ".decodeOpen(): Raw bytes - " + getHexDump(in); logger.debug(CLASS_NAME + s); } // Decode the parameters. String virtualHost = getShortString(in); String reserved1 = getShortString(in); int reserved2 = getBit(in); message.setVirtualHost(virtualHost); message.setReserved1(reserved1); message.setReserved2((reserved2 > 0) ? Boolean.TRUE : Boolean.FALSE); if (logger.isDebugEnabled()) { logger.debug(CLASS_NAME + ".decodeOpen(): " + message); } return message; } private static AmqpOpenOkMessage decodeOpenOk(IoBufferEx in) { Logger logger = LoggerFactory.getLogger(SERVICE_AMQP_PROXY_LOGGER); if (logger.isDebugEnabled()) { String s = ".decodeOpenOk(): Raw bytes - " + getHexDump(in); logger.debug(CLASS_NAME + s); } AmqpOpenOkMessage message = new AmqpOpenOkMessage(); // Decode the parameter(s). String reserved1 = getShortString(in); message.setReserved1(reserved1); if (logger.isDebugEnabled()) { logger.debug(CLASS_NAME + ".decodeOpenOk(): " + message); } return message; } private static AmqpSecureMessage decodeSecure(IoBufferEx in) { Logger logger = LoggerFactory.getLogger(SERVICE_AMQP_PROXY_LOGGER); if (logger.isDebugEnabled()) { String s = ".decodeSecure(): Raw bytes - " + getHexDump(in); logger.debug(CLASS_NAME + s); } AmqpSecureMessage message = new AmqpSecureMessage(); // Decode the parameter(s). String challenge = getLongString(in); message.setChallenge(challenge); if (logger.isDebugEnabled()) { logger.debug(CLASS_NAME + ".decodeSecure(): " + message); } return message; } private static AmqpSecureOkMessage decodeSecureOk(IoSession session, IoBufferEx in) { // Do not log the raw bytes as it can contain the password. AmqpSecureOkMessage message = new AmqpSecureOkMessage(); // Decode the parameter(s). String response = getLongString(in); // The authentication mechanism corresponding to this security mechanism response is injected as a // session attribute while decoding start-ok Object mechanismObj = session.getAttribute(AMQP_AUTHENTICATION_MECHANISM); if (mechanismObj == null) { throw new IllegalStateException("Missing session attribute - " + AMQP_AUTHENTICATION_MECHANISM); } String authMechanism = mechanismObj.toString(); String[] credentials = null; if ("AMQPLAIN".equals(authMechanism)) { credentials = decodeAuthAmqPlain(response); } else if ("PLAIN".equalsIgnoreCase(authMechanism)) { credentials = decodeAuthPlain(response); } if (credentials != null) { String username = credentials[0]; char[] password = credentials[1].toCharArray(); message.setUsername(username); message.setPassword(password); Logger logger = LoggerFactory.getLogger(SERVICE_AMQP_PROXY_LOGGER); if (logger.isDebugEnabled()) { logger.debug(CLASS_NAME + ".decodeSecureOk(): " + message); } } return message; } private static AmqpStartMessage decodeStart(IoBufferEx in) throws ProtocolDecoderException { Logger logger = LoggerFactory.getLogger(SERVICE_AMQP_PROXY_LOGGER); if (logger.isDebugEnabled()) { String s = ".decodeStart(): Raw bytes - " + getHexDump(in); logger.debug(CLASS_NAME + s); } AmqpStartMessage message = new AmqpStartMessage(); // Decode the parameters. short versionMajor = in.getUnsigned(); short versionMinor = in.getUnsigned(); AmqpTable serverProperties = getTable(in); String mechanisms = getLongString(in); String locales = getLongString(in); message.setVersionMajor((byte)versionMajor); message.setVersionMinor((byte)versionMinor); message.setServerProperties(serverProperties); message.setSecurityMechanisms(mechanisms); message.setLocales(locales); if (logger.isDebugEnabled()) { logger.debug(CLASS_NAME + ".decodeStart(): " + message); } return message; } private static AmqpStartOkMessage decodeStartOk(IoSession session, IoBufferEx in) throws ProtocolDecoderException { // Do not log raw bytes as it can contain the password. AmqpStartOkMessage message = new AmqpStartOkMessage(); // Decode the parameters. AmqpTable clientProperties = getTable(in); String mechanism = getShortString(in); String response = getLongString(in); String locale = getShortString(in); message.setClientProperties(clientProperties); message.setSecurityMechanism(mechanism); String[] credentials; if ("AMQPLAIN".equals(mechanism)) { credentials = decodeAuthAmqPlain(response); } else if ("PLAIN".equalsIgnoreCase(mechanism)) { credentials = decodeAuthPlain(response); } else { throw new IllegalStateException("Unsupported SASL authentication mechanism: " + mechanism); } // Inject the SASL authentication mechanism as a session attribute // The mechanism selected by client is needed later for secure-ok session.setAttribute(AMQP_AUTHENTICATION_MECHANISM, mechanism); String username; if (credentials != null) { username = credentials[0]; char[] password = credentials[1].toCharArray(); message.setUsername(username); message.setPassword(password); } message.setLocale(locale); Logger logger = LoggerFactory.getLogger(SERVICE_AMQP_PROXY_LOGGER); if (logger.isDebugEnabled()) { logger.debug(CLASS_NAME + ".decodeStartOk(): " + message); } return message; } private static AmqpTuneMessage decodeTune(IoBufferEx in) { Logger logger = LoggerFactory.getLogger(SERVICE_AMQP_PROXY_LOGGER); if (logger.isDebugEnabled()) { String s = ".decodeTune(): Raw bytes - " + getHexDump(in); logger.debug(CLASS_NAME + s); } AmqpTuneMessage message = new AmqpTuneMessage(); // Decode the parameters. int maxChannels = getUnsignedShort(in); int maxFrameSize = in.getInt(); int heartbeatDelay = getUnsignedShort(in); message.setMaxChannels(maxChannels); message.setMaxFrameSize(maxFrameSize); message.setHeartbeatDelay(heartbeatDelay); if (logger.isDebugEnabled()) { logger.debug(CLASS_NAME + ".decodeTune(): " + message); } return message; } private static AmqpTuneOkMessage decodeTuneOk(IoBufferEx in) { Logger logger = LoggerFactory.getLogger(SERVICE_AMQP_PROXY_LOGGER); if (logger.isDebugEnabled()) { String s = ".decodeTuneOk(): Raw bytes - " + getHexDump(in); logger.debug(CLASS_NAME + s); } AmqpTuneOkMessage message = new AmqpTuneOkMessage(); // Decode the parameters. int maxChannels = getUnsignedShort(in); int maxFrameSize = in.getInt(); int heartbeatDelay = getUnsignedShort(in); message.setMaxChannels(maxChannels); message.setMaxFrameSize(maxFrameSize); message.setHeartbeatDelay(heartbeatDelay); if (logger.isDebugEnabled()) { logger.debug(CLASS_NAME + ".decodeTuneOk(): " + message); } return message; } private static int getBit(IoBufferEx buffer) { return buffer.getUnsigned(); } private static long getMilliseconds(IoBufferEx buffer) { return buffer.getLong(); } public static int getUnsignedShort(IoBufferEx buffer) { int val = (buffer.getShort() & 0xffff); return val; } private static long getUnsignedInt(IoBufferEx buffer) { long val = buffer.getInt() & 0xffffffffL; return val; } private static long getUnsignedInt(ByteBuffer buffer) { long val = buffer.getInt() & 0xffffffffL; return val; } // Gets an AMQP unsigned long. private static long getUnsignedLong(IoBufferEx buffer) { // For unsigned longs (8 byte integers) // throw away the first word, then read the next // word as an unsigned int buffer.getInt(); return getUnsignedInt(buffer); } private static Object getFieldValue(IoBufferEx buffer) { int typeCode = buffer.getUnsigned(); switch(typeCode) { case 116: // 't' boolean b = buffer.getUnsigned() != 0; return b; default: throw new IllegalStateException("Decoding Error in AmqpBuffer: cannot decode field value"); } } private static Map<String,Object> getFieldTable(IoBufferEx buffer) { Map<String,Object> t = new HashMap<>(); int len = (int)getUnsignedInt(buffer); int initial = buffer.position(); while (len > (buffer.position()-initial)) { String key = getShortString(buffer); Object value = getFieldValue(buffer); t.put(key,value); } return t; } private static AmqpTable getTable(IoBufferEx buffer) throws ProtocolDecoderException { long len = getUnsignedInt(buffer); long end = buffer.position() + len; ArrayList<AmqpTableEntry> entries = new ArrayList<>(); while (buffer.position() < end) { String key = getShortString(buffer); AmqpType type = getType(buffer); // String typeCodec = getMappedType(ti); Object value = getObjectOfType(buffer, type); AmqpTable.AmqpTableEntry entry = new AmqpTable.AmqpTableEntry(key, value, type); entries.add(entry); } if (entries.isEmpty()) { return null; } AmqpTable table = new AmqpTable(); table.setEntries(entries); return table; } // Returns an AMQP long-string which is a string prefixed by a unsigned // 32-bit integer representing the length of the string. private static String getLongString(IoBufferEx buffer) { long len = getUnsignedInt(buffer); StringBuilder builder = new StringBuilder(); for (int i = 0; i < len; i++) { builder.append((char)(buffer.getUnsigned())); } String s = builder.toString(); return s; } // Returns an AMQP long-string which is a string prefixed by a unsigned // 32-bit integer representing the length of the string. private static String getLongString(ByteBuffer buffer) { long len = getUnsignedInt(buffer); StringBuilder builder = new StringBuilder(); for (int i = 0; i < len; i++) { builder.append((char)(buffer.get() & 0xff)); } String s = builder.toString(); return s; } // Returns an AMQP short-string which is a string prefixed by a unsigned // 8-bit integer representing the length of the string. private static String getShortString(IoBufferEx buffer) { int len = buffer.getUnsigned(); StringBuilder builder = new StringBuilder(); for (int i = 0; i < len; i++) { builder.append((char)(buffer.getUnsigned())); } String s = builder.toString(); return s; } // Returns an AMQP short-string which is a string prefixed by a unsigned // 8-bit integer representing the length of the string. private static String getShortString(ByteBuffer buffer) { int len = buffer.get() & 0xff; StringBuilder builder = new StringBuilder(); for (int i = 0; i < len; i++) { builder.append((char)(buffer.get() & 0xff)); } String s = builder.toString(); return s; } private static AmqpType getType(IoBufferEx buffer) { char c = (char)(buffer.getUnsigned()); return typeIdentifierMap.get(c); } private static AmqpType getType(ByteBuffer buffer) { char c = (char)(buffer.get() & 0xff); return typeIdentifierMap.get(c); } private static String getHexDump(IoBufferEx buffer) { if (buffer.position() == buffer.limit()) { return "empty"; } StringBuilder hexDump = new StringBuilder(); for (int i = buffer.position() + buffer.arrayOffset(); i < buffer.limit(); i++) { hexDump.append(Integer.toHexString(buffer.get(i)&0xFF)).append(' '); } return hexDump.toString(); } private static String getHexDump(byte[] bytes) { StringBuilder hexDump = new StringBuilder(); for (byte aByte : bytes) { hexDump.append(Integer.toHexString(aByte & 0xFF)).append(" "); } return hexDump.toString(); } /* private FrameHeader getFrameHeader() { int frameType = this.getUnsigned(); int channel = this.getUnsignedShort(); long size = this.getUnsignedInt(); FrameHeader header = new FrameHeader(); header.frameType = frameType; header.size = size; header.channel = channel; return header; } */ private static Object getObjectOfType(IoBufferEx buffer, AmqpType type) throws ProtocolDecoderException { Object value; switch (type) { case BIT: value = getBit(buffer); break; case SHORTSTRING: value = getShortString(buffer); break; case LONGSTRING: value = getLongString(buffer); break; case FIELDTABLE: value = getFieldTable(buffer); break; case TABLE: value = getTable(buffer); break; case INT: value = buffer.getInt(); break; case UNSIGNEDINT: value = getUnsignedInt(buffer); break; case UNSIGNEDSHORT: value = getUnsignedShort(buffer); break; case UNSIGNED: value = buffer.getUnsigned(); break; case SHORT: value = getUnsignedShort(buffer); break; case LONG: value = getUnsignedInt(buffer); break; case OCTET: value = buffer.getUnsigned(); break; case LONGLONG: value = getUnsignedLong(buffer); break; case TIMESTAMP: long millis = getMilliseconds(buffer); value = new Timestamp(millis); break; case VOID: value = null; break; default: String s = "Invalid type: '" + type; throw new ProtocolDecoderException(s); } return value; } private static final AmqpProperty[] PROPERTY_VALUES = AmqpProperty.values(); @SuppressWarnings("unused") private static Map<AmqpProperty, Object> getContentProperties(IoBufferEx buffer) throws ProtocolCodecException { int packedPropertyFlags = getUnsignedShort(buffer); Map<AmqpProperty, Object> contentProperties = new TreeMap<>(); for (int offset = 0, bitmask = packedPropertyFlags; bitmask != 0; offset++, bitmask >>= 1) { if ((bitmask & 0x01) != 0x00) { AmqpProperty property = PROPERTY_VALUES[offset]; contentProperties.put(property, getObjectOfType(buffer, property.domain().type())); } } return contentProperties; } } /* class FrameHeader { int frameType; long size; int channel; } */
mgherghe/gateway
service/amqp/src/main/java/org/kaazing/gateway/service/amqp/amqp091/codec/AmqpMessageDecoder.java
Java
apache-2.0
34,490
/* Copyright (c) 2001-2009, The HSQL Development Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the HSQL Development Group nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG, * 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.hsqldb_voltpatches; import org.hsqldb_voltpatches.lib.OrderedHashSet; /** * Implementation of SQL TRIGGER objects.<p> * * @author Fred Toussi (fredt@users dot sourceforge.net) * @version 1.9.0 * @since 1.9.0 */ public class TriggerDefSQL extends TriggerDef { OrderedHashSet references; public TriggerDefSQL(HsqlNameManager.HsqlName name, String when, String operation, boolean forEachRow, Table table, Table[] transitions, RangeVariable[] rangeVars, Expression condition, String conditionSQL, int[] updateColumns, StatementDMQL[] compiledStatements, String procedureSQL, OrderedHashSet references) { this.name = name; this.actionTimingString = when; this.eventTimingString = operation; this.forEachRow = forEachRow; this.table = table; this.transitions = transitions; this.rangeVars = rangeVars; this.condition = condition == null ? Expression.EXPR_TRUE : condition; this.updateColumns = updateColumns; this.statements = compiledStatements; this.conditionSQL = conditionSQL; this.procedureSQL = procedureSQL; this.references = references; hasTransitionRanges = transitions[OLD_ROW] != null || transitions[NEW_ROW] != null; hasTransitionTables = transitions[OLD_TABLE] != null || transitions[NEW_TABLE] != null; setUpIndexesAndTypes(); // } public OrderedHashSet getReferences() { return references; } public OrderedHashSet getComponents() { return null; } public void compile(Session session) {} public String getClassName() { return null; } public boolean hasOldTable() { return transitions[OLD_TABLE] != null; } public boolean hasNewTable() { return transitions[NEW_TABLE] != null; } synchronized void pushPair(Session session, Object[] oldData, Object[] newData) { if (transitions[OLD_ROW] != null) { rangeVars[OLD_ROW].getIterator(session).currentData = oldData; } if (transitions[NEW_ROW] != null) { rangeVars[NEW_ROW].getIterator(session).currentData = newData; } if (!condition.testCondition(session)) { return; } for (int i = 0; i < statements.length; i++) { statements[i].execute(session); } } public String getSQL() { boolean isBlock = statements.length > 1; StringBuffer sb = new StringBuffer(256); sb.append(Tokens.T_CREATE).append(' '); sb.append(Tokens.T_TRIGGER).append(' '); sb.append(name.statementName).append(' '); sb.append(actionTimingString).append(' '); sb.append(eventTimingString).append(' '); sb.append(Tokens.T_ON).append(' '); sb.append(table.getName().statementName).append(' '); if (hasTransitionRanges || hasTransitionTables) { sb.append(Tokens.T_REFERENCING).append(' '); String separator = ""; if (transitions[OLD_ROW] != null) { sb.append(Tokens.T_OLD).append(' ').append(Tokens.T_ROW); sb.append(' ').append(Tokens.T_AS).append(' '); sb.append(transitions[OLD_ROW].getName().statementName); separator = Tokens.T_COMMA; } if (transitions[NEW_ROW] != null) { sb.append(separator); sb.append(Tokens.T_NEW).append(' ').append(Tokens.T_ROW); sb.append(' ').append(Tokens.T_AS).append(' '); sb.append(transitions[NEW_ROW].getName().statementName); separator = Tokens.T_COMMA; } if (transitions[OLD_TABLE] != null) { sb.append(separator); sb.append(Tokens.T_OLD).append(' ').append(Tokens.T_TABLE); sb.append(' ').append(Tokens.T_AS).append(' '); sb.append(transitions[OLD_TABLE].getName().statementName); separator = Tokens.T_COMMA; } if (transitions[NEW_TABLE] != null) { sb.append(separator); sb.append(Tokens.T_OLD).append(' ').append(Tokens.T_TABLE); sb.append(' ').append(Tokens.T_AS).append(' '); sb.append(transitions[NEW_TABLE].getName().statementName); } sb.append(' '); } if (forEachRow) { sb.append(Tokens.T_FOR).append(' '); sb.append(Tokens.T_EACH).append(' '); sb.append(Tokens.T_ROW).append(' '); } if (condition != Expression.EXPR_TRUE) { sb.append(Tokens.T_WHEN).append(' '); sb.append(Tokens.T_OPENBRACKET).append(conditionSQL); sb.append(Tokens.T_CLOSEBRACKET).append(' '); } if (isBlock) { sb.append(Tokens.T_BEGIN).append(' ').append(Tokens.T_ATOMIC); sb.append(' '); } sb.append(procedureSQL).append(' '); if (isBlock) { sb.append(Tokens.T_END); } return sb.toString(); } }
kumarrus/voltdb
src/hsqldb19b3/org/hsqldb_voltpatches/TriggerDefSQL.java
Java
agpl-3.0
7,132
abstract class Test extends Sup<caret>er { { System.out.println(CONST); System.out.println(Super.CONST); } } abstract class Test1 extends Super { { System.out.println(CONST); System.out.println(Super.CONST); } }
siosio/intellij-community
java/java-tests/testData/refactoring/inlineSuperClass/oneAndKeepReferencesInAnotherInheritor/before/Test.java
Java
apache-2.0
235
/* * 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. */ /** * ENTITIES.java * * This file was auto-generated from WSDL * by the Apache Axis2 version: SNAPSHOT Built on : Dec 21, 2007 (04:03:30 LKT) */ package org.apache.axis2.databinding.types.xsd; import javax.xml.stream.XMLStreamWriter; /** * ENTITIES bean class */ public class ENTITIES implements org.apache.axis2.databinding.ADBBean{ /* This type was generated from the piece of schema that had name = ENTITIES Namespace URI = http://www.w3.org/2001/XMLSchema Namespace Prefix = ns1 */ private static java.lang.String generatePrefix(java.lang.String namespace) { if(namespace.equals("http://www.w3.org/2001/XMLSchema")){ return "xsd"; } return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } /** * field for ENTITIES */ protected org.apache.axis2.databinding.types.Entities localENTITIES ; /** * Auto generated getter method * @return org.apache.axis2.databinding.types.Entities */ public org.apache.axis2.databinding.types.Entities getENTITIES(){ return localENTITIES; } /** * Auto generated setter method * @param param ENTITIES */ public void setENTITIES(org.apache.axis2.databinding.types.Entities param){ this.localENTITIES=param; } public java.lang.String toString(){ return localENTITIES.toString(); } /** * isReaderMTOMAware * @return true if the reader supports MTOM */ public static boolean isReaderMTOMAware(javax.xml.stream.XMLStreamReader reader) { boolean isReaderMTOMAware = false; try{ isReaderMTOMAware = java.lang.Boolean.TRUE.equals(reader.getProperty(org.apache.axiom.om.OMConstants.IS_DATA_HANDLERS_AWARE)); }catch(java.lang.IllegalArgumentException e){ isReaderMTOMAware = false; } return isReaderMTOMAware; } /** * * @param parentQName * @param factory * @return org.apache.axiom.om.OMElement */ public org.apache.axiom.om.OMElement getOMElement ( final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{ org.apache.axiom.om.OMDataSource dataSource = new org.apache.axis2.databinding.ADBDataSource(this,parentQName); return factory.createOMElement(dataSource,parentQName); } public void serialize(final javax.xml.namespace.QName parentQName, XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ serialize(parentQName,xmlWriter,false); } public void serialize(final javax.xml.namespace.QName parentQName, XMLStreamWriter xmlWriter, boolean serializeType) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ java.lang.String prefix = null; java.lang.String namespace = null; prefix = parentQName.getPrefix(); namespace = parentQName.getNamespaceURI(); if ((namespace != null) && (namespace.trim().length() > 0)) { java.lang.String writerPrefix = xmlWriter.getPrefix(namespace); if (writerPrefix != null) { xmlWriter.writeStartElement(namespace, parentQName.getLocalPart()); } else { if (prefix == null) { prefix = generatePrefix(namespace); } xmlWriter.writeStartElement(prefix, parentQName.getLocalPart(), namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } } else { xmlWriter.writeStartElement(parentQName.getLocalPart()); } if (serializeType){ java.lang.String namespacePrefix = registerPrefix(xmlWriter,"http://www.w3.org/2001/XMLSchema"); if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){ writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", namespacePrefix+":ENTITIES", xmlWriter); } else { writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", "ENTITIES", xmlWriter); } } if (localENTITIES==null){ // write the nil attribute throw new org.apache.axis2.databinding.ADBException("ENTITIES cannot be null!!"); }else{ xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localENTITIES)); } xmlWriter.writeEndElement(); } /** * Util method to write an attribute with the ns prefix */ private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (xmlWriter.getPrefix(namespace) == null) { xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } xmlWriter.writeAttribute(namespace,attName,attValue); } /** * Util method to write an attribute without the ns prefix */ private void writeAttribute(java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (namespace.equals("")) { xmlWriter.writeAttribute(attName,attValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace,attName,attValue); } } /** * Util method to write an attribute without the ns prefix */ private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName, javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String attributeNamespace = qname.getNamespaceURI(); java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace); if (attributePrefix == null) { attributePrefix = registerPrefix(xmlWriter, attributeNamespace); } java.lang.String attributeValue; if (attributePrefix.trim().length() > 0) { attributeValue = attributePrefix + ":" + qname.getLocalPart(); } else { attributeValue = qname.getLocalPart(); } if (namespace.equals("")) { xmlWriter.writeAttribute(attName, attributeValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace, attName, attributeValue); } } /** * method to handle Qnames */ private void writeQName(javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String namespaceURI = qname.getNamespaceURI(); if (namespaceURI != null) { java.lang.String prefix = xmlWriter.getPrefix(namespaceURI); if (prefix == null) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } else { // i.e this is the default namespace xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } else { xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } private void writeQNames(javax.xml.namespace.QName[] qnames, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (qnames != null) { // we have to store this data until last moment since it is not possible to write any // namespace data after writing the charactor data java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer(); java.lang.String namespaceURI = null; java.lang.String prefix = null; for (int i = 0; i < qnames.length; i++) { if (i > 0) { stringToWrite.append(" "); } namespaceURI = qnames[i].getNamespaceURI(); if (namespaceURI != null) { prefix = xmlWriter.getPrefix(namespaceURI); if ((prefix == null) || (prefix.length() == 0)) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } xmlWriter.writeCharacters(stringToWrite.toString()); } } /** * Register a namespace prefix */ private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException { java.lang.String prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = generatePrefix(namespace); while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null) { prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } return prefix; } /** * databinding method to get an XML representation of this object * */ public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName) throws org.apache.axis2.databinding.ADBException{ java.util.ArrayList elementList = new java.util.ArrayList(); java.util.ArrayList attribList = new java.util.ArrayList(); elementList.add(org.apache.axis2.databinding.utils.reader.ADBXMLStreamReader.ELEMENT_TEXT); if (localENTITIES != null){ elementList.add(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localENTITIES)); } else { throw new org.apache.axis2.databinding.ADBException("ENTITIES cannot be null!!"); } return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray()); } /** * Factory class that keeps the parse method */ public static class Factory{ public static ENTITIES fromString(java.lang.String value, java.lang.String namespaceURI){ ENTITIES returnValue = new ENTITIES(); returnValue.setENTITIES( org.apache.axis2.databinding.utils.ConverterUtil.convertToENTITIES(value)); return returnValue; } public static ENTITIES fromString(javax.xml.stream.XMLStreamReader xmlStreamReader, java.lang.String content) { if (content.indexOf(":") > -1){ java.lang.String prefix = content.substring(0,content.indexOf(":")); java.lang.String namespaceUri = xmlStreamReader.getNamespaceContext().getNamespaceURI(prefix); return ENTITIES.Factory.fromString(content,namespaceUri); } else { return ENTITIES.Factory.fromString(content,""); } } /** * static method to create the object * Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable * If this object is not an element, it is a complex type and the reader is at the event just after the outer start element * Postcondition: If this object is an element, the reader is positioned at its end element * If this object is a complex type, the reader is positioned at the end element of its outer element */ public static ENTITIES parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{ ENTITIES object = new ENTITIES(); int event; java.lang.String nillableValue = null; java.lang.String prefix =""; java.lang.String namespaceuri =""; try { while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type")!=null){ java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type"); if (fullTypeName!=null){ java.lang.String nsPrefix = null; if (fullTypeName.indexOf(":") > -1){ nsPrefix = fullTypeName.substring(0,fullTypeName.indexOf(":")); } nsPrefix = nsPrefix==null?"":nsPrefix; java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":")+1); if (!"ENTITIES".equals(type)){ //find namespace for the prefix java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix); return (ENTITIES)org.apache.axis2.databinding.types.xsd.ExtensionMapper.getTypeObject( nsUri,type,reader); } } } // Note all attributes that were handled. Used to differ normal attributes // from anyAttributes. java.util.Vector handledAttributes = new java.util.Vector(); while(!reader.isEndElement()) { if (reader.isStartElement() || reader.hasText()){ if (reader.isStartElement() || reader.hasText()){ java.lang.String content = reader.getElementText(); object.setENTITIES( org.apache.axis2.databinding.utils.ConverterUtil.convertToENTITIES(content)); } // End of if for expected property start element else{ // A start element we are not expecting indicates an invalid parameter was passed throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName()); } } else { reader.next(); } } // end of while loop } catch (javax.xml.stream.XMLStreamException e) { throw new java.lang.Exception(e); } return object; } }//end of factory class }
arunasujith/wso2-axis2
modules/adb/src/org/apache/axis2/databinding/types/xsd/ENTITIES.java
Java
apache-2.0
21,086
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.core.ml.dataframe.evaluation.common; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.xpack.core.ml.dataframe.evaluation.classification.AucRoc; import org.elasticsearch.xpack.core.ml.dataframe.evaluation.common.AbstractAucRoc.AucRocPoint; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.hamcrest.Matchers.closeTo; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThanOrEqualTo; public class AbstractAucRocTests extends ESTestCase { public void testCalculateAucScore_GivenZeroPercentiles() { double[] tpPercentiles = zeroPercentiles(); double[] fpPercentiles = zeroPercentiles(); List<AucRocPoint> curve = AucRoc.buildAucRocCurve(tpPercentiles, fpPercentiles); double aucRocScore = AucRoc.calculateAucScore(curve); assertThat(aucRocScore, closeTo(0.5, 0.01)); } public void testCalculateAucScore_GivenRandomTpPercentilesAndZeroFpPercentiles() { double[] tpPercentiles = randomPercentiles(); double[] fpPercentiles = zeroPercentiles(); List<AucRocPoint> curve = AucRoc.buildAucRocCurve(tpPercentiles, fpPercentiles); double aucRocScore = AucRoc.calculateAucScore(curve); assertThat(aucRocScore, closeTo(1.0, 0.1)); } public void testCalculateAucScore_GivenZeroTpPercentilesAndRandomFpPercentiles() { double[] tpPercentiles = zeroPercentiles(); double[] fpPercentiles = randomPercentiles(); List<AucRocPoint> curve = AucRoc.buildAucRocCurve(tpPercentiles, fpPercentiles); double aucRocScore = AucRoc.calculateAucScore(curve); assertThat(aucRocScore, closeTo(0.0, 0.1)); } public void testCalculateAucScore_GivenRandomPercentiles() { for (int i = 0; i < 20; i++) { double[] tpPercentiles = randomPercentiles(); double[] fpPercentiles = randomPercentiles(); List<AucRocPoint> curve = AucRoc.buildAucRocCurve(tpPercentiles, fpPercentiles); double aucRocScore = AucRoc.calculateAucScore(curve); List<AucRocPoint> inverseCurve = AucRoc.buildAucRocCurve(fpPercentiles, tpPercentiles); double inverseAucRocScore = AucRoc.calculateAucScore(inverseCurve); assertThat(aucRocScore, greaterThanOrEqualTo(0.0)); assertThat(aucRocScore, lessThanOrEqualTo(1.0)); assertThat(inverseAucRocScore, greaterThanOrEqualTo(0.0)); assertThat(inverseAucRocScore, lessThanOrEqualTo(1.0)); assertThat(aucRocScore + inverseAucRocScore, closeTo(1.0, 0.05)); } } public void testCalculateAucScore_GivenPrecalculated() { double[] tpPercentiles = new double[99]; double[] fpPercentiles = new double[99]; double[] tpSimplified = new double[] { 0.3, 0.6, 0.5, 0.8 }; double[] fpSimplified = new double[] { 0.1, 0.3, 0.5, 0.5 }; for (int i = 0; i < tpPercentiles.length; i++) { int simplifiedIndex = i / 25; tpPercentiles[i] = tpSimplified[simplifiedIndex]; fpPercentiles[i] = fpSimplified[simplifiedIndex]; } List<AucRocPoint> curve = AucRoc.buildAucRocCurve(tpPercentiles, fpPercentiles); double aucRocScore = AucRoc.calculateAucScore(curve); List<AucRocPoint> inverseCurve = AucRoc.buildAucRocCurve(fpPercentiles, tpPercentiles); double inverseAucRocScore = AucRoc.calculateAucScore(inverseCurve); assertThat(aucRocScore, closeTo(0.8, 0.05)); assertThat(inverseAucRocScore, closeTo(0.2, 0.05)); } public void testCollapseEqualThresholdPoints_GivenEmpty() { assertThat(AbstractAucRoc.collapseEqualThresholdPoints(Collections.emptyList()), is(empty())); } public void testCollapseEqualThresholdPoints() { List<AucRocPoint> curve = Arrays.asList( new AucRocPoint(0.0, 0.0, 1.0), new AucRocPoint(0.1, 0.9, 0.1), new AucRocPoint(0.2, 0.8, 0.2), new AucRocPoint(0.1, 0.9, 0.2), new AucRocPoint(0.3, 0.6, 0.3), new AucRocPoint(0.5, 0.5, 0.4), new AucRocPoint(0.4, 0.6, 0.4), new AucRocPoint(0.9, 0.1, 0.4), new AucRocPoint(1.0, 1.0, 0.0) ); List<AucRocPoint> collapsed = AbstractAucRoc.collapseEqualThresholdPoints(curve); assertThat(collapsed.size(), equalTo(6)); assertThat(collapsed.get(0), equalTo(curve.get(0))); assertThat(collapsed.get(1), equalTo(curve.get(1))); assertPointCloseTo(collapsed.get(2), 0.15, 0.85, 0.2); assertThat(collapsed.get(3), equalTo(curve.get(4))); assertPointCloseTo(collapsed.get(4), 0.6, 0.4, 0.4); assertThat(collapsed.get(5), equalTo(curve.get(8))); } public static double[] zeroPercentiles() { double[] percentiles = new double[99]; Arrays.fill(percentiles, 0.0); return percentiles; } public static double[] randomPercentiles() { double[] percentiles = new double[99]; for (int i = 0; i < percentiles.length; i++) { percentiles[i] = randomDouble(); } Arrays.sort(percentiles); return percentiles; } private static void assertPointCloseTo(AucRocPoint point, double expectedTpr, double expectedFpr, double expectedThreshold) { assertThat(point.tpr, closeTo(expectedTpr, 0.00001)); assertThat(point.fpr, closeTo(expectedFpr, 0.00001)); assertThat(point.threshold, closeTo(expectedThreshold, 0.00001)); } }
GlenRSmith/elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/dataframe/evaluation/common/AbstractAucRocTests.java
Java
apache-2.0
6,032
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; import org.elasticsearch.xpack.ql.expression.Expression; import org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.Combinations; import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; import org.elasticsearch.xpack.ql.tree.AbstractNodeTestCase; import org.elasticsearch.xpack.ql.tree.Source; import java.util.ArrayList; import java.util.BitSet; import java.util.List; import java.util.Objects; import java.util.function.Function; import static org.elasticsearch.xpack.ql.expression.Expressions.pipe; import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomIntLiteral; import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; import static org.elasticsearch.xpack.ql.tree.SourceTests.randomSource; public class LocateFunctionPipeTests extends AbstractNodeTestCase<LocateFunctionPipe, Pipe> { @Override protected LocateFunctionPipe randomInstance() { return randomLocateFunctionPipe(); } private Expression randomLocateFunctionExpression() { return randomLocateFunctionPipe().expression(); } public static LocateFunctionPipe randomLocateFunctionPipe() { return (LocateFunctionPipe) (new Locate( randomSource(), randomStringLiteral(), randomStringLiteral(), randomFrom(true, false) ? randomIntLiteral() : null ).makePipe()); } @Override public void testTransform() { // test transforming only the properties (source, expression), // skipping the children (the two parameters of the binary function) which are tested separately LocateFunctionPipe b1 = randomInstance(); Expression newExpression = randomValueOtherThan(b1.expression(), () -> randomLocateFunctionExpression()); LocateFunctionPipe newB = new LocateFunctionPipe(b1.source(), newExpression, b1.pattern(), b1.input(), b1.start()); assertEquals(newB, b1.transformPropertiesOnly(Expression.class, v -> Objects.equals(v, b1.expression()) ? newExpression : v)); LocateFunctionPipe b2 = randomInstance(); Source newLoc = randomValueOtherThan(b2.source(), () -> randomSource()); newB = new LocateFunctionPipe(newLoc, b2.expression(), b2.pattern(), b2.input(), b2.start()); assertEquals(newB, b2.transformPropertiesOnly(Source.class, v -> Objects.equals(v, b2.source()) ? newLoc : v)); } @Override public void testReplaceChildren() { LocateFunctionPipe b = randomInstance(); Pipe newPattern = randomValueOtherThan(b.pattern(), () -> pipe(randomStringLiteral())); Pipe newInput = randomValueOtherThan(b.input(), () -> pipe(randomStringLiteral())); Pipe newStart = b.start() == null ? null : randomValueOtherThan(b.start(), () -> pipe(randomIntLiteral())); LocateFunctionPipe newB = new LocateFunctionPipe(b.source(), b.expression(), b.pattern(), b.input(), b.start()); LocateFunctionPipe transformed = null; // generate all the combinations of possible children modifications and test all of them for (int i = 1; i < 4; i++) { for (BitSet comb : new Combinations(3, i)) { Pipe tempNewStart = b.start() == null ? b.start() : (comb.get(2) ? newStart : b.start()); transformed = (LocateFunctionPipe) newB.replaceChildren( comb.get(0) ? newPattern : b.pattern(), comb.get(1) ? newInput : b.input(), tempNewStart ); assertEquals(transformed.pattern(), comb.get(0) ? newPattern : b.pattern()); assertEquals(transformed.input(), comb.get(1) ? newInput : b.input()); assertEquals(transformed.start(), tempNewStart); assertEquals(transformed.expression(), b.expression()); assertEquals(transformed.source(), b.source()); } } } @Override protected LocateFunctionPipe mutate(LocateFunctionPipe instance) { List<Function<LocateFunctionPipe, LocateFunctionPipe>> randoms = new ArrayList<>(); if (instance.start() == null) { for (int i = 1; i < 3; i++) { for (BitSet comb : new Combinations(2, i)) { randoms.add( f -> new LocateFunctionPipe( f.source(), f.expression(), comb.get(0) ? randomValueOtherThan(f.pattern(), () -> pipe(randomStringLiteral())) : f.pattern(), comb.get(1) ? randomValueOtherThan(f.input(), () -> pipe(randomStringLiteral())) : f.input(), null ) ); } } } else { for (int i = 1; i < 4; i++) { for (BitSet comb : new Combinations(3, i)) { randoms.add( f -> new LocateFunctionPipe( f.source(), f.expression(), comb.get(0) ? randomValueOtherThan(f.pattern(), () -> pipe(randomStringLiteral())) : f.pattern(), comb.get(1) ? randomValueOtherThan(f.input(), () -> pipe(randomStringLiteral())) : f.input(), comb.get(2) ? randomValueOtherThan(f.start(), () -> pipe(randomIntLiteral())) : f.start() ) ); } } } return randomFrom(randoms).apply(instance); } @Override protected LocateFunctionPipe copy(LocateFunctionPipe instance) { return new LocateFunctionPipe(instance.source(), instance.expression(), instance.pattern(), instance.input(), instance.start()); } }
GlenRSmith/elasticsearch
x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/LocateFunctionPipeTests.java
Java
apache-2.0
6,207
/* * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* this file is generated by RelaxNGCC */ package com.sun.tools.internal.jxc.gen.config; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.Attributes; import com.sun.tools.internal.jxc.NGCCRuntimeEx; import java.util.List; import java.util.ArrayList; /** * <p><b> * Auto-generated, do not edit. * </b></p> */ public class Classes extends NGCCHandler { private String __text; private String exclude_content; private String include_content; protected final NGCCRuntimeEx $runtime; private int $_ngcc_current_state; protected String $uri; protected String $localName; protected String $qname; public final NGCCRuntime getRuntime() { return($runtime); } public Classes(NGCCHandler parent, NGCCEventSource source, NGCCRuntimeEx runtime, int cookie) { super(source, parent, cookie); $runtime = runtime; $_ngcc_current_state = 12; } public Classes(NGCCRuntimeEx runtime) { this(null, runtime, runtime, -1); } private void action0()throws SAXException { this.excludes.add(exclude_content); } private void action1()throws SAXException { $runtime.processList(__text);} private void action2()throws SAXException { this.includes.add(include_content); } private void action3()throws SAXException { $runtime.processList(__text);} public void enterElement(String $__uri, String $__local, String $__qname, Attributes $attrs) throws SAXException { int $ai; $uri = $__uri; $localName = $__local; $qname = $__qname; switch($_ngcc_current_state) { case 12: { if(($__uri.equals("") && $__local.equals("classes"))) { $runtime.onEnterElementConsumed($__uri, $__local, $__qname, $attrs); $_ngcc_current_state = 11; } else { unexpectedEnterElement($__qname); } } break; case 2: { if(($__uri.equals("") && $__local.equals("excludes"))) { $runtime.onEnterElementConsumed($__uri, $__local, $__qname, $attrs); $_ngcc_current_state = 6; } else { $_ngcc_current_state = 1; $runtime.sendEnterElement(super._cookie, $__uri, $__local, $__qname, $attrs); } } break; case 4: { $_ngcc_current_state = 3; $runtime.sendEnterElement(super._cookie, $__uri, $__local, $__qname, $attrs); } break; case 11: { if(($__uri.equals("") && $__local.equals("includes"))) { $runtime.onEnterElementConsumed($__uri, $__local, $__qname, $attrs); $_ngcc_current_state = 10; } else { unexpectedEnterElement($__qname); } } break; case 0: { revertToParentFromEnterElement(this, super._cookie, $__uri, $__local, $__qname, $attrs); } break; default: { unexpectedEnterElement($__qname); } break; } } public void leaveElement(String $__uri, String $__local, String $__qname) throws SAXException { int $ai; $uri = $__uri; $localName = $__local; $qname = $__qname; switch($_ngcc_current_state) { case 2: { $_ngcc_current_state = 1; $runtime.sendLeaveElement(super._cookie, $__uri, $__local, $__qname); } break; case 4: { $_ngcc_current_state = 3; $runtime.sendLeaveElement(super._cookie, $__uri, $__local, $__qname); } break; case 1: { if(($__uri.equals("") && $__local.equals("classes"))) { $runtime.onLeaveElementConsumed($__uri, $__local, $__qname); $_ngcc_current_state = 0; } else { unexpectedLeaveElement($__qname); } } break; case 3: { if(($__uri.equals("") && $__local.equals("excludes"))) { $runtime.onLeaveElementConsumed($__uri, $__local, $__qname); $_ngcc_current_state = 1; } else { unexpectedLeaveElement($__qname); } } break; case 0: { revertToParentFromLeaveElement(this, super._cookie, $__uri, $__local, $__qname); } break; case 8: { if(($__uri.equals("") && $__local.equals("includes"))) { $runtime.onLeaveElementConsumed($__uri, $__local, $__qname); $_ngcc_current_state = 2; } else { unexpectedLeaveElement($__qname); } } break; default: { unexpectedLeaveElement($__qname); } break; } } public void enterAttribute(String $__uri, String $__local, String $__qname) throws SAXException { int $ai; $uri = $__uri; $localName = $__local; $qname = $__qname; switch($_ngcc_current_state) { case 2: { $_ngcc_current_state = 1; $runtime.sendEnterAttribute(super._cookie, $__uri, $__local, $__qname); } break; case 4: { $_ngcc_current_state = 3; $runtime.sendEnterAttribute(super._cookie, $__uri, $__local, $__qname); } break; case 0: { revertToParentFromEnterAttribute(this, super._cookie, $__uri, $__local, $__qname); } break; default: { unexpectedEnterAttribute($__qname); } break; } } public void leaveAttribute(String $__uri, String $__local, String $__qname) throws SAXException { int $ai; $uri = $__uri; $localName = $__local; $qname = $__qname; switch($_ngcc_current_state) { case 2: { $_ngcc_current_state = 1; $runtime.sendLeaveAttribute(super._cookie, $__uri, $__local, $__qname); } break; case 4: { $_ngcc_current_state = 3; $runtime.sendLeaveAttribute(super._cookie, $__uri, $__local, $__qname); } break; case 0: { revertToParentFromLeaveAttribute(this, super._cookie, $__uri, $__local, $__qname); } break; default: { unexpectedLeaveAttribute($__qname); } break; } } public void text(String $value) throws SAXException { int $ai; switch($_ngcc_current_state) { case 2: { $_ngcc_current_state = 1; $runtime.sendText(super._cookie, $value); } break; case 4: { exclude_content = $value; $_ngcc_current_state = 3; action0(); } break; case 10: { __text = $value; $_ngcc_current_state = 9; action3(); } break; case 3: { exclude_content = $value; $_ngcc_current_state = 3; action0(); } break; case 6: { __text = $value; $_ngcc_current_state = 4; action1(); } break; case 0: { revertToParentFromText(this, super._cookie, $value); } break; case 9: { include_content = $value; $_ngcc_current_state = 8; action2(); } break; case 8: { include_content = $value; $_ngcc_current_state = 8; action2(); } break; } } public void onChildCompleted(Object result, int cookie, boolean needAttCheck)throws SAXException { switch(cookie) { } } public boolean accepted() { return(($_ngcc_current_state == 0)); } private List includes = new ArrayList(); public List getIncludes() { return $runtime.getIncludePatterns(this.includes);} private List excludes = new ArrayList(); public List getExcludes() { return $runtime.getExcludePatterns(this.excludes);} }
rokn/Count_Words_2015
testing/openjdk2/jaxws/src/share/jaxws_classes/com/sun/tools/internal/jxc/gen/config/Classes.java
Java
mit
10,462
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide.util; import com.intellij.ide.structureView.StructureViewModel; import com.intellij.ide.structureView.newStructureView.TreeActionsOwner; import com.intellij.ide.util.treeView.smartTree.Sorter; import com.intellij.ide.util.treeView.smartTree.TreeAction; import java.util.HashSet; import java.util.Set; /** * @author Konstantin Bulenkov */ class TreeStructureActionsOwner implements TreeActionsOwner { private final Set<TreeAction> myActions = new HashSet<>(); private final StructureViewModel myModel; TreeStructureActionsOwner(StructureViewModel model) { myModel = model; } @Override public void setActionActive(String name, boolean state) { } @Override public boolean isActionActive(String name) { for (final Sorter sorter : myModel.getSorters()) { if (sorter.getName().equals(name)) { if (!sorter.isVisible()) return true; } } for(TreeAction action: myActions) { if (action.getName().equals(name)) return true; } return false; } public void setActionIncluded(final TreeAction filter, final boolean selected) { if (selected) { myActions.add(filter); } else { myActions.remove(filter); } } }
siosio/intellij-community
platform/lang-impl/src/com/intellij/ide/util/TreeStructureActionsOwner.java
Java
apache-2.0
1,827
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.search.lookup; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.IntsRef; import java.io.IOException; import java.util.Iterator; /* * Can iterate over the positions of a term an arbotrary number of times. * */ public class CachedPositionIterator extends PositionIterator { public CachedPositionIterator(IndexFieldTerm indexFieldTerm) { super(indexFieldTerm); } // all payloads of the term in the current document in one bytes array. // payloadStarts and payloadLength mark the start and end of one payload. final BytesRef payloads = new BytesRef(); final IntsRef payloadsLengths = new IntsRef(0); final IntsRef payloadsStarts = new IntsRef(0); final IntsRef positions = new IntsRef(0); final IntsRef startOffsets = new IntsRef(0); final IntsRef endOffsets = new IntsRef(0); @Override public Iterator<TermPosition> reset() { return new Iterator<TermPosition>() { private int pos = 0; private final TermPosition termPosition = new TermPosition(); @Override public boolean hasNext() { return pos < freq; } @Override public TermPosition next() { termPosition.position = positions.ints[pos]; termPosition.startOffset = startOffsets.ints[pos]; termPosition.endOffset = endOffsets.ints[pos]; termPosition.payload = payloads; payloads.offset = payloadsStarts.ints[pos]; payloads.length = payloadsLengths.ints[pos]; pos++; return termPosition; } @Override public void remove() { } }; } private void record() throws IOException { TermPosition termPosition; for (int i = 0; i < freq; i++) { termPosition = super.next(); positions.ints[i] = termPosition.position; addPayload(i, termPosition.payload); startOffsets.ints[i] = termPosition.startOffset; endOffsets.ints[i] = termPosition.endOffset; } } private void ensureSize(int freq) { if (freq == 0) { return; } if (startOffsets.ints.length < freq) { startOffsets.grow(freq); endOffsets.grow(freq); positions.grow(freq); payloadsLengths.grow(freq); payloadsStarts.grow(freq); } payloads.offset = 0; payloadsLengths.offset = 0; payloadsStarts.offset = 0; payloads.grow(freq * 8);// this is just a guess.... } private void addPayload(int i, BytesRef currPayload) { if (currPayload != null) { payloadsLengths.ints[i] = currPayload.length; payloadsStarts.ints[i] = i == 0 ? 0 : payloadsStarts.ints[i - 1] + payloadsLengths.ints[i - 1]; if (payloads.bytes.length < payloadsStarts.ints[i] + payloadsLengths.ints[i]) { payloads.offset = 0; // the offset serves no purpose here. but // we must assure that it is 0 before // grow() is called payloads.grow(payloads.bytes.length * 2); // just a guess } System.arraycopy(currPayload.bytes, currPayload.offset, payloads.bytes, payloadsStarts.ints[i], currPayload.length); } else { payloadsLengths.ints[i] = 0; payloadsStarts.ints[i] = i == 0 ? 0 : payloadsStarts.ints[i - 1] + payloadsLengths.ints[i - 1]; } } @Override public void nextDoc() throws IOException { super.nextDoc(); ensureSize(freq); record(); } @Override public TermPosition next() { throw new UnsupportedOperationException(); } }
corochoone/elasticsearch
src/main/java/org/elasticsearch/search/lookup/CachedPositionIterator.java
Java
apache-2.0
4,698
/** * Copyright (c) 2010-2016, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.maxcul.internal.messages; /** * Message to set either the Wall Thermostat display shows the actual temperature * * @author Johannes Goehr (johgoe) * @since 1.8.0 */ public class SetDisplayActualTempMsg extends BaseMsg { private static final int SET_DISPLAY_ACTUAL_TEMP_PAYLOAD_LEN = 1; public SetDisplayActualTempMsg(byte msgCount, byte msgFlag, byte groupId, String srcAddr, String dstAddr, boolean displayActualTemp) { super(msgCount, msgFlag, MaxCulMsgType.SET_DISPLAY_ACTUAL_TEMP, groupId, srcAddr, dstAddr); byte[] payload = new byte[SET_DISPLAY_ACTUAL_TEMP_PAYLOAD_LEN]; payload[0] = displayActualTemp ? (byte) 0x04 : (byte) 0x00; super.appendPayload(payload); } }
paolodenti/openhab
bundles/binding/org.openhab.binding.maxcul/src/main/java/org/openhab/binding/maxcul/internal/messages/SetDisplayActualTempMsg.java
Java
epl-1.0
1,073
/**************************************************************************************** * Copyright (c) 2013 Bibek Shrestha <[email protected]> * * Copyright (c) 2013 Zaur Molotnikov <[email protected]> * * Copyright (c) 2013 Nicolas Raoul <[email protected]> * * Copyright (c) 2013 Flavio Lerda <[email protected]> * * * * 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 com.ichi2.anki.multimediacard.fields; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TextView; import android.widget.Toast; import com.ichi2.anki.AnkiDroidApp; import com.ichi2.anki.R; import com.ichi2.anki.multimediacard.activity.LoadPronounciationActivity; import com.ichi2.anki.multimediacard.activity.PickStringDialogFragment; import com.ichi2.anki.multimediacard.activity.SearchImageActivity; import com.ichi2.anki.multimediacard.activity.TranslationActivity; import java.io.File; import java.util.ArrayList; import java.util.List; /** * One of the most powerful controllers - creates UI and works with the field of textual type. * <p> * Controllers work with the edit field activity and create UI on it to edit a field. */ public class BasicTextFieldController extends FieldControllerBase implements IFieldController, DialogInterface.OnClickListener { // Additional activities are started to perform translation/image search and // so on, here are their request codes, to differentiate, when they return. private static final int REQUEST_CODE_TRANSLATE_GLOSBE = 101; private static final int REQUEST_CODE_PRONOUNCIATION = 102; private static final int REQUEST_CODE_TRANSLATE_COLORDICT = 103; private static final int REQUEST_CODE_IMAGE_SEARCH = 104; private TextView mSearchLabel; private EditText mEditText; // This is used to copy from another field value to this field private ArrayList<String> mPossibleClones; @Override public void createUI(LinearLayout layout) { mEditText = new EditText(mActivity); mEditText.setMinLines(3); mEditText.setText(mField.getText()); layout.addView(mEditText, LinearLayout.LayoutParams.FILL_PARENT); LinearLayout layoutTools = new LinearLayout(mActivity); layoutTools.setOrientation(LinearLayout.HORIZONTAL); layout.addView(layoutTools); LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.FILL_PARENT, 1); createCloneButton(layoutTools, p); createClearButton(layoutTools, p); // search label mSearchLabel = new TextView(mActivity); mSearchLabel.setText(R.string.multimedia_editor_text_field_editing_search_label); layout.addView(mSearchLabel); // search buttons LinearLayout layoutTools2 = new LinearLayout(mActivity); layoutTools2.setOrientation(LinearLayout.HORIZONTAL); layout.addView(layoutTools2); createTranslateButton(layoutTools2, p); createPronounceButton(layoutTools2, p); createSearchImageButton(layoutTools2, p); } private String gtxt(int id) { return mActivity.getText(id).toString(); } /** * Google Image Search * * @param layoutTools * @param p */ private void createSearchImageButton(LinearLayout layoutTools, LayoutParams p) { Button clearButton = new Button(mActivity); clearButton.setText(gtxt(R.string.multimedia_editor_text_field_editing_show)); layoutTools.addView(clearButton, p); clearButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String source = mEditText.getText().toString(); if (source.length() == 0) { showToast(gtxt(R.string.multimedia_editor_text_field_editing_no_text)); return; } Intent intent = new Intent(mActivity, SearchImageActivity.class); intent.putExtra(SearchImageActivity.EXTRA_SOURCE, source); mActivity.startActivityForResult(intent, REQUEST_CODE_IMAGE_SEARCH); } }); } private void createClearButton(LinearLayout layoutTools, LayoutParams p) { Button clearButton = new Button(mActivity); clearButton.setText(gtxt(R.string.multimedia_editor_text_field_editing_clear)); layoutTools.addView(clearButton, p); clearButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mEditText.setText(""); } }); } /** * @param layoutTools * @param p Button to load pronunciation from Beolingus */ private void createPronounceButton(LinearLayout layoutTools, LayoutParams p) { Button btnPronounce = new Button(mActivity); btnPronounce.setText(gtxt(R.string.multimedia_editor_text_field_editing_say)); btnPronounce.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String source = mEditText.getText().toString(); if (source.length() == 0) { showToast(gtxt(R.string.multimedia_editor_text_field_editing_no_text)); return; } Intent intent = new Intent(mActivity, LoadPronounciationActivity.class); intent.putExtra(LoadPronounciationActivity.EXTRA_SOURCE, source); mActivity.startActivityForResult(intent, REQUEST_CODE_PRONOUNCIATION); } }); layoutTools.addView(btnPronounce, p); } // Here is all the functionality to provide translations private void createTranslateButton(LinearLayout layoutTool, LayoutParams ps) { Button btnTranslate = new Button(mActivity); btnTranslate.setText(gtxt(R.string.multimedia_editor_text_field_editing_translate)); btnTranslate.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String source = mEditText.getText().toString(); // Checks and warnings if (source.length() == 0) { showToast(gtxt(R.string.multimedia_editor_text_field_editing_no_text)); return; } if (source.contains(" ")) { showToast(gtxt(R.string.multimedia_editor_text_field_editing_many_words)); } // Pick from two translation sources PickStringDialogFragment fragment = new PickStringDialogFragment(); final ArrayList<String> translationSources = new ArrayList<String>(); translationSources.add("Glosbe.com"); // Chromebooks do not support dependent apps yet. if (!AnkiDroidApp.isChromebook()) { translationSources.add("ColorDict"); } fragment.setChoices(translationSources); fragment.setOnclickListener(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String translationSource = translationSources.get(which); if (translationSource.equals("Glosbe.com")) { startTranslationWithGlosbe(); } else if (translationSource.equals("ColorDict")) { startTranslationWithColorDict(); } } }); fragment.setTitle(gtxt(R.string.multimedia_editor_trans_pick_translation_source)); fragment.show(mActivity.getSupportFragmentManager(), "pick.translation.source"); } }); layoutTool.addView(btnTranslate, ps); // flow continues in Start Translation with... } /** * @param activity * @param layoutTools This creates a button, which will call a dialog, allowing to pick from another note's fields * one, and use it's value in the current one. * @param p */ private void createCloneButton(LinearLayout layoutTools, LayoutParams p) { // Makes sense only for two and more fields if (mNote.getNumberOfFields() > 1) { // Should be more than one text not empty fields for clone to make // sense mPossibleClones = new ArrayList<String>(); int numTextFields = 0; for (int i = 0; i < mNote.getNumberOfFields(); ++i) { // Sort out non text and empty fields IField curField = mNote.getField(i); if (curField == null) { continue; } if (curField.getType() != EFieldType.TEXT) { continue; } if (curField.getText() == null) { continue; } if (curField.getText().length() == 0) { continue; } // as well as the same field if (curField.getText().contentEquals(mField.getText())) { continue; } // collect clone sources mPossibleClones.add(curField.getText()); ++numTextFields; } // Nothing to clone from if (numTextFields < 1) { return; } Button btnOtherField = new Button(mActivity); btnOtherField.setText(gtxt(R.string.multimedia_editor_text_field_editing_clone)); layoutTools.addView(btnOtherField, p); final BasicTextFieldController controller = this; btnOtherField.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { PickStringDialogFragment fragment = new PickStringDialogFragment(); fragment.setChoices(mPossibleClones); fragment.setOnclickListener(controller); fragment.setTitle(gtxt(R.string.multimedia_editor_text_field_editing_clone_source)); fragment.show(mActivity.getSupportFragmentManager(), "pick.clone"); // flow continues in the onClick function } }); } } /* * (non-Javadoc) * @see com.ichi2.anki.IFieldController#onActivityResult(int, int, android.content.Intent) When activity started * from here returns, the EditFieldActivity passes control here back. And the results from the started before * activity are received. */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE_TRANSLATE_GLOSBE && resultCode == Activity.RESULT_OK) { // Translation returned. try { String translation = data.getExtras().get(TranslationActivity.EXTRA_TRANSLATION).toString(); mEditText.setText(translation); } catch (Exception e) { showToast(gtxt(R.string.multimedia_editor_trans_translation_failed)); } } else if (requestCode == REQUEST_CODE_PRONOUNCIATION && resultCode == Activity.RESULT_OK) { try { String pronuncPath = data.getExtras().get(LoadPronounciationActivity.EXTRA_PRONUNCIATION_FILE_PATH) .toString(); File f = new File(pronuncPath); if (!f.exists()) { showToast(gtxt(R.string.multimedia_editor_pron_pronunciation_failed)); } AudioField af = new AudioField(); af.setAudioPath(pronuncPath); // This is done to delete the file later. af.setHasTemporaryMedia(true); mActivity.handleFieldChanged(af); } catch (Exception e) { showToast(gtxt(R.string.multimedia_editor_pron_pronunciation_failed)); } } else if (requestCode == REQUEST_CODE_TRANSLATE_COLORDICT && resultCode == Activity.RESULT_OK) { // String subject = data.getStringExtra(Intent.EXTRA_SUBJECT); String text = data.getStringExtra(Intent.EXTRA_TEXT); mEditText.setText(text); } else if (requestCode == REQUEST_CODE_IMAGE_SEARCH && resultCode == Activity.RESULT_OK) { String imgPath = data.getExtras().get(SearchImageActivity.EXTRA_IMAGE_FILE_PATH).toString(); File f = new File(imgPath); if (!f.exists()) { showToast(gtxt(R.string.multimedia_editor_imgs_failed)); } ImageField imgField = new ImageField(); imgField.setImagePath(imgPath); imgField.setHasTemporaryMedia(true); mActivity.handleFieldChanged(imgField); } } /** * @param context * @param intent * @return Needed to check, if the Color Dict is installed */ public static boolean isIntentAvailable(Context context, Intent intent) { final PackageManager packageManager = context.getPackageManager(); List<?> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); return list.size() > 0; } // When Done button is clicked @Override public void onDone() { mField.setText(mEditText.getText().toString()); } // This is when the dialog for clone ends @Override public void onClick(DialogInterface dialog, int which) { mEditText.setText(mPossibleClones.get(which)); } /** * @param text A short cut to show a toast */ private void showToast(CharSequence text) { int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(mActivity, text, duration); toast.show(); } // Only now not all APIs are used, may be later, they will be. @SuppressWarnings("unused") protected void startTranslationWithColorDict() { final String PICK_RESULT_ACTION = "colordict.intent.action.PICK_RESULT"; final String SEARCH_ACTION = "colordict.intent.action.SEARCH"; final String EXTRA_QUERY = "EXTRA_QUERY"; final String EXTRA_FULLSCREEN = "EXTRA_FULLSCREEN"; final String EXTRA_HEIGHT = "EXTRA_HEIGHT"; final String EXTRA_WIDTH = "EXTRA_WIDTH"; final String EXTRA_GRAVITY = "EXTRA_GRAVITY"; final String EXTRA_MARGIN_LEFT = "EXTRA_MARGIN_LEFT"; final String EXTRA_MARGIN_TOP = "EXTRA_MARGIN_TOP"; final String EXTRA_MARGIN_BOTTOM = "EXTRA_MARGIN_BOTTOM"; final String EXTRA_MARGIN_RIGHT = "EXTRA_MARGIN_RIGHT"; Intent intent = new Intent(PICK_RESULT_ACTION); intent.putExtra(EXTRA_QUERY, mEditText.getText().toString()); // Search // Query intent.putExtra(EXTRA_FULLSCREEN, false); // // intent.putExtra(EXTRA_HEIGHT, 400); //400pixel, if you don't specify, // fill_parent" intent.putExtra(EXTRA_GRAVITY, Gravity.BOTTOM); // intent.putExtra(EXTRA_MARGIN_LEFT, 100); if (!isIntentAvailable(mActivity, intent)) { showToast(gtxt(R.string.multimedia_editor_trans_install_color_dict)); return; } mActivity.startActivityForResult(intent, REQUEST_CODE_TRANSLATE_COLORDICT); } protected void startTranslationWithGlosbe() { String source = mEditText.getText().toString(); Intent intent = new Intent(mActivity, TranslationActivity.class); intent.putExtra(TranslationActivity.EXTRA_SOURCE, source); mActivity.startActivityForResult(intent, REQUEST_CODE_TRANSLATE_GLOSBE); } @Override public void onDestroy() { // TODO Auto-generated method stub } }
sundoresu/Anki-Android
src/com/ichi2/anki/multimediacard/fields/BasicTextFieldController.java
Java
gpl-3.0
17,700
/* * Copyright (C) 2008 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.common.collect.testing.testers; import com.google.common.collect.testing.features.CollectionFeature; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; import com.google.common.collect.testing.features.CollectionSize; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.ZERO; /** * A generic JUnit test which tests {@code remove(Object)} operations on a list. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * @author George van den Driessche */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" public class ListRemoveTester<E> extends AbstractListTester<E> { @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(absent = {ZERO, ONE}) public void testRemove_duplicate() { ArrayWithDuplicate<E> arrayAndDuplicate = createArrayWithDuplicateElement(); collection = getSubjectGenerator().create(arrayAndDuplicate.elements); E duplicate = arrayAndDuplicate.duplicate; int firstIndex = getList().indexOf(duplicate); int initialSize = getList().size(); assertTrue("remove(present) should return true", getList().remove(duplicate)); assertTrue("After remove(duplicate), a list should still contain " + "the duplicate element", getList().contains(duplicate)); assertFalse("remove(duplicate) should remove the first instance of the " + "duplicate element in the list", firstIndex == getList().indexOf(duplicate)); assertEquals("remove(present) should decrease the size of a list by one.", initialSize - 1, getList().size()); } }
rzel/google-collections
testfw/com/google/common/collect/testing/testers/ListRemoveTester.java
Java
apache-2.0
2,370
package com.dianping.cat.system.page.login.spi; public interface ISessionManager<S extends ISession, T extends IToken, C extends ICredential> { public T authenticate(C credential); public S validate(T token); }
jialinsun/cat
cat-home/src/main/java/com/dianping/cat/system/page/login/spi/ISessionManager.java
Java
apache-2.0
220
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.search.aggregations.bucket; import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.geo.GeoDistance; import org.elasticsearch.common.geo.GeoPoint; import org.elasticsearch.common.unit.DistanceUnit; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.search.aggregations.BaseAggregationTestCase; import org.elasticsearch.search.aggregations.bucket.range.GeoDistanceAggregationBuilder; import org.elasticsearch.search.aggregations.bucket.range.GeoDistanceAggregationBuilder.Range; import org.elasticsearch.test.geo.RandomShapeGenerator; import java.io.IOException; import static org.hamcrest.Matchers.containsString; public class GeoDistanceRangeTests extends BaseAggregationTestCase<GeoDistanceAggregationBuilder> { @Override protected GeoDistanceAggregationBuilder createTestAggregatorBuilder() { int numRanges = randomIntBetween(1, 10); GeoPoint origin = RandomShapeGenerator.randomPoint(random()); GeoDistanceAggregationBuilder factory = new GeoDistanceAggregationBuilder("foo", origin); for (int i = 0; i < numRanges; i++) { String key = null; if (randomBoolean()) { key = randomAlphaOfLengthBetween(1, 20); } double from = randomBoolean() ? 0 : randomIntBetween(0, Integer.MAX_VALUE - 1000); double to = randomBoolean() ? Double.POSITIVE_INFINITY : (Double.compare(from, 0) == 0 ? randomIntBetween(0, Integer.MAX_VALUE) : randomIntBetween((int) from, Integer.MAX_VALUE)); factory.addRange(new Range(key, from, to)); } factory.field(randomAlphaOfLengthBetween(1, 20)); if (randomBoolean()) { factory.keyed(randomBoolean()); } if (randomBoolean()) { factory.missing("0, 0"); } if (randomBoolean()) { factory.unit(randomFrom(DistanceUnit.values())); } if (randomBoolean()) { factory.distanceType(randomFrom(GeoDistance.values())); } return factory; } public void testParsingRangeStrict() throws IOException { final String rangeAggregation = "{\n" + "\"field\" : \"location\",\n" + "\"origin\" : \"52.3760, 4.894\",\n" + "\"unit\" : \"m\",\n" + "\"ranges\" : [\n" + " { \"from\" : 10000, \"to\" : 20000, \"badField\" : \"abcd\" }\n" + "]\n" + "}"; XContentParser parser = createParser(JsonXContent.jsonXContent, rangeAggregation); ParsingException ex = expectThrows(ParsingException.class, () -> GeoDistanceAggregationBuilder.parse("aggregationName", parser)); assertThat(ex.getDetailedMessage(), containsString("badField")); } /** * We never render "null" values to xContent, but we should test that we can parse them (and they return correct defaults) */ public void testParsingNull() throws IOException { final String rangeAggregation = "{\n" + "\"field\" : \"location\",\n" + "\"origin\" : \"52.3760, 4.894\",\n" + "\"unit\" : \"m\",\n" + "\"ranges\" : [\n" + " { \"from\" : null, \"to\" : null }\n" + "]\n" + "}"; XContentParser parser = createParser(JsonXContent.jsonXContent, rangeAggregation); GeoDistanceAggregationBuilder aggregationBuilder = (GeoDistanceAggregationBuilder) GeoDistanceAggregationBuilder .parse("aggregationName", parser); assertEquals(1, aggregationBuilder.range().size()); assertEquals(0.0, aggregationBuilder.range().get(0).getFrom(), 0.0); assertEquals(Double.POSITIVE_INFINITY, aggregationBuilder.range().get(0).getTo(), 0.0); } }
qwerty4030/elasticsearch
server/src/test/java/org/elasticsearch/search/aggregations/bucket/GeoDistanceRangeTests.java
Java
apache-2.0
4,766
package org.java_websocket; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; import java.nio.channels.NotYetConnectedException; import java.nio.channels.SelectionKey; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import org.java_websocket.drafts.Draft; import org.java_websocket.drafts.Draft.CloseHandshakeType; import org.java_websocket.drafts.Draft.HandshakeState; import org.java_websocket.drafts.Draft_10; import org.java_websocket.drafts.Draft_17; import org.java_websocket.drafts.Draft_75; import org.java_websocket.drafts.Draft_76; import org.java_websocket.exceptions.IncompleteHandshakeException; import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.exceptions.InvalidHandshakeException; import org.java_websocket.exceptions.WebsocketNotConnectedException; import org.java_websocket.framing.CloseFrame; import org.java_websocket.framing.CloseFrameBuilder; import org.java_websocket.framing.Framedata; import org.java_websocket.framing.Framedata.Opcode; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.ClientHandshakeBuilder; import org.java_websocket.handshake.Handshakedata; import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.handshake.ServerHandshakeBuilder; import org.java_websocket.server.WebSocketServer.WebSocketWorker; import org.java_websocket.util.Charsetfunctions; /** * Represents one end (client or server) of a single WebSocketImpl connection. * Takes care of the "handshake" phase, then allows for easy sending of * text frames, and receiving frames through an event-based model. * */ public class WebSocketImpl implements WebSocket { public static int RCVBUF = 16384; public static/*final*/boolean DEBUG = false; // must be final in the future in order to take advantage of VM optimization public static final List<Draft> defaultdraftlist = new ArrayList<Draft>( 4 ); static { defaultdraftlist.add( new Draft_17() ); defaultdraftlist.add( new Draft_10() ); defaultdraftlist.add( new Draft_76() ); defaultdraftlist.add( new Draft_75() ); } public SelectionKey key; /** the possibly wrapped channel object whose selection is controlled by {@link #key} */ public ByteChannel channel; /** * Queue of buffers that need to be sent to the client. */ public final BlockingQueue<ByteBuffer> outQueue; /** * Queue of buffers that need to be processed */ public final BlockingQueue<ByteBuffer> inQueue; /** * Helper variable meant to store the thread which ( exclusively ) triggers this objects decode method. **/ public volatile WebSocketWorker workerThread; // TODO reset worker? /** When true no further frames may be submitted to be sent */ private volatile boolean flushandclosestate = false; private READYSTATE readystate = READYSTATE.NOT_YET_CONNECTED; /** * The listener to notify of WebSocket events. */ private final WebSocketListener wsl; private List<Draft> knownDrafts; private Draft draft = null; private Role role; private Opcode current_continuous_frame_opcode = null; /** the bytes of an incomplete received handshake */ private ByteBuffer tmpHandshakeBytes = ByteBuffer.allocate( 0 ); /** stores the handshake sent by this websocket ( Role.CLIENT only ) */ private ClientHandshake handshakerequest = null; private String closemessage = null; private Integer closecode = null; private Boolean closedremotely = null; private String resourceDescriptor = null; /** * crates a websocket with server role */ public WebSocketImpl( WebSocketListener listener , List<Draft> drafts ) { this( listener, (Draft) null ); this.role = Role.SERVER; // draft.copyInstance will be called when the draft is first needed if( drafts == null || drafts.isEmpty() ) { knownDrafts = defaultdraftlist; } else { knownDrafts = drafts; } } /** * crates a websocket with client role * * @param listener * may be unbound */ public WebSocketImpl( WebSocketListener listener , Draft draft ) { if( listener == null || ( draft == null && role == Role.SERVER ) )// socket can be null because we want do be able to create the object without already having a bound channel throw new IllegalArgumentException( "parameters must not be null" ); this.outQueue = new LinkedBlockingQueue<ByteBuffer>(); inQueue = new LinkedBlockingQueue<ByteBuffer>(); this.wsl = listener; this.role = Role.CLIENT; if( draft != null ) this.draft = draft.copyInstance(); } @Deprecated public WebSocketImpl( WebSocketListener listener , Draft draft , Socket socket ) { this( listener, draft ); } @Deprecated public WebSocketImpl( WebSocketListener listener , List<Draft> drafts , Socket socket ) { this( listener, drafts ); } /** * */ public void decode( ByteBuffer socketBuffer ) { assert ( socketBuffer.hasRemaining() ); if( DEBUG ) System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" ); if( readystate != READYSTATE.NOT_YET_CONNECTED ) { decodeFrames( socketBuffer );; } else { if( decodeHandshake( socketBuffer ) ) { assert ( tmpHandshakeBytes.hasRemaining() != socketBuffer.hasRemaining() || !socketBuffer.hasRemaining() ); // the buffers will never have remaining bytes at the same time if( socketBuffer.hasRemaining() ) { decodeFrames( socketBuffer ); } else if( tmpHandshakeBytes.hasRemaining() ) { decodeFrames( tmpHandshakeBytes ); } } } assert ( isClosing() || isFlushAndClose() || !socketBuffer.hasRemaining() ); } /** * Returns whether the handshake phase has is completed. * In case of a broken handshake this will be never the case. **/ private boolean decodeHandshake( ByteBuffer socketBufferNew ) { ByteBuffer socketBuffer; if( tmpHandshakeBytes.capacity() == 0 ) { socketBuffer = socketBufferNew; } else { if( tmpHandshakeBytes.remaining() < socketBufferNew.remaining() ) { ByteBuffer buf = ByteBuffer.allocate( tmpHandshakeBytes.capacity() + socketBufferNew.remaining() ); tmpHandshakeBytes.flip(); buf.put( tmpHandshakeBytes ); tmpHandshakeBytes = buf; } tmpHandshakeBytes.put( socketBufferNew ); tmpHandshakeBytes.flip(); socketBuffer = tmpHandshakeBytes; } socketBuffer.mark(); try { if( draft == null ) { HandshakeState isflashedgecase = isFlashEdgeCase( socketBuffer ); if( isflashedgecase == HandshakeState.MATCHED ) { try { write( ByteBuffer.wrap( Charsetfunctions.utf8Bytes( wsl.getFlashPolicy( this ) ) ) ); close( CloseFrame.FLASHPOLICY, "" ); } catch ( InvalidDataException e ) { close( CloseFrame.ABNORMAL_CLOSE, "remote peer closed connection before flashpolicy could be transmitted", true ); } return false; } } HandshakeState handshakestate = null; try { if( role == Role.SERVER ) { if( draft == null ) { for( Draft d : knownDrafts ) { d = d.copyInstance(); try { d.setParseMode( role ); socketBuffer.reset(); Handshakedata tmphandshake = d.translateHandshake( socketBuffer ); if( tmphandshake instanceof ClientHandshake == false ) { flushAndClose( CloseFrame.PROTOCOL_ERROR, "wrong http function", false ); return false; } ClientHandshake handshake = (ClientHandshake) tmphandshake; handshakestate = d.acceptHandshakeAsServer( handshake ); if( handshakestate == HandshakeState.MATCHED ) { resourceDescriptor = handshake.getResourceDescriptor(); ServerHandshakeBuilder response; try { response = wsl.onWebsocketHandshakeReceivedAsServer( this, d, handshake ); } catch ( InvalidDataException e ) { flushAndClose( e.getCloseCode(), e.getMessage(), false ); return false; } catch ( RuntimeException e ) { wsl.onWebsocketError( this, e ); flushAndClose( CloseFrame.NEVER_CONNECTED, e.getMessage(), false ); return false; } write( d.createHandshake( d.postProcessHandshakeResponseAsServer( handshake, response ), role ) ); draft = d; open( handshake ); return true; } } catch ( InvalidHandshakeException e ) { // go on with an other draft } } if( draft == null ) { close( CloseFrame.PROTOCOL_ERROR, "no draft matches" ); } return false; } else { // special case for multiple step handshakes Handshakedata tmphandshake = draft.translateHandshake( socketBuffer ); if( tmphandshake instanceof ClientHandshake == false ) { flushAndClose( CloseFrame.PROTOCOL_ERROR, "wrong http function", false ); return false; } ClientHandshake handshake = (ClientHandshake) tmphandshake; handshakestate = draft.acceptHandshakeAsServer( handshake ); if( handshakestate == HandshakeState.MATCHED ) { open( handshake ); return true; } else { close( CloseFrame.PROTOCOL_ERROR, "the handshake did finaly not match" ); } return false; } } else if( role == Role.CLIENT ) { draft.setParseMode( role ); Handshakedata tmphandshake = draft.translateHandshake( socketBuffer ); if( tmphandshake instanceof ServerHandshake == false ) { flushAndClose( CloseFrame.PROTOCOL_ERROR, "wrong http function", false ); return false; } ServerHandshake handshake = (ServerHandshake) tmphandshake; handshakestate = draft.acceptHandshakeAsClient( handshakerequest, handshake ); if( handshakestate == HandshakeState.MATCHED ) { try { wsl.onWebsocketHandshakeReceivedAsClient( this, handshakerequest, handshake ); } catch ( InvalidDataException e ) { flushAndClose( e.getCloseCode(), e.getMessage(), false ); return false; } catch ( RuntimeException e ) { wsl.onWebsocketError( this, e ); flushAndClose( CloseFrame.NEVER_CONNECTED, e.getMessage(), false ); return false; } open( handshake ); return true; } else { close( CloseFrame.PROTOCOL_ERROR, "draft " + draft + " refuses handshake" ); } } } catch ( InvalidHandshakeException e ) { close( e ); } } catch ( IncompleteHandshakeException e ) { if( tmpHandshakeBytes.capacity() == 0 ) { socketBuffer.reset(); int newsize = e.getPreferedSize(); if( newsize == 0 ) { newsize = socketBuffer.capacity() + 16; } else { assert ( e.getPreferedSize() >= socketBuffer.remaining() ); } tmpHandshakeBytes = ByteBuffer.allocate( newsize ); tmpHandshakeBytes.put( socketBufferNew ); // tmpHandshakeBytes.flip(); } else { tmpHandshakeBytes.position( tmpHandshakeBytes.limit() ); tmpHandshakeBytes.limit( tmpHandshakeBytes.capacity() ); } } return false; } private void decodeFrames( ByteBuffer socketBuffer ) { List<Framedata> frames; try { frames = draft.translateFrame( socketBuffer ); for( Framedata f : frames ) { if( DEBUG ) System.out.println( "matched frame: " + f ); Opcode curop = f.getOpcode(); boolean fin = f.isFin(); if( curop == Opcode.CLOSING ) { int code = CloseFrame.NOCODE; String reason = ""; if( f instanceof CloseFrame ) { CloseFrame cf = (CloseFrame) f; code = cf.getCloseCode(); reason = cf.getMessage(); } if( readystate == READYSTATE.CLOSING ) { // complete the close handshake by disconnecting closeConnection( code, reason, true ); } else { // echo close handshake if( draft.getCloseHandshakeType() == CloseHandshakeType.TWOWAY ) close( code, reason, true ); else flushAndClose( code, reason, false ); } continue; } else if( curop == Opcode.PING ) { wsl.onWebsocketPing( this, f ); continue; } else if( curop == Opcode.PONG ) { wsl.onWebsocketPong( this, f ); continue; } else if( !fin || curop == Opcode.CONTINUOUS ) { if( curop != Opcode.CONTINUOUS ) { if( current_continuous_frame_opcode != null ) throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "Previous continuous frame sequence not completed." ); current_continuous_frame_opcode = curop; } else if( fin ) { if( current_continuous_frame_opcode == null ) throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "Continuous frame sequence was not started." ); current_continuous_frame_opcode = null; } else if( current_continuous_frame_opcode == null ) { throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "Continuous frame sequence was not started." ); } try { wsl.onWebsocketMessageFragment( this, f ); } catch ( RuntimeException e ) { wsl.onWebsocketError( this, e ); } } else if( current_continuous_frame_opcode != null ) { throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "Continuous frame sequence not completed." ); } else if( curop == Opcode.TEXT ) { try { wsl.onWebsocketMessage( this, Charsetfunctions.stringUtf8( f.getPayloadData() ) ); } catch ( RuntimeException e ) { wsl.onWebsocketError( this, e ); } } else if( curop == Opcode.BINARY ) { try { wsl.onWebsocketMessage( this, f.getPayloadData() ); } catch ( RuntimeException e ) { wsl.onWebsocketError( this, e ); } } else { throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "non control or continious frame expected" ); } } } catch ( InvalidDataException e1 ) { wsl.onWebsocketError( this, e1 ); close( e1 ); return; } } private void close( int code, String message, boolean remote ) { if( readystate != READYSTATE.CLOSING && readystate != READYSTATE.CLOSED ) { if( readystate == READYSTATE.OPEN ) { if( code == CloseFrame.ABNORMAL_CLOSE ) { assert ( remote == false ); readystate = READYSTATE.CLOSING; flushAndClose( code, message, false ); return; } if( draft.getCloseHandshakeType() != CloseHandshakeType.NONE ) { try { if( !remote ) { try { wsl.onWebsocketCloseInitiated( this, code, message ); } catch ( RuntimeException e ) { wsl.onWebsocketError( this, e ); } } sendFrame( new CloseFrameBuilder( code, message ) ); } catch ( InvalidDataException e ) { wsl.onWebsocketError( this, e ); flushAndClose( CloseFrame.ABNORMAL_CLOSE, "generated frame is invalid", false ); } } flushAndClose( code, message, remote ); } else if( code == CloseFrame.FLASHPOLICY ) { assert ( remote ); flushAndClose( CloseFrame.FLASHPOLICY, message, true ); } else { flushAndClose( CloseFrame.NEVER_CONNECTED, message, false ); } if( code == CloseFrame.PROTOCOL_ERROR )// this endpoint found a PROTOCOL_ERROR flushAndClose( code, message, remote ); readystate = READYSTATE.CLOSING; tmpHandshakeBytes = null; return; } } @Override public void close( int code, String message ) { close( code, message, false ); } /** * * @param remote * Indicates who "generated" <code>code</code>.<br> * <code>true</code> means that this endpoint received the <code>code</code> from the other endpoint.<br> * false means this endpoint decided to send the given code,<br> * <code>remote</code> may also be true if this endpoint started the closing handshake since the other endpoint may not simply echo the <code>code</code> but close the connection the same time this endpoint does do but with an other <code>code</code>. <br> **/ protected synchronized void closeConnection( int code, String message, boolean remote ) { if( readystate == READYSTATE.CLOSED ) { return; } if( key != null ) { // key.attach( null ); //see issue #114 key.cancel(); } if( channel != null ) { try { channel.close(); } catch ( IOException e ) { wsl.onWebsocketError( this, e ); } } try { this.wsl.onWebsocketClose( this, code, message, remote ); } catch ( RuntimeException e ) { wsl.onWebsocketError( this, e ); } if( draft != null ) draft.reset(); handshakerequest = null; readystate = READYSTATE.CLOSED; this.outQueue.clear(); } protected void closeConnection( int code, boolean remote ) { closeConnection( code, "", remote ); } public void closeConnection() { if( closedremotely == null ) { throw new IllegalStateException( "this method must be used in conjuction with flushAndClose" ); } closeConnection( closecode, closemessage, closedremotely ); } public void closeConnection( int code, String message ) { closeConnection( code, message, false ); } protected synchronized void flushAndClose( int code, String message, boolean remote ) { if( flushandclosestate ) { return; } closecode = code; closemessage = message; closedremotely = remote; flushandclosestate = true; wsl.onWriteDemand( this ); // ensures that all outgoing frames are flushed before closing the connection try { wsl.onWebsocketClosing( this, code, message, remote ); } catch ( RuntimeException e ) { wsl.onWebsocketError( this, e ); } if( draft != null ) draft.reset(); handshakerequest = null; } public void eot() { if( getReadyState() == READYSTATE.NOT_YET_CONNECTED ) { closeConnection( CloseFrame.NEVER_CONNECTED, true ); } else if( flushandclosestate ) { closeConnection( closecode, closemessage, closedremotely ); } else if( draft.getCloseHandshakeType() == CloseHandshakeType.NONE ) { closeConnection( CloseFrame.NORMAL, true ); } else if( draft.getCloseHandshakeType() == CloseHandshakeType.ONEWAY ) { if( role == Role.SERVER ) closeConnection( CloseFrame.ABNORMAL_CLOSE, true ); else closeConnection( CloseFrame.NORMAL, true ); } else { closeConnection( CloseFrame.ABNORMAL_CLOSE, true ); } } @Override public void close( int code ) { close( code, "", false ); } public void close( InvalidDataException e ) { close( e.getCloseCode(), e.getMessage(), false ); } /** * Send Text data to the other end. * * @throws IllegalArgumentException * @throws NotYetConnectedException */ @Override public void send( String text ) throws WebsocketNotConnectedException { if( text == null ) throw new IllegalArgumentException( "Cannot send 'null' data to a WebSocketImpl." ); send( draft.createFrames( text, role == Role.CLIENT ) ); } /** * Send Binary data (plain bytes) to the other end. * * @throws IllegalArgumentException * @throws NotYetConnectedException */ @Override public void send( ByteBuffer bytes ) throws IllegalArgumentException , WebsocketNotConnectedException { if( bytes == null ) throw new IllegalArgumentException( "Cannot send 'null' data to a WebSocketImpl." ); send( draft.createFrames( bytes, role == Role.CLIENT ) ); } @Override public void send( byte[] bytes ) throws IllegalArgumentException , WebsocketNotConnectedException { send( ByteBuffer.wrap( bytes ) ); } private void send( Collection<Framedata> frames ) { if( !isOpen() ) throw new WebsocketNotConnectedException(); for( Framedata f : frames ) { sendFrame( f ); } } @Override public void sendFragmentedFrame( Opcode op, ByteBuffer buffer, boolean fin ) { send( draft.continuousFrame( op, buffer, fin ) ); } @Override public void sendFrame( Framedata framedata ) { if( DEBUG ) System.out.println( "send frame: " + framedata ); write( draft.createBinaryFrame( framedata ) ); } @Override public boolean hasBufferedData() { return !this.outQueue.isEmpty(); } private HandshakeState isFlashEdgeCase( ByteBuffer request ) throws IncompleteHandshakeException { request.mark(); if( request.limit() > Draft.FLASH_POLICY_REQUEST.length ) { return HandshakeState.NOT_MATCHED; } else if( request.limit() < Draft.FLASH_POLICY_REQUEST.length ) { throw new IncompleteHandshakeException( Draft.FLASH_POLICY_REQUEST.length ); } else { for( int flash_policy_index = 0 ; request.hasRemaining() ; flash_policy_index++ ) { if( Draft.FLASH_POLICY_REQUEST[ flash_policy_index ] != request.get() ) { request.reset(); return HandshakeState.NOT_MATCHED; } } return HandshakeState.MATCHED; } } public void startHandshake( ClientHandshakeBuilder handshakedata ) throws InvalidHandshakeException { assert ( readystate != READYSTATE.CONNECTING ) : "shall only be called once"; // Store the Handshake Request we are about to send this.handshakerequest = draft.postProcessHandshakeRequestAsClient( handshakedata ); resourceDescriptor = handshakedata.getResourceDescriptor(); assert( resourceDescriptor != null ); // Notify Listener try { wsl.onWebsocketHandshakeSentAsClient( this, this.handshakerequest ); } catch ( InvalidDataException e ) { // Stop if the client code throws an exception throw new InvalidHandshakeException( "Handshake data rejected by client." ); } catch ( RuntimeException e ) { wsl.onWebsocketError( this, e ); throw new InvalidHandshakeException( "rejected because of" + e ); } // Send write( draft.createHandshake( this.handshakerequest, role ) ); } private void write( ByteBuffer buf ) { if( DEBUG ) System.out.println( "write(" + buf.remaining() + "): {" + ( buf.remaining() > 1000 ? "too big to display" : new String( buf.array() ) ) + "}" ); outQueue.add( buf ); /*try { outQueue.put( buf ); } catch ( InterruptedException e ) { write( buf ); Thread.currentThread().interrupt(); // keep the interrupted status e.printStackTrace(); }*/ wsl.onWriteDemand( this ); } private void write( List<ByteBuffer> bufs ) { for( ByteBuffer b : bufs ) { write( b ); } } private void open( Handshakedata d ) { if( DEBUG ) System.out.println( "open using draft: " + draft.getClass().getSimpleName() ); readystate = READYSTATE.OPEN; try { wsl.onWebsocketOpen( this, d ); } catch ( RuntimeException e ) { wsl.onWebsocketError( this, e ); } } @Override public boolean isConnecting() { assert ( flushandclosestate ? readystate == READYSTATE.CONNECTING : true ); return readystate == READYSTATE.CONNECTING; // ifflushandclosestate } @Override public boolean isOpen() { assert ( readystate == READYSTATE.OPEN ? !flushandclosestate : true ); return readystate == READYSTATE.OPEN; } @Override public boolean isClosing() { return readystate == READYSTATE.CLOSING; } @Override public boolean isFlushAndClose() { return flushandclosestate; } @Override public boolean isClosed() { return readystate == READYSTATE.CLOSED; } @Override public READYSTATE getReadyState() { return readystate; } @Override public int hashCode() { return super.hashCode(); } @Override public String toString() { return super.toString(); // its nice to be able to set breakpoints here } @Override public InetSocketAddress getRemoteSocketAddress() { return wsl.getRemoteSocketAddress( this ); } @Override public InetSocketAddress getLocalSocketAddress() { return wsl.getLocalSocketAddress( this ); } @Override public Draft getDraft() { return draft; } @Override public void close() { close( CloseFrame.NORMAL ); } @Override public String getResourceDescriptor() { return resourceDescriptor; } }
loadtestgo/pizzascript
websocket/src/main/java/org/java_websocket/WebSocketImpl.java
Java
bsd-3-clause
23,812
/* * org.openmicroscopy.shoola.util.concur.tasks.TestCompositeTaskDone2 * *------------------------------------------------------------------------------ * Copyright (C) 2006 University of Dundee. All rights reserved. * * * 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 2 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, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * *------------------------------------------------------------------------------ */ package org.openmicroscopy.shoola.util.concur.tasks; //Java imports //Third-party libraries //Application-internal dependencies /** * Verifies the behavior of a <code>CompositeTask</code> object when in the * <i>Done</i> state. * * @author Jean-Marie Burel &nbsp;&nbsp;&nbsp;&nbsp; * <a href="mailto:[email protected]">[email protected]</a> * @author <br>Andrea Falconi &nbsp;&nbsp;&nbsp;&nbsp; * <a href="mailto:[email protected]"> * [email protected]</a> * @version 2.2 * <small> * (<b>Internal version:</b> $Revision$ $Date$) * </small> * @since OME2.2 */ public class TestCompositeTaskDone2 extends TestCompositeTaskDone { //Only change wrt to superclass is fixture; target will be in DONE state //but will have children. protected void setUp() { super.setUp(); target = new CompositeTask(); //In ADDING state. target.add(new NullMultiStepTask()); //Its isDone always returns TRUE. target.add(new NullMultiStepTask()); target.isDone(); //Transitions to DONE b/c all children are done. } }
simleo/openmicroscopy
components/insight/TEST/org/openmicroscopy/shoola/util/concur/tasks/TestCompositeTaskDone2.java
Java
gpl-2.0
2,160
/* This code is part of Freenet. It is distributed under the GNU General * Public License, version 2 (or at your option any later version). See * http://www.gnu.org/ for further details of the GPL. */ package freenet.config; /** * Thrown when the node must be restarted for a config setting to be applied. * The thrower must ensure that the value reaches the config file, even though * it cannot be immediately used. */ @SuppressWarnings("serial") public class NodeNeedRestartException extends ConfigException { public NodeNeedRestartException(String msg) { super(msg); } }
uprasad/fred
src/freenet/config/NodeNeedRestartException.java
Java
gpl-2.0
586
// Copyright 2016 The Bazel Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // 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.testing.junit.runner; import com.google.testing.junit.runner.util.GoogleTestSecurityManager; import java.util.ArrayList; import java.util.List; import org.junit.runner.JUnitCore; import org.junit.runner.Request; import org.junit.runner.Result; /** * A straightforward JUnit test runner that runs the test in the specified class using * {@link JUnitCore}. */ public class TestRunner { private static final String PACKAGE = TestRunner.class.getPackage().getName(); private TestRunner() {} public static void main(String[] args) throws ClassNotFoundException { if (args.length == 0) { throw new IllegalArgumentException( "Must specify at least one argument (source files of the tests to run)!"); } JUnitCore junitCore = new JUnitCore(); junitCore.addListener(new TestListener()); SecurityManager previousSecurityManager = setGoogleTestSecurityManager(); Request request = createRequest(args); Result result = junitCore.run(request); restorePreviousSecurityManager(previousSecurityManager); System.exit(result.wasSuccessful() ? 0 : 1); } private static Request createRequest(String[] filepaths) throws ClassNotFoundException { List<Class<?>> classes = new ArrayList<>(filepaths.length); for (String path : filepaths) { classes.add(getClass(path)); } return Request.classes(classes.toArray(new Class<?>[0])); } private static Class<?> getClass(String filepath) throws ClassNotFoundException { String className = filepath.replace('/', '.'); if (filepath.endsWith(".java")) { className = className.substring(0, className.length() - 5); } return Class.forName(PACKAGE + "." + className); } // Sets a new GoogleTestSecurityManager as security manager and returns the previous one. private static SecurityManager setGoogleTestSecurityManager() { SecurityManager previousSecurityManager = System.getSecurityManager(); GoogleTestSecurityManager newSecurityManager = new GoogleTestSecurityManager(); System.setSecurityManager(newSecurityManager); return previousSecurityManager; } private static void restorePreviousSecurityManager(SecurityManager previousSecurityManager) { GoogleTestSecurityManager.uninstallIfInstalled(); System.setSecurityManager(previousSecurityManager); } }
hermione521/bazel
src/test/junitrunner/javatests/com/google/testing/junit/runner/TestRunner.java
Java
apache-2.0
2,962
// Copyright (C) 2009 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.httpd; import com.google.gerrit.extensions.events.LifecycleListener; import com.google.inject.Provider; import com.google.inject.ProvisionException; import com.google.inject.Singleton; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; /** Provides access to the {@code ReviewDb} DataSource. */ @Singleton final class ReviewDbDataSourceProvider implements Provider<DataSource>, LifecycleListener { private DataSource ds; @Override public synchronized DataSource get() { if (ds == null) { ds = open(); } return ds; } @Override public void start() { } @Override public synchronized void stop() { if (ds != null) { closeDataSource(ds); } } private DataSource open() { final String dsName = "java:comp/env/jdbc/ReviewDb"; try { return (DataSource) new InitialContext().lookup(dsName); } catch (NamingException namingErr) { throw new ProvisionException("No DataSource " + dsName, namingErr); } } private void closeDataSource(final DataSource ds) { try { Class<?> type = Class.forName("org.apache.commons.dbcp.BasicDataSource"); if (type.isInstance(ds)) { type.getMethod("close").invoke(ds); return; } } catch (Throwable bad) { // Oh well, its not a Commons DBCP pooled connection. } try { Class<?> type = Class.forName("com.mchange.v2.c3p0.DataSources"); if (type.isInstance(ds)) { type.getMethod("destroy", DataSource.class).invoke(null, ds); } } catch (Throwable bad) { // Oh well, its not a c3p0 pooled connection. } } }
midnightradio/gerrit
gerrit-war/src/main/java/com/google/gerrit/httpd/ReviewDbDataSourceProvider.java
Java
apache-2.0
2,302
/* * 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.axis2.jaxws.description.impl; import junit.framework.TestCase; import org.apache.axis2.description.AxisService; import org.apache.axis2.jaxws.description.DescriptionFactory; import org.apache.axis2.jaxws.description.DescriptionTestUtils; import org.apache.axis2.jaxws.description.EndpointDescription; import org.apache.axis2.jaxws.description.ServiceDescription; import org.apache.axis2.jaxws.description.builder.DescriptionBuilderComposite; import org.apache.axis2.jaxws.description.builder.WebServiceClientAnnot; import javax.jws.WebService; import javax.xml.namespace.QName; import javax.xml.ws.Holder; import javax.xml.ws.WebServiceClient; import java.net.URL; /** * Test client sparse composite support in the MDQ layer at the Service creation level. */ public class ClientDBCSupportTests extends TestCase { private String namespaceURI = "http://org.apache.axis2.jaxws.description.impl.ClientDBCSupportTests"; private String svcLocalPart = "svcLocalPart"; private String portLocalPart = "portLocalPart"; /** * Test the previous way of constructing a ServiceDescription and then updating it with an * Endpoint. This is verifying that the previous APIs work as expected. */ public void testServiceAndSeiClass() { QName serviceQName = new QName(namespaceURI, svcLocalPart); ServiceDescription svcDesc = DescriptionFactory.createServiceDescription(null, serviceQName, ClientDBCSupportServiceSubclass.class); assertNotNull(svcDesc); ServiceDescriptionImpl svcDescImpl = (ServiceDescriptionImpl) svcDesc; DescriptionBuilderComposite svcDescComposite = svcDescImpl.getDescriptionBuilderComposite(); assertNotNull(svcDescComposite); Class testServiceClass = svcDescComposite.getCorrespondingClass(); assertNotNull(testServiceClass); assertEquals(ClientDBCSupportServiceSubclass.class, testServiceClass); // Now update with an SEI QName portQName = new QName(namespaceURI, portLocalPart); EndpointDescription epDesc = DescriptionFactory.updateEndpoint(svcDesc, ClientDBCSupportSEI.class, portQName, DescriptionFactory.UpdateType.GET_PORT); assertNotNull(epDesc); EndpointDescriptionImpl epDescImpl = (EndpointDescriptionImpl) epDesc; DescriptionBuilderComposite epDescComposite = epDescImpl.getDescriptionBuilderComposite(); Class seiClass = epDescComposite.getCorrespondingClass(); assertEquals(ClientDBCSupportSEI.class, seiClass); // Make sure we didn't overwrite the class in the ServiceDesc composite assertEquals(ClientDBCSupportServiceSubclass.class, svcDescComposite.getCorrespondingClass()); } /** * Create a ServiceDescription with a composite. Nothing in the composite is overriden; validate * the values from the annotions in the Service class. */ public void testClientServiceClassComposite() { QName serviceQName = new QName(namespaceURI, svcLocalPart); DescriptionBuilderComposite composite = new DescriptionBuilderComposite(); Object compositeKey = "CompositeKey"; ServiceDescription svcDesc = new ServiceDescriptionImpl(null, serviceQName, ClientDBCSupportServiceSubclass.class, composite, compositeKey); assertNotNull(svcDesc); ServiceDescriptionImpl svcDescImpl = (ServiceDescriptionImpl) svcDesc; DescriptionBuilderComposite svcDescComposite = svcDescImpl.getDescriptionBuilderComposite(); assertNotNull(svcDescComposite); assertNotSame(composite, svcDescComposite); assertSame(composite, svcDescComposite.getSparseComposite(compositeKey)); WebServiceClient wsClient = svcDescComposite.getWebServiceClientAnnot(); assertNotNull(wsClient); assertEquals("originalWsdlLocation", wsClient.wsdlLocation()); assertEquals("originalTNS", wsClient.targetNamespace()); // We're testing the composite, not the metadata layer, so none of the defaulting logic // is exercised. assertEquals("", wsClient.name()); } /** * Create a ServiceDescription using a sparse composite that overrides the wsdlLocation on the * WebServiceClient annotation. Validate the override only affects the wsdlLocation and not * the other annotations members. */ public void testServiceClientWSDLLocationOverride() { QName serviceQName = new QName(namespaceURI, svcLocalPart); // Create a composite with a WebServiceClient override of the WSDL location. DescriptionBuilderComposite composite = new DescriptionBuilderComposite(); String overridenWsdlLocation = DescriptionTestUtils.getWSDLLocation("ClientEndpointMetadata.wsdl"); WebServiceClientAnnot wsClientAnno = WebServiceClientAnnot.createWebServiceClientAnnotImpl(null, null, overridenWsdlLocation); composite.setWebServiceClientAnnot(wsClientAnno); Object compositeKey = "CompositeKey"; ServiceDescription svcDesc = new ServiceDescriptionImpl(null, serviceQName, ClientDBCSupportServiceSubclass.class, composite, compositeKey); assertNotNull(svcDesc); ServiceDescriptionImpl svcDescImpl = (ServiceDescriptionImpl) svcDesc; DescriptionBuilderComposite svcDescComposite = svcDescImpl.getDescriptionBuilderComposite(); assertNotNull(svcDescComposite); assertNotSame(composite, svcDescComposite); assertSame(composite, svcDescComposite.getSparseComposite(compositeKey)); // The client annot we set as a sparse composite should be the same. assertSame(wsClientAnno, svcDescComposite.getSparseComposite(compositeKey).getWebServiceClientAnnot()); // The WebServiceClient annot on the service desc should represent the wsdl override from the // sparse composite WebServiceClient wsClient = svcDescComposite.getWebServiceClientAnnot(compositeKey); assertEquals(overridenWsdlLocation, wsClient.wsdlLocation()); // Make sure the non-overridden values still come from the service class annotation assertEquals("originalTNS", wsClient.targetNamespace()); assertEquals("", wsClient.name()); } /** * Test the ability to set a prefered port on a service description via a sparse composite. */ public void testPreferredPort() { QName serviceQName = new QName(namespaceURI, svcLocalPart); DescriptionBuilderComposite composite = new DescriptionBuilderComposite(); QName preferredPort = new QName("preferredTNS", "preferredLP"); composite.setPreferredPort(preferredPort); Object compositeKey = "CompositeKey"; ServiceDescription svcDesc = DescriptionFactory.createServiceDescription(null, serviceQName, ClientDBCSupportServiceSubclass.class, composite, compositeKey); DescriptionBuilderComposite svcDescComposite = DescriptionTestUtils.getServiceDescriptionComposite(svcDesc); assertNotNull(svcDescComposite); assertNull(svcDescComposite.getPreferredPort()); DescriptionBuilderComposite svcDescSparseComposite = svcDescComposite.getSparseComposite(compositeKey); assertNotNull(svcDescSparseComposite); assertSame(preferredPort, svcDescSparseComposite.getPreferredPort()); assertSame(preferredPort, svcDescComposite.getPreferredPort(compositeKey)); } /** * Test the ability to set MTOM enablement on a service description via a sparse composite. */ public void testMTOMEnablement() { QName serviceQName = new QName(namespaceURI, svcLocalPart); DescriptionBuilderComposite composite = new DescriptionBuilderComposite(); composite.setIsMTOMEnabled(true); Object compositeKey = "CompositeKey"; ServiceDescription svcDesc = DescriptionFactory.createServiceDescription(null, serviceQName, ClientDBCSupportServiceSubclass.class, composite, compositeKey); DescriptionBuilderComposite svcDescComposite = DescriptionTestUtils.getServiceDescriptionComposite(svcDesc); assertNotNull(svcDescComposite); assertFalse(svcDescComposite.isMTOMEnabled()); DescriptionBuilderComposite svcDescSparseComposite = svcDescComposite.getSparseComposite(compositeKey); assertNotNull(svcDescSparseComposite); assertTrue(svcDescSparseComposite.isMTOMEnabled()); assertTrue(svcDescComposite.isMTOMEnabled(compositeKey)); } } @WebServiceClient(targetNamespace="originalTNS", wsdlLocation="originalWsdlLocation") class ClientDBCSupportServiceSubclass extends javax.xml.ws.Service { protected ClientDBCSupportServiceSubclass(URL wsdlDocumentLocation, QName serviceName) { super(wsdlDocumentLocation, serviceName); } } @WebService interface ClientDBCSupportSEI { public String echo (String string); } @WebService(serviceName = "EchoService", endpointInterface="org.apache.ws.axis2.tests.EchoPort") class ClientDBCSupportEchoServiceImplWithSEI { public void echo(Holder<String> text) { text.value = "Echo " + text.value; } }
manuranga/wso2-axis2
modules/metadata/test/org/apache/axis2/jaxws/description/impl/ClientDBCSupportTests.java
Java
apache-2.0
10,657
/* * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* @test * @bug 4799427 * @summary Https can not retry request * @run main/othervm RetryHttps * * SunJSSE does not support dynamic system properties, no way to re-use * system properties in samevm/agentvm mode. * @author Yingxian Wang */ import java.net.*; import java.util.*; import java.io.*; import javax.net.ssl.*; public class RetryHttps { static Map cookies; ServerSocket ss; /* * ============================================================= * Set the various variables needed for the tests, then * specify what tests to run on each side. */ /* * Should we run the client or server in a separate thread? * Both sides can throw exceptions, but do you have a preference * as to which side should be the main thread. */ static boolean separateServerThread = true; /* * Where do we find the keystores? */ static String pathToStores = "../../../../../../etc"; static String keyStoreFile = "keystore"; static String trustStoreFile = "truststore"; static String passwd = "passphrase"; /* * Is the server ready to serve? */ volatile static boolean serverReady = false; /* * Turn on SSL debugging? */ static boolean debug = false; private SSLServerSocket sslServerSocket = null; /* * Define the server side of the test. * * If the server prematurely exits, serverReady will be set to true * to avoid infinite hangs. */ void doServerSide() throws Exception { SSLServerSocketFactory sslssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); sslServerSocket = (SSLServerSocket) sslssf.createServerSocket(serverPort); serverPort = sslServerSocket.getLocalPort(); /* * Signal Client, we're ready for his connect. */ serverReady = true; SSLSocket sslSocket = null; try { for (int i = 0; i < 2; i++) { sslSocket = (SSLSocket) sslServerSocket.accept(); // read request InputStream is = sslSocket.getInputStream (); BufferedReader r = new BufferedReader(new InputStreamReader(is)); boolean flag = false; String x; while ((x=r.readLine()) != null) { if (x.length() ==0) { break; } } PrintStream out = new PrintStream( new BufferedOutputStream( sslSocket.getOutputStream() )); /* send the header */ out.print("HTTP/1.1 200 OK\r\n"); out.print("Content-Type: text/html; charset=iso-8859-1\r\n"); out.print("Content-Length: "+10+"\r\n"); out.print("\r\n"); out.print("Testing"+i+"\r\n"); out.flush(); sslSocket.close(); } sslServerSocket.close(); } catch (Exception e) { e.printStackTrace(); } } /* * Define the client side of the test. * * If the server prematurely exits, serverReady will be set to true * to avoid infinite hangs. */ void doClientSide() throws Exception { HostnameVerifier reservedHV = HttpsURLConnection.getDefaultHostnameVerifier(); try { /* * Wait for server to get started. */ while (!serverReady) { Thread.sleep(50); } try { HttpsURLConnection http = null; /* establish http connection to server */ URL url = new URL("https://localhost:" + serverPort+"/file1"); System.out.println("url is "+url.toString()); HttpsURLConnection.setDefaultHostnameVerifier( new NameVerifier()); http = (HttpsURLConnection)url.openConnection(); int respCode = http.getResponseCode(); int cl = http.getContentLength(); InputStream is = http.getInputStream (); int count = 0; while (is.read() != -1 && count++ < cl); System.out.println("respCode1 = "+respCode); Thread.sleep(2000); url = new URL("https://localhost:" + serverPort+"/file2"); http = (HttpsURLConnection)url.openConnection(); respCode = http.getResponseCode(); System.out.println("respCode2 = "+respCode); } catch (IOException ioex) { if (sslServerSocket != null) sslServerSocket.close(); throw ioex; } } finally { HttpsURLConnection.setDefaultHostnameVerifier(reservedHV); } } static class NameVerifier implements HostnameVerifier { public boolean verify(String hostname, SSLSession session) { return true; } } /* * ============================================================= * The remainder is just support stuff */ // use any free port by default volatile int serverPort = 0; volatile Exception serverException = null; volatile Exception clientException = null; public static void main(String args[]) throws Exception { String keyFilename = System.getProperty("test.src", "./") + "/" + pathToStores + "/" + keyStoreFile; String trustFilename = System.getProperty("test.src", "./") + "/" + pathToStores + "/" + trustStoreFile; System.setProperty("javax.net.ssl.keyStore", keyFilename); System.setProperty("javax.net.ssl.keyStorePassword", passwd); System.setProperty("javax.net.ssl.trustStore", trustFilename); System.setProperty("javax.net.ssl.trustStorePassword", passwd); if (debug) System.setProperty("javax.net.debug", "all"); /* * Start the tests. */ new RetryHttps(); } Thread clientThread = null; Thread serverThread = null; /* * Primary constructor, used to drive remainder of the test. * * Fork off the other side, then do your work. */ RetryHttps() throws Exception { if (separateServerThread) { startServer(true); startClient(false); } else { startClient(true); startServer(false); } /* * Wait for other side to close down. */ if (separateServerThread) { serverThread.join(); } else { clientThread.join(); } /* * When we get here, the test is pretty much over. * * If the main thread excepted, that propagates back * immediately. If the other thread threw an exception, we * should report back. */ if (serverException != null) throw serverException; if (clientException != null) throw clientException; } void startServer(boolean newThread) throws Exception { if (newThread) { serverThread = new Thread() { public void run() { try { doServerSide(); } catch (Exception e) { /* * Our server thread just died. * * Release the client, if not active already... */ System.err.println("Server died..."); serverReady = true; serverException = e; } } }; serverThread.start(); } else { doServerSide(); } } void startClient(boolean newThread) throws Exception { if (newThread) { clientThread = new Thread() { public void run() { try { doClientSide(); } catch (Exception e) { /* * Our client thread just died. */ System.err.println("Client died..."); clientException = e; } } }; clientThread.start(); } else { doClientSide(); } } }
rokn/Count_Words_2015
testing/openjdk2/jdk/test/sun/security/ssl/sun/net/www/protocol/https/HttpsURLConnection/RetryHttps.java
Java
mit
9,678
@Override public void onRequestPermissionsResult (int permissionID, String permissions[], int[] grantResults) { boolean permissionsGranted = (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED); if (! permissionsGranted) Log.d ("JUCE", "onRequestPermissionsResult: runtime permission was DENIED: " + getAndroidPermissionName (permissionID)); Long ptrToCallback = permissionCallbackPtrMap.get (permissionID); permissionCallbackPtrMap.remove (permissionID); androidRuntimePermissionsCallback (permissionsGranted, ptrToCallback); }
reuk/waveguide
wayverb/JuceLibraryCode/modules/juce_core/native/java/AndroidRuntimePermissions.java
Java
gpl-2.0
640
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.search_engines; import org.chromium.base.CalledByNative; import org.chromium.base.ObserverList; import org.chromium.base.ThreadUtils; import java.util.ArrayList; import java.util.List; /** * Android wrapper of the TemplateUrlService which provides access from the Java * layer. * * Only usable from the UI thread as it's primary purpose is for supporting the Android * preferences UI. * * See components/search_engines/template_url_service.h for more details. */ public class TemplateUrlService { /** * This listener will be notified when template url service is done loading. */ public interface LoadListener { public abstract void onTemplateUrlServiceLoaded(); } /** * Represents search engine with its index. */ public static class TemplateUrl { private final int mIndex; private final String mShortName; private final String mKeyword; @CalledByNative("TemplateUrl") public static TemplateUrl create(int id, String shortName, String keyword) { return new TemplateUrl(id, shortName, keyword); } public TemplateUrl(int index, String shortName, String keyword) { mIndex = index; mShortName = shortName; mKeyword = keyword; } public int getIndex() { return mIndex; } public String getShortName() { return mShortName; } public String getKeyword() { return mKeyword; } } private static TemplateUrlService sService; public static TemplateUrlService getInstance() { ThreadUtils.assertOnUiThread(); if (sService == null) { sService = new TemplateUrlService(); } return sService; } private final long mNativeTemplateUrlServiceAndroid; private final ObserverList<LoadListener> mLoadListeners = new ObserverList<LoadListener>(); private TemplateUrlService() { // Note that this technically leaks the native object, however, TemlateUrlService // is a singleton that lives forever and there's no clean shutdown of Chrome on Android mNativeTemplateUrlServiceAndroid = nativeInit(); } public boolean isLoaded() { ThreadUtils.assertOnUiThread(); return nativeIsLoaded(mNativeTemplateUrlServiceAndroid); } public void load() { ThreadUtils.assertOnUiThread(); nativeLoad(mNativeTemplateUrlServiceAndroid); } /** * Get the collection of localized search engines. */ public List<TemplateUrl> getLocalizedSearchEngines() { ThreadUtils.assertOnUiThread(); int templateUrlCount = nativeGetTemplateUrlCount(mNativeTemplateUrlServiceAndroid); List<TemplateUrl> templateUrls = new ArrayList<TemplateUrl>(templateUrlCount); for (int i = 0; i < templateUrlCount; i++) { TemplateUrl templateUrl = nativeGetPrepopulatedTemplateUrlAt( mNativeTemplateUrlServiceAndroid, i); if (templateUrl != null) { templateUrls.add(templateUrl); } } return templateUrls; } /** * Called from native when template URL service is done loading. */ @CalledByNative private void templateUrlServiceLoaded() { ThreadUtils.assertOnUiThread(); for (LoadListener listener : mLoadListeners) { listener.onTemplateUrlServiceLoaded(); } } /** * @return The default search engine index (e.g., 0, 1, 2,...). */ public int getDefaultSearchEngineIndex() { ThreadUtils.assertOnUiThread(); return nativeGetDefaultSearchProvider(mNativeTemplateUrlServiceAndroid); } /** * @return {@link TemplateUrlService.TemplateUrl} for the default search engine. */ public TemplateUrl getDefaultSearchEngineTemplateUrl() { if (!isLoaded()) return null; int defaultSearchEngineIndex = getDefaultSearchEngineIndex(); if (defaultSearchEngineIndex == -1) return null; assert defaultSearchEngineIndex >= 0; assert defaultSearchEngineIndex < nativeGetTemplateUrlCount( mNativeTemplateUrlServiceAndroid); return nativeGetPrepopulatedTemplateUrlAt( mNativeTemplateUrlServiceAndroid, defaultSearchEngineIndex); } public void setSearchEngine(int selectedIndex) { ThreadUtils.assertOnUiThread(); nativeSetUserSelectedDefaultSearchProvider(mNativeTemplateUrlServiceAndroid, selectedIndex); } public boolean isSearchProviderManaged() { return nativeIsSearchProviderManaged(mNativeTemplateUrlServiceAndroid); } /** * @return Whether or not the default search engine has search by image support. */ public boolean isSearchByImageAvailable() { ThreadUtils.assertOnUiThread(); return nativeIsSearchByImageAvailable(mNativeTemplateUrlServiceAndroid); } /** * @return Whether the default configured search engine is for a Google property. */ public boolean isDefaultSearchEngineGoogle() { return nativeIsDefaultSearchEngineGoogle(mNativeTemplateUrlServiceAndroid); } /** * Registers a listener for the callback that indicates that the * TemplateURLService has loaded. */ public void registerLoadListener(LoadListener listener) { ThreadUtils.assertOnUiThread(); boolean added = mLoadListeners.addObserver(listener); assert added; } /** * Unregisters a listener for the callback that indicates that the * TemplateURLService has loaded. */ public void unregisterLoadListener(LoadListener listener) { ThreadUtils.assertOnUiThread(); boolean removed = mLoadListeners.removeObserver(listener); assert removed; } /** * Finds the default search engine for the default provider and returns the url query * {@link String} for {@code query}. * @param query The {@link String} that represents the text query the search url should * represent. * @return A {@link String} that contains the url of the default search engine with * {@code query} inserted as the search parameter. */ public String getUrlForSearchQuery(String query) { return nativeGetUrlForSearchQuery(mNativeTemplateUrlServiceAndroid, query); } /** * Finds the default search engine for the default provider and returns the url query * {@link String} for {@code query} with voice input source param set. * @param query The {@link String} that represents the text query the search url should * represent. * @return A {@link String} that contains the url of the default search engine with * {@code query} inserted as the search parameter and voice input source param set. */ public String getUrlForVoiceSearchQuery(String query) { return nativeGetUrlForVoiceSearchQuery(mNativeTemplateUrlServiceAndroid, query); } /** * Replaces the search terms from {@code query} in {@code url}. * @param query The {@link String} that represents the text query that should replace the * existing query in {@code url}. * @param url The {@link String} that contains the search url with another search query that * will be replaced with {@code query}. * @return A new version of {@code url} with the search term replaced with {@code query}. */ public String replaceSearchTermsInUrl(String query, String url) { return nativeReplaceSearchTermsInUrl(mNativeTemplateUrlServiceAndroid, query, url); } // TODO(donnd): Delete once the client no longer references it. /** * Finds the default search engine for the default provider and returns the url query * {@link String} for {@code query} with the contextual search version param set. * @param query The search term to use as the main query in the returned search url. * @param alternateTerm The alternate search term to use as an alternate suggestion. * @return A {@link String} that contains the url of the default search engine with * {@code query} and {@code alternateTerm} inserted as parameters and contextual * search and prefetch parameters set. */ public String getUrlForContextualSearchQuery(String query, String alternateTerm) { return nativeGetUrlForContextualSearchQuery( mNativeTemplateUrlServiceAndroid, query, alternateTerm, true); } /** * Finds the default search engine for the default provider and returns the url query * {@link String} for {@code query} with the contextual search version param set. * @param query The search term to use as the main query in the returned search url. * @param alternateTerm The alternate search term to use as an alternate suggestion. * @param shouldPrefetch Whether the returned url should include a prefetch parameter. * @return A {@link String} that contains the url of the default search engine with * {@code query} and {@code alternateTerm} inserted as parameters and contextual * search and prefetch parameters conditionally set. */ public String getUrlForContextualSearchQuery(String query, String alternateTerm, boolean shouldPrefetch) { return nativeGetUrlForContextualSearchQuery( mNativeTemplateUrlServiceAndroid, query, alternateTerm, shouldPrefetch); } private native long nativeInit(); private native void nativeLoad(long nativeTemplateUrlServiceAndroid); private native boolean nativeIsLoaded(long nativeTemplateUrlServiceAndroid); private native int nativeGetTemplateUrlCount(long nativeTemplateUrlServiceAndroid); private native TemplateUrl nativeGetPrepopulatedTemplateUrlAt( long nativeTemplateUrlServiceAndroid, int i); private native void nativeSetUserSelectedDefaultSearchProvider( long nativeTemplateUrlServiceAndroid, int selectedIndex); private native int nativeGetDefaultSearchProvider(long nativeTemplateUrlServiceAndroid); private native boolean nativeIsSearchProviderManaged(long nativeTemplateUrlServiceAndroid); private native boolean nativeIsSearchByImageAvailable(long nativeTemplateUrlServiceAndroid); private native boolean nativeIsDefaultSearchEngineGoogle(long nativeTemplateUrlServiceAndroid); private native String nativeGetUrlForSearchQuery(long nativeTemplateUrlServiceAndroid, String query); private native String nativeGetUrlForVoiceSearchQuery(long nativeTemplateUrlServiceAndroid, String query); private native String nativeReplaceSearchTermsInUrl(long nativeTemplateUrlServiceAndroid, String query, String currentUrl); private native String nativeGetUrlForContextualSearchQuery(long nativeTemplateUrlServiceAndroid, String query, String alternateTerm, boolean shouldPrefetch); }
s20121035/rk3288_android5.1_repo
external/chromium_org/chrome/android/java/src/org/chromium/chrome/browser/search_engines/TemplateUrlService.java
Java
gpl-3.0
11,364
/* * The basic Constrained Component class. * Every Constrained Component consists of several parts: * 1) A private internal representation of points/scalars, as appropriate for * the component. * 2) A collection of export variables. These are all public variables * and can be constrained. * 3) A collection of constraints on (2) * 4) A customized draw() method that makes use of values from parts * (1) and/or (2) * 5) A customized moveBy() method that requests the object's center move by * the specified amount * 6) A vector of points that are currently selected, which will be affected * by moveBy messages * 7) A vector of constraint objs that care about this CC's state. Typically, * this will entail interest in the bounding box of this CC. * * $Id: ConstrComponent.java,v 1.4 1999/12/16 02:09:59 gjb Exp $ * */ package EDU.Washington.grad.noth.cda; import java.awt.Graphics; import java.awt.Point; import java.awt.Rectangle; import java.awt.Color; import java.util.Vector; import EDU.Washington.grad.gjb.cassowary.*; public abstract class ConstrComponent { // Reference to the solver public ClSimplexSolver solver; // Set of selectable points public Vector selPoints; // Flags indicating if the CC is selected or highlighted protected boolean isSelected, isHighlighted; // Bounding box for the CC public Rectangle bbox; // The SelPoint that is on each of the 4 borders of the bbox public SelPoint topSP, bottomSP, leftSP, rightSP; // List of constraint objs. that care about the state of this one protected Vector interConstr; // Default constructor public ConstrComponent(ClSimplexSolver solver) { this.solver = solver; selPoints = new Vector(5); bbox = new Rectangle(); isHighlighted = false; isSelected = false; interConstr = new Vector(4); topSP = null; bottomSP = null; leftSP = null; rightSP = null; } // Draw method public void draw(Graphics g) { for ( int a = 0; a < selPoints.size(); a++ ) { ((SelPoint) selPoints.elementAt(a)).draw(g); } // If CC is highlighted or selected, draw bounding box if ( isSelected ) { g.setColor(CDA_G.DARK_GREEN); g.drawRect(bbox.x, bbox.y, bbox.width, bbox.height); } else if ( isHighlighted ) { g.setColor(CDA_G.DARK_BLUE); g.drawRect(bbox.x, bbox.y, bbox.width, bbox.height); g.drawRect(bbox.x+1, bbox.y+1, bbox.width-2, bbox.height-2); } } // Helper method to set up edit constraints for the component // Returns the # of edit constraints registered. public int setEditConstraints() { int nec = 0; SelPoint cp; for (int a = 0; a < selPoints.size(); a++ ) { cp = (SelPoint) selPoints.elementAt(a); if ( cp.getSelected() ) { cp.setEditConstraints(); nec += 2; } } return nec; } // Helper method to remove all edit constraints associated with the comp. public void removeEditConstraints() { SelPoint cp; for (int a = 0; a < selPoints.size(); a++ ) { cp = (SelPoint) selPoints.elementAt(a); if ( cp.getSelected() ) { cp.removeEditConstraints(); } } } // MoveBy method // Iterate over CC's constrainable parts and record the target edit constant // values into the ECL. MUST iterate over constrainable parts in the // same order as the set/removeEditConstraints methods. public void moveBy(Point delta, EditConstantList editConstantList) { SelPoint cp = null; for ( int a = 0; a < selPoints.size(); a++ ) { cp = (SelPoint) selPoints.elementAt(a); if ( cp.getSelected() ) { editConstantList.registerDelta(cp, delta); } } } // Update internal variables of the CC by querying the ClVariables, // which reflect any change made due to a resolve by the solver. // Order of iteration does not matter. // Also update the bounding box. public void updateEditConstants() { SelPoint cp = null; for ( int a = 0; a < selPoints.size(); a++ ) { cp = (SelPoint) selPoints.elementAt(a); cp.updateValue(); } updateBoundingBox(); } // Methods for picking/selecting // Select at a single (x, y) point. accum indicates if the set of selected // points should be accumulated (toggling applicable point(s) only), or // reset to just the applicable point(s). public void select(Point p, boolean accum) { SelPoint sp = null; int a; if ( accum == false ) { // Unselect anything currently selected unselect(); } for (a = 0; a < selPoints.size(); a++ ) { sp = (SelPoint) selPoints.elementAt(a); if ( sp.inside(p) ) sp.setSelected(); } updateIsSelected(); } // Clear selection on every point public void unselect() { for (int a = 0; a < selPoints.size(); a++ ) { ((SelPoint) selPoints.elementAt(a)).clearSelected(); } updateIsSelected(); } // Select inside a box. accum is as for above method. public void select(Rectangle b, boolean accum) { SelPoint sp = null; int a; if ( accum == false ) { // Unselect anything currently selected for (a = 0; a < selPoints.size(); a++ ) { ((SelPoint) selPoints.elementAt(a)).clearSelected(); } } for (a = 0; a < selPoints.size(); a++ ) { sp = (SelPoint) selPoints.elementAt(a); if ( sp.inside(b) ) sp.setSelected(); } updateIsSelected(); } // Query all points at the (x, y) point position. Modifies the vector // passed as a parameter. public void getSelPointsAt(Point p, Vector retv) { SelPoint sp = null; int a; for (a = 0; a < selPoints.size(); a++ ) { sp = (SelPoint) selPoints.elementAt(a); if ( sp.inside(p) ) retv.addElement(sp); } } // Updates the isSelected flag based on if all SelPoints are selected public void updateIsSelected() { isSelected = true; int a; SelPoint sp; for ( a = 0; a < selPoints.size(); a++ ) { sp = (SelPoint) selPoints.elementAt(a); if ( !sp.getSelected() ) { isSelected = false; return; } } } // Method for highlighting point as mouse moves public void highlight(Point p, boolean isShiftDown) { SelPoint sp = null; int a; // Un-highlight anything that is only highlighted (vs selected) for (a = 0; a < selPoints.size(); a++ ) { ((SelPoint) selPoints.elementAt(a)).isHighlighted = false; } for (a = 0; a < selPoints.size(); a++ ) { sp = (SelPoint) selPoints.elementAt(a); if ( sp.inside(p) ) sp.isHighlighted = true; } if ( bbox.contains(p) && isShiftDown ) isHighlighted = true; else isHighlighted = false; } public void highlight(Rectangle r) { SelPoint sp = null; int a; // Un-highlight anything that is only highlighted (vs selected) for (a = 0; a < selPoints.size(); a++ ) { ((SelPoint) selPoints.elementAt(a)).isHighlighted = false; } for (a = 0; a < selPoints.size(); a++ ) { sp = (SelPoint) selPoints.elementAt(a); if ( sp.inside(r) ) sp.isHighlighted = true; } } // Return the first SelPoint the given point hits, or null if none public SelPoint getSelPointAt(Point p) { int a; SelPoint sp; for (a = 0; a < selPoints.size(); a++ ) { sp = (SelPoint) selPoints.elementAt(a); if ( sp.inside(p) ) return sp; } return null; } // Method to update any within-window constraints the CC or its SelPoints // have. Called upon a DrawPanel resize. public void setBorderConstraints(int r, int b) { SelPoint sp = null; int a; for (a = 0; a < selPoints.size(); a++ ) { ((SelPoint) selPoints.elementAt(a)).setBorderConstraints(r, b); } } // Method to return a list of all selected SelPoints the component contains. public Vector getAllSelectedSelPoints() { Vector v = new Vector(2); int a; SelPoint sp; for (a = 0; a < selPoints.size(); a++ ) { sp = (SelPoint) selPoints.elementAt(a); if ( sp.getSelected() ) v.addElement(sp); } return v; } // Method to return a reference to the "end SP" of the component. The // SelPoint returned is the one that is dragged about upon a CC placement. public abstract SelPoint getEndSP(); // Method to replace all instances of the given SelPoint with another. // It is assumed that the replacement SelPoint has any necessary // constraints already established. // It is *not* safe to remove constraints associated with the point being // replaced, as it might be a reference to a shared point. Instead, // constraints associated with the replaced SelPoint are removed elsewhere, // when it is known the point is not shared. // If ownership of the point needs to be changed, it will be handled // elsewhere. // The original point loses interest in this CC, and the new point // gains interest. public final void replaceSelPoint(SelPoint origsp, SelPoint newsp) { SelPoint sp; int a; /* System.out.println("CC.repSP: Before replacement, selPoints = " + selPoints); */ for (a = 0; a < selPoints.size(); a++ ) { sp = (SelPoint) selPoints.elementAt(a); if ( sp == origsp ) { // Compare pointers // Allow notification to subclass that a point has been replaced, // so it can establish any constraints on it that are subclass- // specific (IE mark new pt as midpoint of line, etc.) // When this call returns, there should be no constraints associated // with the given point left in the receiver; they should have been // replaced with equivalent constraints on the new SP notifySelPointReplacement(a, newsp); // Replace the reference in the array selPoints.setElementAt(newsp, a); // Update the interested-in lists of each point sp.removeInterestedCC(this); newsp.addInterestedCC(this); } } // Better update the bounding box of the CC updateBoundingBox(); /* System.out.println("CC.repSP: After replacement, selPoints = " + selPoints); System.out.println("CC.repSP: After, bbox = " + bbox); */ } // Helper function called when a SelPoint at a specified index is // replaced with a new one. All constraints involving the point at the // index should be removed and reestablished using newsp instead. // Should be subclassed by all classes that have any constraint // relationships between their SelPoints. protected void notifySelPointReplacement(int idx, SelPoint newsp) { System.out.println("CC.notifySPReplacement invoked"); return; } // Returns true if component has SelPoint sp, false otherwise public boolean hasSelPoint(SelPoint sp) { for ( int a = 0; a < selPoints.size(); a++ ) { if ( sp == (SelPoint) selPoints.elementAt(a) ) return true; } return false; } // Update the bounding box of the component. Also notify all concerned // constraints that this component's bbox has changed. public void updateBoundingBox() { int minx, miny, maxx, maxy, a; SelPoint sp; SelPoint oldLeftSP, oldRightSP, oldTopSP, oldBottomSP; minx = 50000; miny = 50000; maxx = -50000; maxy = -50000; oldLeftSP = leftSP; oldRightSP = rightSP; oldTopSP = topSP; oldBottomSP = bottomSP; for ( a = 0; a < selPoints.size(); a++ ) { sp = (SelPoint) selPoints.elementAt(a); if ( sp.x < minx ) { minx = sp.x; leftSP = sp; } if ( sp.y < miny ) { miny = sp.y; topSP = sp; } if ( sp.x > maxx ) { maxx = sp.x; rightSP = sp; } if ( sp.y > maxy ) { maxy = sp.y; bottomSP = sp; } } bbox.x = minx; bbox.y = miny; bbox.width = (maxx - minx); bbox.height = (maxy - miny); // Notify each constraint about bbox change, if any if ( (leftSP != oldLeftSP) || (rightSP != oldRightSP) || (topSP != oldTopSP) || (bottomSP != oldBottomSP) ) { // MORE WORK HERE Constraint c; for ( a = 0; a < interConstr.size(); a++ ) { c = (Constraint) interConstr.elementAt(a); c.notifyCCBBoxChange(this); } } } // Access functions for selection public boolean getisSelected() { return isSelected; } public void setisSelected(boolean value) { int a; SelPoint sp; isSelected = value; if ( value == true ) { // Select every SelPoint of component for ( a = 0; a < selPoints.size(); a++ ) { sp = (SelPoint) selPoints.elementAt(a); sp.isSelected = true; } } } // Access functions for interested Constraint obj list public void addInterestedConstr(Constraint c) { if ( !interConstr.contains(c) ) interConstr.addElement(c); } public Vector getInterestedConstr() { return (Vector) interConstr.clone(); } public void removeInterestedConstr(Constraint c) { /* System.out.println("CC.remInterConstr: Removing " + c + " from " + interConstr); */ if ( interConstr.contains(c) ) interConstr.removeElement(c); } // Clean up function. Should remove all CC-specific constraints. // By default, does nothing. Should be overridden by any class that // has constraints beyond those internal to SelPoints. public void cleanUp() { } public void finalize() { cleanUp(); } } /* * $Log: ConstrComponent.java,v $ * Revision 1.4 1999/12/16 02:09:59 gjb * * java/cda/Makefile.am: Put Constraint/*, Main/* files into the * distribution and build with them. * * * java/demos/*.java: Move everything into the * EDU.Washington.grad.gjb.cassowary_demos package. * * * java/cda/classes/run.html, java/demos/quaddemo.htm: Fix nl * convention, name class explicitly w/ package in front, w/o * trailing .class. * * * java/cda/**: Move everything into the * EDU.Washington.grad.noth.cda package. * * Revision 1.3 1998/06/23 02:08:37 gjb * Added import of cassowary package so that the cda doesn't need to be * in the same package as the solver. * * Revision 1.2 1998/05/09 00:30:19 gjb * Remove cr-s * * Revision 1.1 1998/05/09 00:10:55 gjb * Added * * Revision 1.17 1998/04/20 09:53:31 Michael * Removed debugging msg * * Revision 1.16 1998/04/19 04:09:49 Michael * Increased thickness of blue selection box * * Revision 1.15 1998/04/15 00:09:29 Michael * Added function to accumulate vector of SP's at a point * * Revision 1.14 1998/04/10 01:59:11 Michael * Added getEndSP method * * Revision 1.13 1998/04/08 05:44:57 Michael * Commented out printing stmts and changed interface to highlight * * Revision 1.12 1998/04/02 07:01:28 Michael * Added bounding box change notification * * Revision 1.11 1998/04/01 10:13:19 Michael * Added data and functions for interested Constraint obj back-ptrs * * Revision 1.10 1998/03/27 06:27:38 Michael * Added helper function to update entire CC selection status * * Revision 1.9 1998/03/25 02:46:39 Michael * Added bounding box functions * * Revision 1.8 1998/03/19 09:16:06 Michael * Fixed logic bug where constraints on a shared SelPoint may be removed * * Revision 1.7 1998/02/25 10:40:01 Michael * Added functions for replacing a SelPoint (used for sharing) * * Revision 1.6 1998/02/17 08:27:17 Michael * Added method to return set of all selected point * * Revision 1.5 1998/02/16 10:34:19 Michael * Added method to help with changing constraints on window resize * * Revision 1.4 1998/02/15 11:34:04 Michael * Modified internals to facilitate integration with Cassowary * * Revision 1.3 1998/02/15 07:12:42 Michael * Added highlight method and moved to access function model for selection * * Revision 1.2 1998/02/06 08:36:40 Michael * Fixed compile errors * * */
wanderwaltz/WinObjC
deps/3rdparty/cassowary-0.60/java/cda/Component/ConstrComponent.java
Java
mit
16,023
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.cloudtrail.model.transform; import static com.amazonaws.util.StringUtils.UTF8; import static com.amazonaws.util.StringUtils.COMMA_SEPARATOR; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.Writer; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.regex.Pattern; import com.amazonaws.AmazonClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.cloudtrail.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.BinaryUtils; import com.amazonaws.util.StringUtils; import com.amazonaws.util.StringInputStream; import com.amazonaws.util.json.*; /** * Create Trail Request Marshaller */ public class CreateTrailRequestMarshaller implements Marshaller<Request<CreateTrailRequest>, CreateTrailRequest> { public Request<CreateTrailRequest> marshall(CreateTrailRequest createTrailRequest) { if (createTrailRequest == null) { throw new AmazonClientException("Invalid argument passed to marshall(...)"); } Request<CreateTrailRequest> request = new DefaultRequest<CreateTrailRequest>(createTrailRequest, "AWSCloudTrail"); String target = "CloudTrail_20131101.CreateTrail"; request.addHeader("X-Amz-Target", target); request.setHttpMethod(HttpMethodName.POST); request.setResourcePath(""); try { StringWriter stringWriter = new StringWriter(); JSONWriter jsonWriter = new JSONWriter(stringWriter); jsonWriter.object(); if (createTrailRequest.getName() != null) { jsonWriter.key("Name").value(createTrailRequest.getName()); } if (createTrailRequest.getS3BucketName() != null) { jsonWriter.key("S3BucketName").value(createTrailRequest.getS3BucketName()); } if (createTrailRequest.getS3KeyPrefix() != null) { jsonWriter.key("S3KeyPrefix").value(createTrailRequest.getS3KeyPrefix()); } if (createTrailRequest.getSnsTopicName() != null) { jsonWriter.key("SnsTopicName").value(createTrailRequest.getSnsTopicName()); } if (createTrailRequest.isIncludeGlobalServiceEvents() != null) { jsonWriter.key("IncludeGlobalServiceEvents").value(createTrailRequest.isIncludeGlobalServiceEvents()); } if (createTrailRequest.getCloudWatchLogsLogGroupArn() != null) { jsonWriter.key("CloudWatchLogsLogGroupArn").value(createTrailRequest.getCloudWatchLogsLogGroupArn()); } if (createTrailRequest.getCloudWatchLogsRoleArn() != null) { jsonWriter.key("CloudWatchLogsRoleArn").value(createTrailRequest.getCloudWatchLogsRoleArn()); } jsonWriter.endObject(); String snippet = stringWriter.toString(); byte[] content = snippet.getBytes(UTF8); request.setContent(new StringInputStream(snippet)); request.addHeader("Content-Length", Integer.toString(content.length)); request.addHeader("Content-Type", "application/x-amz-json-1.1"); } catch(Throwable t) { throw new AmazonClientException("Unable to marshall request to JSON: " + t.getMessage(), t); } return request; } }
mahaliachante/aws-sdk-java
aws-java-sdk-cloudtrail/src/main/java/com/amazonaws/services/cloudtrail/model/transform/CreateTrailRequestMarshaller.java
Java
apache-2.0
4,165
/* * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.media.sound; /** * A standard director who chooses performers * by there keyfrom,keyto,velfrom,velto properties. * * @author Karl Helgason */ public class ModelStandardDirector implements ModelDirector { ModelPerformer[] performers; ModelDirectedPlayer player; boolean noteOnUsed = false; boolean noteOffUsed = false; public ModelStandardDirector(ModelPerformer[] performers, ModelDirectedPlayer player) { this.performers = performers; this.player = player; for (int i = 0; i < performers.length; i++) { ModelPerformer p = performers[i]; if (p.isReleaseTriggered()) { noteOffUsed = true; } else { noteOnUsed = true; } } } public void close() { } public void noteOff(int noteNumber, int velocity) { if (!noteOffUsed) return; for (int i = 0; i < performers.length; i++) { ModelPerformer p = performers[i]; if (p.getKeyFrom() <= noteNumber && p.getKeyTo() >= noteNumber) { if (p.getVelFrom() <= velocity && p.getVelTo() >= velocity) { if (p.isReleaseTriggered()) { player.play(i, null); } } } } } public void noteOn(int noteNumber, int velocity) { if (!noteOnUsed) return; for (int i = 0; i < performers.length; i++) { ModelPerformer p = performers[i]; if (p.getKeyFrom() <= noteNumber && p.getKeyTo() >= noteNumber) { if (p.getVelFrom() <= velocity && p.getVelTo() >= velocity) { if (!p.isReleaseTriggered()) { player.play(i, null); } } } } } }
rokn/Count_Words_2015
testing/openjdk/jdk/src/share/classes/com/sun/media/sound/ModelStandardDirector.java
Java
mit
3,085
/** * $Id$ * $URL$ * PollEntityProvider.java - polls - Aug 21, 2008 7:34:47 PM - azeckoski ************************************************************************** * Copyright (c) 2008, 2009 The Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sakaiproject.poll.tool.entityproviders; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import javax.servlet.http.HttpServletResponse; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.lang3.StringUtils; import org.sakaiproject.entitybroker.EntityReference; import org.sakaiproject.entitybroker.EntityView; import org.sakaiproject.entitybroker.entityprovider.EntityProvider; import org.sakaiproject.entitybroker.entityprovider.annotations.EntityCustomAction; import org.sakaiproject.entitybroker.entityprovider.capabilities.ActionsExecutable; import org.sakaiproject.entitybroker.entityprovider.capabilities.AutoRegisterEntityProvider; import org.sakaiproject.entitybroker.entityprovider.capabilities.CollectionResolvable; import org.sakaiproject.entitybroker.entityprovider.capabilities.Describeable; import org.sakaiproject.entitybroker.entityprovider.capabilities.Outputable; import org.sakaiproject.entitybroker.entityprovider.capabilities.RequestStorable; import org.sakaiproject.entitybroker.entityprovider.extension.Formats; import org.sakaiproject.entitybroker.entityprovider.extension.RequestStorage; import org.sakaiproject.entitybroker.entityprovider.search.Restriction; import org.sakaiproject.entitybroker.entityprovider.search.Search; import org.sakaiproject.entitybroker.exception.EntityException; import org.sakaiproject.entitybroker.util.AbstractEntityProvider; import org.sakaiproject.event.api.UsageSession; import org.sakaiproject.event.api.UsageSessionService; import org.sakaiproject.poll.logic.PollListManager; import org.sakaiproject.poll.logic.PollVoteManager; import org.sakaiproject.poll.model.Option; import org.sakaiproject.poll.model.Poll; import org.sakaiproject.poll.model.Vote; import org.sakaiproject.user.api.UserDirectoryService; import lombok.Setter; import lombok.extern.slf4j.Slf4j; /** * Handles the polls tool. * * @author Aaron Zeckoski (azeckoski @ gmail.com) * @author Denny (denny.denny @ gmail.com) */ @Slf4j public class PollsEntityProvider extends AbstractEntityProvider implements EntityProvider, AutoRegisterEntityProvider, RequestStorable, ActionsExecutable, Outputable, Describeable { @Setter private PollListManager pollListManager; @Setter private PollVoteManager pollVoteManager; @Setter private UsageSessionService usageSessionService; @Setter private UserDirectoryService userDirectoryService; @Setter private RequestStorage requestStorage = null; public static final String ENTITY_PREFIX = "polls"; @Override public String getEntityPrefix() { return ENTITY_PREFIX; } public String[] getHandledOutputFormats() { return new String[] { Formats.XML, Formats.JSON }; } public String[] getHandledInputFormats() { return new String[] { Formats.XML, Formats.JSON, Formats.HTML }; } /** * site/siteId */ @EntityCustomAction(action = "site", viewKey = EntityView.VIEW_LIST) public List<Poll> getPollsForSite(EntityView view) { // get siteId String siteId = view.getPathSegment(2); // check siteId supplied if (StringUtils.isBlank(siteId)) { throw new IllegalArgumentException( "siteId must be set in order to get the polls for a site, via the URL /polls/site/siteId"); } String[] siteIds = new String[] { siteId }; if (log.isDebugEnabled()) { log.debug("poll for site " + siteId); } String userId = developerHelperService.getCurrentUserId(); if (userId == null) { throw new EntityException( "No user is currently logged in so no polls data can be retrieved", siteId, HttpServletResponse.SC_UNAUTHORIZED); } boolean adminControl = false; String perm = PollListManager.PERMISSION_VOTE; if (adminControl) { perm = PollListManager.PERMISSION_ADD; } List<Poll> polls = pollListManager .findAllPollsForUserAndSitesAndPermission(userId, siteIds, perm); if (adminControl) { // add in options for (Poll p : polls) { List<Option> options = pollListManager.getOptionsForPoll(p .getPollId()); p.setOptions(options); } } else { // add in the indicators that this user has replied Long[] pollIds = new Long[polls.size()]; for (int i = 0; i < polls.size(); i++) { pollIds[i] = polls.get(i).getPollId(); } Map<Long, List<Vote>> voteMap = pollVoteManager.getVotesForUser( userId, pollIds); for (Poll poll : polls) { Long pollId = poll.getPollId(); List<Vote> l = voteMap.get(pollId); if (l != null) { poll.setCurrentUserVoted(true); } else { poll.setCurrentUserVoted(false); } } } return polls; } @EntityCustomAction(action = "my", viewKey = EntityView.VIEW_LIST) public List<?> getEntities(EntityReference ref, Search search) { log.info("get entities"); // get the setting which indicates if we are getting polls we can admin // or polls we can take boolean adminControl = false; Restriction adminRes = search.getRestrictionByProperty("admin"); if (adminRes != null) { adminControl = developerHelperService.convert( adminRes.getSingleValue(), boolean.class); } // get the location (if set) Restriction locRes = search .getRestrictionByProperty(CollectionResolvable.SEARCH_LOCATION_REFERENCE); // requestStorage.getStoredValueAsType(String.class, // "siteId"); String[] siteIds = null; if (locRes != null) { String siteId = developerHelperService.getLocationIdFromRef(locRes .getStringValue()); siteIds = new String[] { siteId }; } // get the user (if set) Restriction userRes = search .getRestrictionByProperty(CollectionResolvable.SEARCH_USER_REFERENCE); String userId = null; if (userRes != null) { String currentUser = developerHelperService .getCurrentUserReference(); String userReference = userRes.getStringValue(); if (userReference == null) { throw new IllegalArgumentException( "Invalid request: Cannot limit polls by user when the value is null"); } if (userReference.equals(currentUser) || developerHelperService.isUserAdmin(currentUser)) { userId = developerHelperService.getUserIdFromRef(userReference); // requestStorage.getStoredValueAsType(String.class, // "userId"); } else { throw new SecurityException( "Only the admin can get polls for other users, you requested polls for: " + userReference); } } else { userId = developerHelperService.getCurrentUserId(); if (userId == null) { throw new EntityException( "No user is currently logged in so no polls data can be retrieved", ref.getId(), HttpServletResponse.SC_UNAUTHORIZED); } } String perm = PollListManager.PERMISSION_VOTE; if (adminControl) { perm = PollListManager.PERMISSION_ADD; } List<Poll> polls = pollListManager .findAllPollsForUserAndSitesAndPermission(userId, siteIds, perm); if (adminControl) { // add in options for (Poll p : polls) { List<Option> options = pollListManager.getOptionsForPoll(p .getPollId()); p.setOptions(options); } } else { // add in the indicators that this user has replied Long[] pollIds = new Long[polls.size()]; for (int i = 0; i < polls.size(); i++) { pollIds[i] = polls.get(i).getPollId(); } Map<Long, List<Vote>> voteMap = pollVoteManager.getVotesForUser( userId, pollIds); for (Poll poll : polls) { Long pollId = poll.getPollId(); List<Vote> l = voteMap.get(pollId); if (l != null) { poll.setCurrentUserVoted(true); } else { poll.setCurrentUserVoted(false); } } } return polls; } /** * @param id * @return */ private Poll getPollById(String id) { Long pollId; try { pollId = Long.valueOf(id); } catch (NumberFormatException e) { throw new IllegalArgumentException("Invalid poll id (" + id + "), the id must be a number"); } Poll poll = pollListManager.getPollById(pollId, false); return poll; } @EntityCustomAction(action = "poll-view", viewKey = EntityView.VIEW_SHOW) public Poll getPollEntity(EntityView view, EntityReference ref) { String id = ref.getId(); log.debug(id); if (StringUtils.isBlank(id)) { log.warn("Poll id is not exist. Returning an empty poll object."); return new Poll(); } Poll poll = getPollById(id); if (poll == null) { throw new IllegalArgumentException( "No poll found for the given reference: " + id); } Long pollId = poll.getPollId(); String currentUserId = developerHelperService.getCurrentUserId(); boolean allowedManage = false; if (!developerHelperService.isEntityRequestInternal(id + "")) { if (!pollListManager.isPollPublic(poll)) { // this is not a public poll? (ie .anon role has poll.vote) String userReference = developerHelperService .getCurrentUserReference(); if (userReference == null) { throw new EntityException( "User must be logged in in order to access poll data", id, HttpServletResponse.SC_UNAUTHORIZED); } allowedManage = developerHelperService .isUserAllowedInEntityReference(userReference, PollListManager.PERMISSION_ADD, "/site/" + poll.getSiteId()); boolean allowedVote = developerHelperService .isUserAllowedInEntityReference(userReference, PollListManager.PERMISSION_VOTE, "/site/" + poll.getSiteId()); if (!allowedManage && !allowedVote) { throw new SecurityException("User (" + userReference + ") not allowed to access poll data: " + id); } } } log.debug("requestStorage" , requestStorage); Boolean includeVotes = requestStorage.getStoredValueAsType( Boolean.class, "includeVotes"); if (includeVotes == null) { includeVotes = false; } if (includeVotes) { List<Vote> votes = pollVoteManager.getAllVotesForPoll(poll); poll.setVotes(votes); } Boolean includeOptions = requestStorage.getStoredValueAsType( Boolean.class, "includeOptions"); if (includeOptions == null) { includeOptions = false; } if (includeOptions) { List<Option> options = pollListManager.getOptionsForPoll(poll); poll.setOptions(options); } // add in the indicator that this user has replied if (currentUserId != null) { Map<Long, List<Vote>> voteMap = pollVoteManager.getVotesForUser( currentUserId, new Long[] { pollId }); List<Vote> l = voteMap.get(pollId); if (l != null) { poll.setCurrentUserVoted(true); } else { poll.setCurrentUserVoted(false); } } return poll; } /** * Note that details is the only optional field */ @EntityCustomAction(action = "poll-create", viewKey = EntityView.VIEW_NEW) public String createPollEntity(EntityReference ref, Map<String, Object> params) { Poll poll = new Poll(); // copy from params to Poll copyParamsToObject(params, poll); poll.setCreationDate(new Date()); if (poll.getId() == null) { poll.setId(UUID.randomUUID().toString()); } if (poll.getOwner() == null) { poll.setOwner(developerHelperService.getCurrentUserId()); } String siteId = developerHelperService.getCurrentLocationId(); if (poll.getSiteId() == null) { poll.setSiteId(siteId); } else { siteId = poll.getSiteId(); } String userReference = developerHelperService.getCurrentUserReference(); String location = "/site/" + siteId; boolean allowed = developerHelperService .isUserAllowedInEntityReference(userReference, PollListManager.PERMISSION_ADD, location); if (!allowed) { throw new SecurityException("Current user (" + userReference + ") cannot create polls in location (" + location + ")"); } pollListManager.savePoll(poll); return poll.getPollId() + ""; } @EntityCustomAction(action = "poll-update", viewKey = EntityView.VIEW_EDIT) public void updatePollEntity(EntityReference ref, Map<String, Object> params) { String id = ref.getId(); if (id == null) { throw new IllegalArgumentException( "The reference must include an id for updates (id is currently null)"); } String userReference = developerHelperService.getCurrentUserReference(); if (userReference == null) { throw new SecurityException("anonymous user cannot update poll: " + ref); } Poll current = getPollById(id); if (current == null) { throw new IllegalArgumentException( "No poll found to update for the given reference: " + ref); } Poll poll = new Poll(); copyParamsToObject(params, poll); String siteId = developerHelperService.getCurrentLocationId(); if (poll.getSiteId() == null) { poll.setSiteId(siteId); } else { siteId = poll.getSiteId(); } String location = "/site/" + siteId; // should this check a different permission? boolean allowed = developerHelperService .isUserAllowedInEntityReference(userReference, PollListManager.PERMISSION_ADD, location); if (!allowed) { throw new SecurityException("Current user (" + userReference + ") cannot update polls in location (" + location + ")"); } developerHelperService.copyBean(poll, current, 0, new String[] { "id", "pollId", "owner", "siteId", "creationDate", "reference", "url", "properties" }, true); pollListManager.savePoll(current); } @EntityCustomAction(action = "poll-delete", viewKey = EntityView.VIEW_SHOW) public Object deletePollEntity(EntityReference ref) { String id = ref.getId(); if (id == null) { throw new IllegalArgumentException( "The reference must include an id for deletes (id is currently null)"); } Poll poll = getPollById(id); if (poll == null) { throw new IllegalArgumentException( "No poll found for the given reference: " + ref); } try { pollListManager.deletePoll(poll); return String.format("Poll id %d removed", id); } catch (SecurityException e) { throw new SecurityException("The current user (" + developerHelperService.getCurrentUserReference() + ") is not allowed to delete this poll: " + ref); } } /** * /{pollId}/poll-options */ @EntityCustomAction(action = "poll-option-list", viewKey = EntityView.VIEW_SHOW) public List<?> getPollOptionList(EntityView view, EntityReference ref) { // get the pollId String id = ref.getId(); log.debug(id); // check siteId supplied if (StringUtils.isBlank(id)) { throw new IllegalArgumentException( "siteId must be set in order to get the polls for a site, via the URL /polls/site/siteId"); } Long pollId = null; try { pollId = Long.parseLong(id); } catch (UnsupportedOperationException e) { throw new IllegalArgumentException( "Invalid: pollId must be a long number: " + e.getMessage(), e); } // get the poll Poll poll = pollListManager.getPollById(pollId); if (poll == null) { throw new IllegalArgumentException("pollId (" + pollId + ") is invalid and does not match any known polls"); } else { boolean allowedPublic = pollListManager.isPollPublic(poll); if (!allowedPublic) { String userReference = developerHelperService .getCurrentUserReference(); if (userReference == null) { throw new EntityException( "User must be logged in in order to access poll data", id, HttpServletResponse.SC_UNAUTHORIZED); } else { boolean allowedManage = false; boolean allowedVote = false; allowedManage = developerHelperService .isUserAllowedInEntityReference(userReference, PollListManager.PERMISSION_ADD, "/site/" + poll.getSiteId()); allowedVote = developerHelperService .isUserAllowedInEntityReference(userReference, PollListManager.PERMISSION_VOTE, "/site/" + poll.getSiteId()); if (!(allowedManage || allowedVote)) { throw new SecurityException("User (" + userReference + ") not allowed to access poll data: " + id); } } } } // get the options List<Option> options = pollListManager.getOptionsForPoll(pollId); return options; } @EntityCustomAction(action = "option-view", viewKey = EntityView.VIEW_SHOW) public Object getOptionEntity(EntityReference ref) { String id = ref.getId(); if (id == null) { return new Option(); } String currentUser = developerHelperService.getCurrentUserReference(); if (currentUser == null) { throw new EntityException( "Anonymous users cannot view specific options", ref.getId(), HttpServletResponse.SC_UNAUTHORIZED); } Option option = getOptionById(id); if (developerHelperService.isEntityRequestInternal(ref.toString())) { // ok to retrieve internally } else { // need to security check if (developerHelperService.isUserAdmin(currentUser)) { // ok to view this vote } else { // not allowed to view throw new SecurityException("User (" + currentUser + ") cannot view option (" + ref + ")"); } } return option; } @EntityCustomAction(action = "option-create", viewKey = EntityView.VIEW_NEW) public String createOptionEntity(EntityReference ref, Map<String, Object> params) { String userReference = developerHelperService.getCurrentUserReference(); if (userReference == null) { throw new EntityException( "User must be logged in to create new options", ref.getId(), HttpServletResponse.SC_UNAUTHORIZED); } Option option = new Option(); // copy from params to Option copyParamsToObject(params, option); // check minimum settings if (option.getPollId() == null) { throw new IllegalArgumentException( "Poll ID must be set to create an option"); } // check minimum settings if (option.getText() == null) { throw new IllegalArgumentException( "Poll Option text must be set to create an option"); } checkOptionPermission(userReference, option); // set default values option.setUuid(UUID.randomUUID().toString()); boolean saved = pollListManager.saveOption(option); if (!saved) { throw new IllegalStateException("Unable to save option (" + option + ") for user (" + userReference + "): " + ref); } return option.getId() + ""; } /** * Helper to copy from map of parameters to object. * * @param params * source * @param object * destination */ private void copyParamsToObject(Map<String, Object> params, Object object) { Class<?> c = object.getClass(); Method[] methods = c.getDeclaredMethods(); for (Method m : methods) { String name = m.getName(); Class<?>[] types = m.getParameterTypes(); if (name.startsWith("set") && (types.length == 1)) { String key = Character.toLowerCase(name.charAt(3)) + name.substring(4); Object value = params.get(key); if (value != null) { if (types[0].equals(Date.class)) { Date dateValue = new Date( Long.valueOf(value.toString())); try { m.invoke(object, new Object[] { dateValue }); } catch (IllegalAccessException e) { log.debug(e.getMessage(), e); } catch (IllegalArgumentException e) { log.debug(e.getMessage(), e); } catch (InvocationTargetException e) { log.debug(e.getMessage(), e); } } else { // use generic converter from BeanUtils try { BeanUtils.copyProperty(object, key, value); } catch (IllegalAccessException e) { log.debug(e.getMessage(), e); } catch (InvocationTargetException e) { log.debug(e.getMessage(), e); } } } } } } @EntityCustomAction(action = "option-update", viewKey = EntityView.VIEW_EDIT) public void updateOptionEntity(EntityReference ref, Map<String, Object> params) { String id = ref.getId(); if (id == null) { throw new IllegalArgumentException( "The reference must include an id for updates (id is currently null)"); } String userReference = developerHelperService.getCurrentUserReference(); if (userReference == null) { throw new EntityException("Anonymous user cannot update option", ref.getId(), HttpServletResponse.SC_UNAUTHORIZED); } Option current = getOptionById(id); if (current == null) { throw new IllegalArgumentException( "No option found to update for the given reference: " + ref); } Option option = new Option(); // copy from params to Option copyParamsToObject(params, option); checkOptionPermission(userReference, current); developerHelperService.copyBean(option, current, 0, new String[] { "id", "pollId", "UUId" }, true); boolean saved = pollListManager.saveOption(current); if (!saved) { throw new IllegalStateException("Unable to update option (" + option + ") for user (" + userReference + "): " + ref); } } @EntityCustomAction(action = "option-delete", viewKey = EntityView.VIEW_SHOW) public void deleteOptionEntity(EntityReference ref, Map<String, Object> params) { String id = ref.getId(); String userReference = developerHelperService.getCurrentUserReference(); if (userReference == null) { throw new EntityException("Anonymous user cannot delete option", ref.getId(), HttpServletResponse.SC_UNAUTHORIZED); } Option option = getOptionById(id); if (option == null) { throw new IllegalArgumentException( "No option found to delete for the given reference: " + ref); } checkOptionPermission(userReference, option); pollListManager.deleteOption(option); // return String.format("Poll option id %d removed", id); } /** * Checks if the given user can create/update/delete options * * @param userRef * @param option */ private void checkOptionPermission(String userRef, Option option) { if (option.getPollId() == null) { throw new IllegalArgumentException( "Poll Id must be set in the option to check permissions: " + option); } Long pollId = option.getPollId(); // validate poll exists Poll poll = pollListManager.getPollById(pollId, false); if (poll == null) { throw new IllegalArgumentException("Invalid poll id (" + pollId + "), could not find poll from option: " + option); } // check permissions String siteRef = "/site/" + poll.getSiteId(); if (!developerHelperService.isUserAllowedInEntityReference(userRef, PollListManager.PERMISSION_ADD, siteRef)) { throw new SecurityException( "User (" + userRef + ") is not allowed to create/update/delete options in this poll (" + pollId + ")"); } } /** * @param id * @return */ private Option getOptionById(String id) { Long optionId; try { optionId = Long.valueOf(id); } catch (NumberFormatException e) { throw new IllegalArgumentException("Cannot convert id (" + id + ") to long: " + e.getMessage(), e); } Option option = pollListManager.getOptionById(optionId); return option; } @EntityCustomAction(action = "vote-create", viewKey = EntityView.VIEW_NEW) public String createVoteEntity(EntityReference ref, Map<String, Object> params) { String userId = userDirectoryService.getCurrentUser().getId(); Vote vote = new Vote(); copyParamsToObject(params, vote); log.debug("got vote: " + vote.toString()); Long pollId = null; try { pollId = Long.valueOf((String) params.get("pollId")); } catch (Exception e) { log.warn(e.getMessage(), e); } if (pollId == null) { throw new IllegalArgumentException( "Poll Id must be set to create a vote"); } vote.setPollId(pollId); Long optionId = null; try { optionId = Long.valueOf((String) params.get("pollOption")); } catch (Exception e) { log.warn(e.getMessage(), e); } if (optionId == null) { throw new IllegalArgumentException( "Poll Option must be set to create a vote"); } if (!pollVoteManager.isUserAllowedVote(userId, pollId, false)) { throw new SecurityException("User (" + userId + ") is not allowed to vote in this poll (" + pollId + ")"); } vote.setPollOption(optionId); // validate option Option option = pollListManager.getOptionById(vote.getPollOption()); if (option == null) { throw new IllegalArgumentException("Invalid poll option (" + vote.getPollOption() + ") [cannot find option] in vote (" + vote + ") for user (" + userId + ")"); } else { if (!pollId.equals(option.getPollId())) { throw new IllegalArgumentException("Invalid poll option (" + vote.getPollOption() + ") [not in poll (" + pollId + ")] in vote (" + vote + ") for user (" + userId + ")"); } } // set default vote values vote.setVoteDate(new Date()); vote.setUserId(userId); if (vote.getSubmissionId() == null) { String sid = userId + ":" + UUID.randomUUID(); vote.setSubmissionId(sid); } // set the IP address UsageSession usageSession = usageSessionService.getSession(); if (usageSession != null) { vote.setIp(usageSession.getIpAddress()); } boolean saved = pollVoteManager.saveVote(vote); if (!saved) { throw new IllegalStateException("Unable to save vote (" + vote + ") for user (" + userId + "): " + ref); } return vote.getId() + ""; } @EntityCustomAction(action = "vote-view", viewKey = EntityView.VIEW_SHOW) public Object getVoteEntity(EntityReference ref) { String id = ref.getId(); String currentUser = developerHelperService.getCurrentUserReference(); log.debug("current user is: " + currentUser); if (currentUser == null || currentUser.length() == 0) { throw new EntityException( "Anonymous users cannot view specific votes", ref.getId(), HttpServletResponse.SC_UNAUTHORIZED); } // is this a new object? if (ref.getId() == null) { new Vote(); } Vote vote = getVoteById(id); String userId = developerHelperService.getUserIdFromRef(currentUser); if (developerHelperService.isUserAdmin(currentUser)) { // ok to view this vote } else if (userId.equals(vote.getUserId())) { // ok to view own } else if (developerHelperService.isEntityRequestInternal(ref .toString())) { // ok for all internal requests } else { // TODO - check vote location and perm? // not allowed to view throw new SecurityException("User (" + currentUser + ") cannot view vote (" + ref + ")"); } if (id == null) { return new Vote(); } return vote; } @EntityCustomAction(action = "vote-list", viewKey = EntityView.VIEW_LIST) public List<?> getVoteEntities(EntityReference ref, Search search) { String currentUserId = userDirectoryService.getCurrentUser().getId(); Restriction pollRes = search.getRestrictionByProperty("pollId"); if (pollRes == null || pollRes.getSingleValue() == null) { // throw new // IllegalArgumentException("Must include a non-null pollId in order to retreive a list of votes"); return null; } Long pollId = null; boolean viewVoters = false; if (developerHelperService.isUserAdmin(developerHelperService .getCurrentUserReference())) { viewVoters = true; } try { pollId = developerHelperService.convert(pollRes.getSingleValue(), Long.class); } catch (UnsupportedOperationException e) { throw new IllegalArgumentException( "Invalid: pollId must be a long number: " + e.getMessage(), e); } Poll poll = pollListManager.getPollById(pollId); if (poll == null) { throw new IllegalArgumentException("pollId (" + pollId + ") is invalid and does not match any known polls"); } List<Vote> votes = pollVoteManager.getAllVotesForPoll(poll); if (developerHelperService.isEntityRequestInternal(ref.toString())) { // ok for all internal requests } else if (!pollListManager.isAllowedViewResults(poll, currentUserId)) { // TODO - check vote location and perm? // not allowed to view throw new SecurityException("User (" + currentUserId + ") cannot view vote (" + ref + ")"); } if (viewVoters) { return votes; } else { return anonymizeVotes(votes); } } private List<?> anonymizeVotes(List<Vote> votes) { List<Vote> ret = new ArrayList<Vote>(); String userId = userDirectoryService.getCurrentUser().getId(); for (int i = 0; i < votes.size(); i++) { Vote vote = (Vote) votes.get(i); if (!userId.equals(vote.getUserId())) { Vote newVote = new Vote(); newVote.setPollId(vote.getPollId()); newVote.setPollOption(vote.getPollOption()); newVote.setSubmissionId(vote.getSubmissionId()); ret.add(newVote); } else { ret.add(vote); } } return ret; } /** * Allows a user to create multiple Vote objects at once, taking one or more * pollOption parameters. */ @EntityCustomAction(action = "vote", viewKey = EntityView.VIEW_NEW) public void vote(EntityView view, EntityReference ref, String prefix, Search search, OutputStream out, Map<String, Object> params) { Long pollId = null; try { pollId = Long.valueOf((String) params.get("pollId")); } catch (NumberFormatException nfe) { throw new IllegalArgumentException("No pollId found."); } String userId = userDirectoryService.getCurrentUser().getId(); Poll poll = pollListManager.getPollById(pollId, false); if (poll == null) { throw new IllegalArgumentException( "No poll found to update for the given reference: " + ref); } if (!pollVoteManager.isUserAllowedVote(userId, poll.getPollId(), false)) { throw new SecurityException("User (" + userId + ") is not allowed to vote in this poll (" + poll.getPollId() + ")"); } Set<String> optionIds = new HashSet<String>(); Object param = params.get("pollOption"); if (param == null) { throw new IllegalArgumentException( "At least one pollOption parameter must be provided to vote."); } else if (param instanceof String) { optionIds.add((String) param); } else if (param instanceof Iterable<?>) { for (Object o : (Iterable<?>) param) if (o instanceof String) optionIds.add((String) o); else throw new IllegalArgumentException( "Each pollOption must be a String, not " + o.getClass().getName()); } else if (param instanceof Object[]) { for (Object o : (Object[]) param) if (o instanceof String) optionIds.add((String) o); else throw new IllegalArgumentException( "Each pollOption must be a String, not " + o.getClass().getName()); } else throw new IllegalArgumentException( "pollOption must be String, String[] or List<String>, not " + param.getClass().getName()); // Turn each option String into an Option, making sure that each is a // valid choice for the poll. We use a Map to make sure one cannot vote // more than once for any option by specifying it using equivalent // representations Map<Long, Option> options = new HashMap<Long, Option>(); for (String optionId : optionIds) { try { Option option = pollListManager.getOptionById(Long .valueOf(optionId)); if (!poll.getPollId().equals(option.getPollId())) throw new Exception(); options.put(option.getOptionId(), option); } catch (Exception e) { throw new IllegalArgumentException("Invalid pollOption: " + optionId); } } // Validate that the number of options voted for is within acceptable // bounds. if (options.size() < poll.getMinOptions()) throw new IllegalArgumentException("You must provide at least " + poll.getMinOptions() + " options, not " + options.size() + "."); if (options.size() > poll.getMaxOptions()) throw new IllegalArgumentException("You may provide at most " + poll.getMaxOptions() + " options, not " + options.size() + "."); // Create and save the Vote objects. UsageSession usageSession = usageSessionService.getSession(); List<Vote> votes = new ArrayList<Vote>(); for (Option option : options.values()) { Vote vote = new Vote(); vote.setVoteDate(new Date()); vote.setUserId(userId); vote.setPollId(poll.getPollId()); vote.setPollOption(option.getOptionId()); if (vote.getSubmissionId() == null) { String sid = userId + ":" + UUID.randomUUID(); vote.setSubmissionId(sid); } if (usageSession != null) vote.setIp(usageSession.getIpAddress()); boolean saved = pollVoteManager.saveVote(vote); if (!saved) { throw new IllegalStateException("Unable to save vote (" + vote + ") for user (" + userId + "): " + ref); } votes.add(vote); } } /** * @param id * @return */ private Vote getVoteById(String id) { Long voteId; try { voteId = Long.valueOf(id); } catch (NumberFormatException e) { throw new IllegalArgumentException("Cannot convert id (" + id + ") to long: " + e.getMessage(), e); } Vote vote = pollVoteManager.getVoteById(voteId); return vote; } }
OpenCollabZA/sakai
polls/tool/src/java/org/sakaiproject/poll/tool/entityproviders/PollsEntityProvider.java
Java
apache-2.0
33,518
/* * Druid - a distributed column store. * Copyright 2012 - 2015 Metamarkets Group 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 io.druid.query; import com.metamx.common.guava.Sequence; import java.util.Map; /** */ public abstract class BySegmentSkippingQueryRunner<T> implements QueryRunner<T> { private final QueryRunner<T> baseRunner; public BySegmentSkippingQueryRunner( QueryRunner<T> baseRunner ) { this.baseRunner = baseRunner; } @Override public Sequence<T> run(Query<T> query, Map<String, Object> responseContext) { if (query.getContextBySegment(false)) { return baseRunner.run(query, responseContext); } return doRun(baseRunner, query, responseContext); } protected abstract Sequence<T> doRun(QueryRunner<T> baseRunner, Query<T> query, Map<String, Object> context); }
elijah513/druid
processing/src/main/java/io/druid/query/BySegmentSkippingQueryRunner.java
Java
apache-2.0
1,366
/* * 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.ignite.internal.processors.hadoop.impl.igfs; import static org.apache.ignite.igfs.IgfsMode.PROXY; /** * IGFS Hadoop file system IPC shmem self test in SECONDARY mode. */ public class IgniteHadoopFileSystemShmemExternalSecondarySelfTest extends IgniteHadoopFileSystemShmemAbstractSelfTest { /** * Constructor. */ public IgniteHadoopFileSystemShmemExternalSecondarySelfTest() { super(PROXY, true); } }
afinka77/ignite
modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/impl/igfs/IgniteHadoopFileSystemShmemExternalSecondarySelfTest.java
Java
apache-2.0
1,260
package com.vaadin.tests.components.ui; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import com.vaadin.tests.tb3.MultiBrowserTest; public class PollListeningTest extends MultiBrowserTest { @Test public void testReceivePollEvent() { openTestURL(); waitUntilPollEventReceived(); } private void waitUntilPollEventReceived() { waitUntil(new ExpectedCondition<Boolean>() { private String expected = "PollEvent received"; @Override public Boolean apply(WebDriver arg0) { return driver.getPageSource().contains(expected); } @Override public String toString() { return String.format("page to contain text '%s'", expected); } }); } }
jdahlstrom/vaadin.react
uitest/src/test/java/com/vaadin/tests/components/ui/PollListeningTest.java
Java
apache-2.0
873
/* ObjectReferenceFactory.java -- Copyright (C) 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath 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 2, or (at your option) any later version. GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package org.omg.PortableInterceptor; import org.omg.CORBA.Object; import org.omg.CORBA.portable.IDLEntity; import org.omg.CORBA.portable.ValueBase; /** * Provides the possibility to create the CORBA object reference. * The reference is created from repository id (defining the type of the * object) and the object id (defining the identity of the object). * * @since 1.5 * * @author Audrius Meskauskas, Lithuania ([email protected]) */ public interface ObjectReferenceFactory extends ValueBase, IDLEntity { /** * Create an object with the given repository and object ids. This interface * does not specify where and how the returned object must be connected and * activated. The derived {@link ObjectReferenceTemplate} interface assumes * the object must be connected to the POA that is specific to that * template (name can be obtained). * * If the object with this objectId already exists in the given context, it * is found and returned; a new object is <i>not</i> created. * * @param repositoryId the repository id of the object being created, defines * the type of the object. * * @param objectId the byte array, defining the identity of the object. * * @return The created corba object. */ Object make_object(String repositoryId, byte[] objectId); }
shaotuanchen/sunflower_exp
tools/source/gcc-4.2.4/libjava/classpath/org/omg/PortableInterceptor/ObjectReferenceFactory.java
Java
bsd-3-clause
3,085
/* * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* */ /* * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved * (C) Copyright IBM Corp. 1996 - 1999 - All Rights Reserved * * The original version of this source code and documentation * is copyrighted and owned by Taligent, Inc., a wholly-owned * subsidiary of IBM. These materials are provided under terms * of a License Agreement between Taligent and Sun. This technology * is protected by multiple US and International patents. * * This notice and attribution to Taligent may not be removed. * Taligent is a registered trademark of Taligent, Inc. * */ package sun.text.resources; import java.util.ListResourceBundle; public class CollationData_zh extends ListResourceBundle { protected final Object[][] getContents() { return new Object[][] { { "Rule", // GB 2312 "& Z<\u3000<\u3001<\u3002<\u30fb<\u02c9" + "<\u02c7<\u3003<\u3005<\u2015<\uff5e<\u2016" + "<\u2026<\u2018<\u2019<\u201c<\u201d<\u3014<\u3015" + "<\u3008<\u3009<\u300a<\u300b<\u300c<\u300d<\u300e" + "<\u300f<\u3016<\u3017<\u3010<\u3011" + "<\u2236<\u2227<\u2228<\u2211<\u220f<\u222a" + "<\u2229<\u2208<\u2237<\u221a<\u22a5<\u2225<\u2220" + "<\u2312<\u2299<\u222b<\u222e<\u2261<\u224c<\u2248" + "<\u223d<\u221d<\u2260<\u226e<\u226f<\u2264<\u2265" + "<\u221e<\u2235<\u2234<\u2642<\u2640<\u2032" + "<\u2033<\u2103<\uff04<\uffe0<\uffe1<\u2030" + "<\u2116<\u2606<\u2605<\u25cb<\u25cf<\u25ce" + "<\u25c7<\u25c6<\u25a1<\u25a0<\u25b3<\u25b2<\u203b" + "<\u2192<\u2190<\u2191<\u2193<\u3013" + "<\u2488<\u2489<\u248a<\u248b<\u248c<\u248d<\u248e" + "<\u248f<\u2490<\u2491<\u2492<\u2493<\u2494<\u2495" + "<\u2496<\u2497<\u2498<\u2499<\u249a<\u249b<\u2474" + "<\u2475<\u2476<\u2477<\u2478<\u2479<\u247a<\u247b" + "<\u247c<\u247d<\u247e<\u247f<\u2480<\u2481<\u2482" + "<\u2483<\u2484<\u2485<\u2486<\u2487<\u2460<\u2461" + "<\u2462<\u2463<\u2464<\u2465<\u2466<\u2467<\u2468" + "<\u2469<\u3220<\u3221<\u3222<\u3223" + "<\u3224<\u3225<\u3226<\u3227<\u3228<\u3229" + "<\uff01<\uff02<\uff03<\uffe5<\uff05<\uff06" + "<\uff08<\uff09<\uff0a<\uff0b<\uff0c<\uff0d" + "<\uff0e<\uff0f<\uff10<\uff11<\uff12<\uff13<\uff14" + "<\uff15<\uff16<\uff17<\uff18<\uff19<\uff1a<\uff1b" + "<\uff1c<\uff1d<\uff1e<\uff1f<\uff20<\uff21<\uff22" + "<\uff23<\uff24<\uff25<\uff26<\uff27<\uff28<\uff29" + "<\uff2a<\uff2b<\uff2c<\uff2d<\uff2e<\uff2f<\uff30" + "<\uff31<\uff32<\uff33<\uff34<\uff35<\uff36<\uff37" + "<\uff38<\uff39<\uff3a<\uff3b<\uff3c<\uff3d<\uff3e" + "<\uff3f<\uff40<\uff41<\uff42<\uff43<\uff44<\uff45" + "<\uff46<\uff47<\uff48<\uff49<\uff4a<\uff4b<\uff4c" + "<\uff4d<\uff4e<\uff4f<\uff50<\uff51<\uff52<\uff53" + "<\uff54<\uff55<\uff56<\uff57<\uff58<\uff59<\uff5a" + "<\uff5b<\uff5c<\uff5d<\uffe3<\u3041<\u3042<\u3043" + "<\u3044<\u3045<\u3046<\u3047<\u3048<\u3049<\u304a" + "<\u304b<\u304c<\u304d<\u304e<\u304f<\u3050<\u3051" + "<\u3052<\u3053<\u3054<\u3055<\u3056<\u3057<\u3058" + "<\u3059<\u305a<\u305b<\u305c<\u305d<\u305e<\u305f" + "<\u3060<\u3061<\u3062<\u3063<\u3064<\u3065<\u3066" + "<\u3067<\u3068<\u3069<\u306a<\u306b<\u306c<\u306d" + "<\u306e<\u306f<\u3070<\u3071<\u3072<\u3073<\u3074" + "<\u3075<\u3076<\u3077<\u3078<\u3079<\u307a<\u307b" + "<\u307c<\u307d<\u307e<\u307f<\u3080<\u3081<\u3082" + "<\u3083<\u3084<\u3085<\u3086<\u3087<\u3088<\u3089" + "<\u308a<\u308b<\u308c<\u308d<\u308e<\u308f<\u3090" + "<\u3091<\u3092<\u3093" + "<\u30a1<\u30a2<\u30a3<\u30a4<\u30a5<\u30a6<\u30a7" + "<\u30a8<\u30a9<\u30aa<\u30ab<\u30ac<\u30ad<\u30ae" + "<\u30af<\u30b0<\u30b1<\u30b2<\u30b3<\u30b4<\u30b5" + "<\u30b6<\u30b7<\u30b8<\u30b9<\u30ba<\u30bb<\u30bc" + "<\u30bd<\u30be<\u30bf<\u30c0<\u30c1<\u30c2<\u30c3" + "<\u30c4<\u30c5<\u30c6<\u30c7<\u30c8<\u30c9<\u30ca" + "<\u30cb<\u30cc<\u30cd<\u30ce<\u30cf<\u30d0<\u30d1" + "<\u30d2<\u30d3<\u30d4<\u30d5<\u30d6<\u30d7<\u30d8" + "<\u30d9<\u30da<\u30db<\u30dc<\u30dd<\u30de<\u30df" + "<\u30e0<\u30e1<\u30e2<\u30e3<\u30e4<\u30e5<\u30e6" + "<\u30e7<\u30e8<\u30e9<\u30ea<\u30eb<\u30ec<\u30ed" + "<\u30ee<\u30ef<\u30f0<\u30f1<\u30f2<\u30f3<\u30f4" + "<\u30f5<\u30f6" + "<\u0391<\u0392<\u0393<\u0394" + "<\u0395<\u0396<\u0397<\u0398<\u0399<\u039a<\u039b" + "<\u039c<\u039d<\u039e<\u039f<\u03a0<\u03a1<\u03a3" + "<\u03a4<\u03a5<\u03a6<\u03a7<\u03a8<\u03a9" + "<\u03b1<\u03b2<\u03b3<\u03b4<\u03b5<\u03b6<\u03b7" + "<\u03b8<\u03b9<\u03ba<\u03bb<\u03bc<\u03bd<\u03be" + "<\u03bf<\u03c0<\u03c1<\u03c3<\u03c4<\u03c5<\u03c6" + "<\u03c7<\u03c8<\u03c9" + "<\u0410" + "<\u0411<\u0412<\u0413<\u0414<\u0415<\u0401<\u0416" + "<\u0417<\u0418<\u0419<\u041a<\u041b<\u041c<\u041d" + "<\u041e<\u041f<\u0420<\u0421<\u0422<\u0423<\u0424" + "<\u0425<\u0426<\u0427<\u0428<\u0429<\u042a<\u042b" + "<\u042c<\u042d<\u042e<\u042f" + "<\u0430<\u0431" + "<\u0432<\u0433<\u0434<\u0435<\u0451<\u0436<\u0437" + "<\u0438<\u0439<\u043a<\u043b<\u043c<\u043d<\u043e" + "<\u043f<\u0440<\u0441<\u0442<\u0443<\u0444<\u0445" + "<\u0446<\u0447<\u0448<\u0449<\u044a<\u044b<\u044c" + "<\u044d<\u044e<\u044f" + "<\u3105<\u3106<\u3107<\u3108" + "<\u3109<\u310a<\u310b<\u310c<\u310d<\u310e<\u310f" + "<\u3110<\u3111<\u3112<\u3113<\u3114<\u3115<\u3116" + "<\u3117<\u3118<\u3119<\u311a<\u311b<\u311c<\u311d" + "<\u311e<\u311f<\u3120<\u3121<\u3122<\u3123<\u3124" + "<\u3125<\u3126<\u3127<\u3128<\u3129" + "<\u2500<\u2501<\u2502<\u2503<\u2504<\u2505" + "<\u2506<\u2507<\u2508<\u2509<\u250a<\u250b<\u250c" + "<\u250d<\u250e<\u250f<\u2510<\u2511<\u2512<\u2513" + "<\u2514<\u2515<\u2516<\u2517<\u2518<\u2519<\u251a" + "<\u251b<\u251c<\u251d<\u251e<\u251f<\u2520<\u2521" + "<\u2522<\u2523<\u2524<\u2525<\u2526<\u2527<\u2528" + "<\u2529<\u252a<\u252b<\u252c<\u252d<\u252e<\u252f" + "<\u2530<\u2531<\u2532<\u2533<\u2534<\u2535<\u2536" + "<\u2537<\u2538<\u2539<\u253a<\u253b<\u253c<\u253d" + "<\u253e<\u253f<\u2540<\u2541<\u2542<\u2543<\u2544" + "<\u2545<\u2546<\u2547<\u2548<\u2549<\u254a<\u254b" + "<\u554a<\u963f" + "<\u57c3<\u6328<\u54ce<\u5509<\u54c0<\u7691<\u764c" + "<\u853c<\u77ee<\u827e<\u788d<\u7231<\u9698<\u978d" + "<\u6c28<\u5b89<\u4ffa<\u6309<\u6697<\u5cb8<\u80fa" + "<\u6848<\u80ae<\u6602<\u76ce<\u51f9<\u6556<\u71ac" + "<\u7ff1<\u8884<\u50b2<\u5965<\u61ca<\u6fb3<\u82ad" + "<\u634c<\u6252<\u53ed<\u5427<\u7b06<\u516b<\u75a4" + "<\u5df4<\u62d4<\u8dcb<\u9776<\u628a<\u8019<\u575d" + "<\u9738<\u7f62<\u7238<\u767d<\u67cf<\u767e<\u6446" + "<\u4f70<\u8d25<\u62dc<\u7a17<\u6591<\u73ed<\u642c" + "<\u6273<\u822c<\u9881<\u677f<\u7248<\u626e<\u62cc" + "<\u4f34<\u74e3<\u534a<\u529e<\u7eca<\u90a6<\u5e2e" + "<\u6886<\u699c<\u8180<\u7ed1<\u68d2<\u78c5<\u868c" + "<\u9551<\u508d<\u8c24<\u82de<\u80de<\u5305<\u8912" + "<\u5265<\u8584<\u96f9<\u4fdd<\u5821<\u9971<\u5b9d" + "<\u62b1<\u62a5<\u66b4<\u8c79<\u9c8d<\u7206<\u676f" + "<\u7891<\u60b2<\u5351<\u5317<\u8f88<\u80cc<\u8d1d" + "<\u94a1<\u500d<\u72c8<\u5907<\u60eb<\u7119<\u88ab" + "<\u5954<\u82ef<\u672c<\u7b28<\u5d29<\u7ef7<\u752d" + "<\u6cf5<\u8e66<\u8ff8<\u903c<\u9f3b<\u6bd4<\u9119" + "<\u7b14<\u5f7c<\u78a7<\u84d6<\u853d<\u6bd5<\u6bd9" + "<\u6bd6<\u5e01<\u5e87<\u75f9<\u95ed<\u655d<\u5f0a" + "<\u5fc5<\u8f9f<\u58c1<\u81c2<\u907f<\u965b<\u97ad" + "<\u8fb9<\u7f16<\u8d2c<\u6241<\u4fbf<\u53d8<\u535e" + "<\u8fa8<\u8fa9<\u8fab<\u904d<\u6807<\u5f6a<\u8198" + "<\u8868<\u9cd6<\u618b<\u522b<\u762a<\u5f6c<\u658c" + "<\u6fd2<\u6ee8<\u5bbe<\u6448<\u5175<\u51b0<\u67c4" + "<\u4e19<\u79c9<\u997c<\u70b3<\u75c5<\u5e76<\u73bb" + "<\u83e0<\u64ad<\u62e8<\u94b5<\u6ce2<\u535a<\u52c3" + "<\u640f<\u94c2<\u7b94<\u4f2f<\u5e1b<\u8236<\u8116" + "<\u818a<\u6e24<\u6cca<\u9a73<\u6355<\u535c<\u54fa" + "<\u8865<\u57e0<\u4e0d<\u5e03<\u6b65<\u7c3f<\u90e8" + "<\u6016<\u64e6<\u731c<\u88c1<\u6750<\u624d<\u8d22" + "<\u776c<\u8e29<\u91c7<\u5f69<\u83dc<\u8521<\u9910" + "<\u53c2<\u8695<\u6b8b<\u60ed<\u60e8<\u707f<\u82cd" + "<\u8231<\u4ed3<\u6ca7<\u85cf<\u64cd<\u7cd9<\u69fd" + "<\u66f9<\u8349<\u5395<\u7b56<\u4fa7<\u518c<\u6d4b" + "<\u5c42<\u8e6d<\u63d2<\u53c9<\u832c<\u8336<\u67e5" + "<\u78b4<\u643d<\u5bdf<\u5c94<\u5dee<\u8be7<\u62c6" + "<\u67f4<\u8c7a<\u6400<\u63ba<\u8749<\u998b<\u8c17" + "<\u7f20<\u94f2<\u4ea7<\u9610<\u98a4<\u660c<\u7316" + "<\u573a<\u5c1d<\u5e38<\u957f<\u507f<\u80a0<\u5382" + "<\u655e<\u7545<\u5531<\u5021<\u8d85<\u6284<\u949e" + "<\u671d<\u5632<\u6f6e<\u5de2<\u5435<\u7092<\u8f66" + "<\u626f<\u64a4<\u63a3<\u5f7b<\u6f88<\u90f4<\u81e3" + "<\u8fb0<\u5c18<\u6668<\u5ff1<\u6c89<\u9648<\u8d81" + "<\u886c<\u6491<\u79f0<\u57ce<\u6a59<\u6210<\u5448" + "<\u4e58<\u7a0b<\u60e9<\u6f84<\u8bda<\u627f<\u901e" + "<\u9a8b<\u79e4<\u5403<\u75f4<\u6301<\u5319<\u6c60" + "<\u8fdf<\u5f1b<\u9a70<\u803b<\u9f7f<\u4f88<\u5c3a" + "<\u8d64<\u7fc5<\u65a5<\u70bd<\u5145<\u51b2<\u866b" + "<\u5d07<\u5ba0<\u62bd<\u916c<\u7574<\u8e0c<\u7a20" + "<\u6101<\u7b79<\u4ec7<\u7ef8<\u7785<\u4e11<\u81ed" + "<\u521d<\u51fa<\u6a71<\u53a8<\u8e87<\u9504<\u96cf" + "<\u6ec1<\u9664<\u695a<\u7840<\u50a8<\u77d7<\u6410" + "<\u89e6<\u5904<\u63e3<\u5ddd<\u7a7f<\u693d<\u4f20" + "<\u8239<\u5598<\u4e32<\u75ae<\u7a97<\u5e62<\u5e8a" + "<\u95ef<\u521b<\u5439<\u708a<\u6376<\u9524<\u5782" + "<\u6625<\u693f<\u9187<\u5507<\u6df3<\u7eaf<\u8822" + "<\u6233<\u7ef0<\u75b5<\u8328<\u78c1<\u96cc<\u8f9e" + "<\u6148<\u74f7<\u8bcd<\u6b64<\u523a<\u8d50<\u6b21" + "<\u806a<\u8471<\u56f1<\u5306<\u4ece<\u4e1b<\u51d1" + "<\u7c97<\u918b<\u7c07<\u4fc3<\u8e7f<\u7be1<\u7a9c" + "<\u6467<\u5d14<\u50ac<\u8106<\u7601<\u7cb9<\u6dec" + "<\u7fe0<\u6751<\u5b58<\u5bf8<\u78cb<\u64ae<\u6413" + "<\u63aa<\u632b<\u9519<\u642d<\u8fbe<\u7b54<\u7629" + "<\u6253<\u5927<\u5446<\u6b79<\u50a3<\u6234<\u5e26" + "<\u6b86<\u4ee3<\u8d37<\u888b<\u5f85<\u902e<\u6020" + "<\u803d<\u62c5<\u4e39<\u5355<\u90f8<\u63b8<\u80c6" + "<\u65e6<\u6c2e<\u4f46<\u60ee<\u6de1<\u8bde<\u5f39" + "<\u86cb<\u5f53<\u6321<\u515a<\u8361<\u6863<\u5200" + "<\u6363<\u8e48<\u5012<\u5c9b<\u7977<\u5bfc<\u5230" + "<\u7a3b<\u60bc<\u9053<\u76d7<\u5fb7<\u5f97<\u7684" + "<\u8e6c<\u706f<\u767b<\u7b49<\u77aa<\u51f3<\u9093" + "<\u5824<\u4f4e<\u6ef4<\u8fea<\u654c<\u7b1b<\u72c4" + "<\u6da4<\u7fdf<\u5ae1<\u62b5<\u5e95<\u5730<\u8482" + "<\u7b2c<\u5e1d<\u5f1f<\u9012<\u7f14<\u98a0<\u6382" + "<\u6ec7<\u7898<\u70b9<\u5178<\u975b<\u57ab<\u7535" + "<\u4f43<\u7538<\u5e97<\u60e6<\u5960<\u6dc0<\u6bbf" + "<\u7889<\u53fc<\u96d5<\u51cb<\u5201<\u6389<\u540a" + "<\u9493<\u8c03<\u8dcc<\u7239<\u789f<\u8776<\u8fed" + "<\u8c0d<\u53e0<\u4e01<\u76ef<\u53ee<\u9489<\u9876" + "<\u9f0e<\u952d<\u5b9a<\u8ba2<\u4e22<\u4e1c<\u51ac" + "<\u8463<\u61c2<\u52a8<\u680b<\u4f97<\u606b<\u51bb" + "<\u6d1e<\u515c<\u6296<\u6597<\u9661<\u8c46<\u9017" + "<\u75d8<\u90fd<\u7763<\u6bd2<\u728a<\u72ec<\u8bfb" + "<\u5835<\u7779<\u8d4c<\u675c<\u9540<\u809a<\u5ea6" + "<\u6e21<\u5992<\u7aef<\u77ed<\u953b<\u6bb5<\u65ad" + "<\u7f0e<\u5806<\u5151<\u961f<\u5bf9<\u58a9<\u5428" + "<\u8e72<\u6566<\u987f<\u56e4<\u949d<\u76fe<\u9041" + "<\u6387<\u54c6<\u591a<\u593a<\u579b<\u8eb2<\u6735" + "<\u8dfa<\u8235<\u5241<\u60f0<\u5815<\u86fe<\u5ce8" + "<\u9e45<\u4fc4<\u989d<\u8bb9<\u5a25<\u6076<\u5384" + "<\u627c<\u904f<\u9102<\u997f<\u6069<\u800c<\u513f" + "<\u8033<\u5c14<\u9975<\u6d31<\u4e8c<\u8d30<\u53d1" + "<\u7f5a<\u7b4f<\u4f10<\u4e4f<\u9600<\u6cd5<\u73d0" + "<\u85e9<\u5e06<\u756a<\u7ffb<\u6a0a<\u77fe<\u9492" + "<\u7e41<\u51e1<\u70e6<\u53cd<\u8fd4<\u8303<\u8d29" + "<\u72af<\u996d<\u6cdb<\u574a<\u82b3<\u65b9<\u80aa" + "<\u623f<\u9632<\u59a8<\u4eff<\u8bbf<\u7eba<\u653e" + "<\u83f2<\u975e<\u5561<\u98de<\u80a5<\u532a<\u8bfd" + "<\u5420<\u80ba<\u5e9f<\u6cb8<\u8d39<\u82ac<\u915a" + "<\u5429<\u6c1b<\u5206<\u7eb7<\u575f<\u711a<\u6c7e" + "<\u7c89<\u594b<\u4efd<\u5fff<\u6124<\u7caa<\u4e30" + "<\u5c01<\u67ab<\u8702<\u5cf0<\u950b<\u98ce<\u75af" + "<\u70fd<\u9022<\u51af<\u7f1d<\u8bbd<\u5949<\u51e4" + "<\u4f5b<\u5426<\u592b<\u6577<\u80a4<\u5b75<\u6276" + "<\u62c2<\u8f90<\u5e45<\u6c1f<\u7b26<\u4f0f<\u4fd8" + "<\u670d<\u6d6e<\u6daa<\u798f<\u88b1<\u5f17<\u752b" + "<\u629a<\u8f85<\u4fef<\u91dc<\u65a7<\u812f<\u8151" + "<\u5e9c<\u8150<\u8d74<\u526f<\u8986<\u8d4b<\u590d" + "<\u5085<\u4ed8<\u961c<\u7236<\u8179<\u8d1f<\u5bcc" + "<\u8ba3<\u9644<\u5987<\u7f1a<\u5490<\u5676<\u560e" + "<\u8be5<\u6539<\u6982<\u9499<\u76d6<\u6e89<\u5e72" + "<\u7518<\u6746<\u67d1<\u7aff<\u809d<\u8d76<\u611f" + "<\u79c6<\u6562<\u8d63<\u5188<\u521a<\u94a2<\u7f38" + "<\u809b<\u7eb2<\u5c97<\u6e2f<\u6760<\u7bd9<\u768b" + "<\u9ad8<\u818f<\u7f94<\u7cd5<\u641e<\u9550<\u7a3f" + "<\u544a<\u54e5<\u6b4c<\u6401<\u6208<\u9e3d<\u80f3" + "<\u7599<\u5272<\u9769<\u845b<\u683c<\u86e4<\u9601" + "<\u9694<\u94ec<\u4e2a<\u5404<\u7ed9<\u6839<\u8ddf" + "<\u8015<\u66f4<\u5e9a<\u7fb9<\u57c2<\u803f<\u6897" + "<\u5de5<\u653b<\u529f<\u606d<\u9f9a<\u4f9b<\u8eac" + "<\u516c<\u5bab<\u5f13<\u5de9<\u6c5e<\u62f1<\u8d21" + "<\u5171<\u94a9<\u52fe<\u6c9f<\u82df<\u72d7<\u57a2" + "<\u6784<\u8d2d<\u591f<\u8f9c<\u83c7<\u5495<\u7b8d" + "<\u4f30<\u6cbd<\u5b64<\u59d1<\u9f13<\u53e4<\u86ca" + "<\u9aa8<\u8c37<\u80a1<\u6545<\u987e<\u56fa<\u96c7" + "<\u522e<\u74dc<\u5250<\u5be1<\u6302<\u8902<\u4e56" + "<\u62d0<\u602a<\u68fa<\u5173<\u5b98<\u51a0<\u89c2" + "<\u7ba1<\u9986<\u7f50<\u60ef<\u704c<\u8d2f<\u5149" + "<\u5e7f<\u901b<\u7470<\u89c4<\u572d<\u7845<\u5f52" + "<\u9f9f<\u95fa<\u8f68<\u9b3c<\u8be1<\u7678<\u6842" + "<\u67dc<\u8dea<\u8d35<\u523d<\u8f8a<\u6eda<\u68cd" + "<\u9505<\u90ed<\u56fd<\u679c<\u88f9<\u8fc7<\u54c8" + "<\u9ab8<\u5b69<\u6d77<\u6c26<\u4ea5<\u5bb3<\u9a87" + "<\u9163<\u61a8<\u90af<\u97e9<\u542b<\u6db5<\u5bd2" + "<\u51fd<\u558a<\u7f55<\u7ff0<\u64bc<\u634d<\u65f1" + "<\u61be<\u608d<\u710a<\u6c57<\u6c49<\u592f<\u676d" + "<\u822a<\u58d5<\u568e<\u8c6a<\u6beb<\u90dd<\u597d" + "<\u8017<\u53f7<\u6d69<\u5475<\u559d<\u8377<\u83cf" + "<\u6838<\u79be<\u548c<\u4f55<\u5408<\u76d2<\u8c89" + "<\u9602<\u6cb3<\u6db8<\u8d6b<\u8910<\u9e64<\u8d3a" + "<\u563f<\u9ed1<\u75d5<\u5f88<\u72e0<\u6068<\u54fc" + "<\u4ea8<\u6a2a<\u8861<\u6052<\u8f70<\u54c4<\u70d8" + "<\u8679<\u9e3f<\u6d2a<\u5b8f<\u5f18<\u7ea2<\u5589" + "<\u4faf<\u7334<\u543c<\u539a<\u5019<\u540e<\u547c" + "<\u4e4e<\u5ffd<\u745a<\u58f6<\u846b<\u80e1<\u8774" + "<\u72d0<\u7cca<\u6e56<\u5f27<\u864e<\u552c<\u62a4" + "<\u4e92<\u6caa<\u6237<\u82b1<\u54d7<\u534e<\u733e" + "<\u6ed1<\u753b<\u5212<\u5316<\u8bdd<\u69d0<\u5f8a" + "<\u6000<\u6dee<\u574f<\u6b22<\u73af<\u6853<\u8fd8" + "<\u7f13<\u6362<\u60a3<\u5524<\u75ea<\u8c62<\u7115" + "<\u6da3<\u5ba6<\u5e7b<\u8352<\u614c<\u9ec4<\u78fa" + "<\u8757<\u7c27<\u7687<\u51f0<\u60f6<\u714c<\u6643" + "<\u5e4c<\u604d<\u8c0e<\u7070<\u6325<\u8f89<\u5fbd" + "<\u6062<\u86d4<\u56de<\u6bc1<\u6094<\u6167<\u5349" + "<\u60e0<\u6666<\u8d3f<\u79fd<\u4f1a<\u70e9<\u6c47" + "<\u8bb3<\u8bf2<\u7ed8<\u8364<\u660f<\u5a5a<\u9b42" + "<\u6d51<\u6df7<\u8c41<\u6d3b<\u4f19<\u706b<\u83b7" + "<\u6216<\u60d1<\u970d<\u8d27<\u7978<\u51fb<\u573e" + "<\u57fa<\u673a<\u7578<\u7a3d<\u79ef<\u7b95<\u808c" + "<\u9965<\u8ff9<\u6fc0<\u8ba5<\u9e21<\u59ec<\u7ee9" + "<\u7f09<\u5409<\u6781<\u68d8<\u8f91<\u7c4d<\u96c6" + "<\u53ca<\u6025<\u75be<\u6c72<\u5373<\u5ac9<\u7ea7" + "<\u6324<\u51e0<\u810a<\u5df1<\u84df<\u6280<\u5180" + "<\u5b63<\u4f0e<\u796d<\u5242<\u60b8<\u6d4e<\u5bc4" + "<\u5bc2<\u8ba1<\u8bb0<\u65e2<\u5fcc<\u9645<\u5993" + "<\u7ee7<\u7eaa<\u5609<\u67b7<\u5939<\u4f73<\u5bb6" + "<\u52a0<\u835a<\u988a<\u8d3e<\u7532<\u94be<\u5047" + "<\u7a3c<\u4ef7<\u67b6<\u9a7e<\u5ac1<\u6b7c<\u76d1" + "<\u575a<\u5c16<\u7b3a<\u95f4<\u714e<\u517c<\u80a9" + "<\u8270<\u5978<\u7f04<\u8327<\u68c0<\u67ec<\u78b1" + "<\u7877<\u62e3<\u6361<\u7b80<\u4fed<\u526a<\u51cf" + "<\u8350<\u69db<\u9274<\u8df5<\u8d31<\u89c1<\u952e" + "<\u7bad<\u4ef6<\u5065<\u8230<\u5251<\u996f<\u6e10" + "<\u6e85<\u6da7<\u5efa<\u50f5<\u59dc<\u5c06<\u6d46" + "<\u6c5f<\u7586<\u848b<\u6868<\u5956<\u8bb2<\u5320" + "<\u9171<\u964d<\u8549<\u6912<\u7901<\u7126<\u80f6" + "<\u4ea4<\u90ca<\u6d47<\u9a84<\u5a07<\u56bc<\u6405" + "<\u94f0<\u77eb<\u4fa5<\u811a<\u72e1<\u89d2<\u997a" + "<\u7f34<\u7ede<\u527f<\u6559<\u9175<\u8f7f<\u8f83" + "<\u53eb<\u7a96<\u63ed<\u63a5<\u7686<\u79f8<\u8857" + "<\u9636<\u622a<\u52ab<\u8282<\u6854<\u6770<\u6377" + "<\u776b<\u7aed<\u6d01<\u7ed3<\u89e3<\u59d0<\u6212" + "<\u85c9<\u82a5<\u754c<\u501f<\u4ecb<\u75a5<\u8beb" + "<\u5c4a<\u5dfe<\u7b4b<\u65a4<\u91d1<\u4eca<\u6d25" + "<\u895f<\u7d27<\u9526<\u4ec5<\u8c28<\u8fdb<\u9773" + "<\u664b<\u7981<\u8fd1<\u70ec<\u6d78<\u5c3d<\u52b2" + "<\u8346<\u5162<\u830e<\u775b<\u6676<\u9cb8<\u4eac" + "<\u60ca<\u7cbe<\u7cb3<\u7ecf<\u4e95<\u8b66<\u666f" + "<\u9888<\u9759<\u5883<\u656c<\u955c<\u5f84<\u75c9" + "<\u9756<\u7adf<\u7ade<\u51c0<\u70af<\u7a98<\u63ea" + "<\u7a76<\u7ea0<\u7396<\u97ed<\u4e45<\u7078<\u4e5d" + "<\u9152<\u53a9<\u6551<\u65e7<\u81fc<\u8205<\u548e" + "<\u5c31<\u759a<\u97a0<\u62d8<\u72d9<\u75bd<\u5c45" + "<\u9a79<\u83ca<\u5c40<\u5480<\u77e9<\u4e3e<\u6cae" + "<\u805a<\u62d2<\u636e<\u5de8<\u5177<\u8ddd<\u8e1e" + "<\u952f<\u4ff1<\u53e5<\u60e7<\u70ac<\u5267<\u6350" + "<\u9e43<\u5a1f<\u5026<\u7737<\u5377<\u7ee2<\u6485" + "<\u652b<\u6289<\u6398<\u5014<\u7235<\u89c9<\u51b3" + "<\u8bc0<\u7edd<\u5747<\u83cc<\u94a7<\u519b<\u541b" + "<\u5cfb<\u4fca<\u7ae3<\u6d5a<\u90e1<\u9a8f<\u5580" + "<\u5496<\u5361<\u54af<\u5f00<\u63e9<\u6977<\u51ef" + "<\u6168<\u520a<\u582a<\u52d8<\u574e<\u780d<\u770b" + "<\u5eb7<\u6177<\u7ce0<\u625b<\u6297<\u4ea2<\u7095" + "<\u8003<\u62f7<\u70e4<\u9760<\u5777<\u82db<\u67ef" + "<\u68f5<\u78d5<\u9897<\u79d1<\u58f3<\u54b3<\u53ef" + "<\u6e34<\u514b<\u523b<\u5ba2<\u8bfe<\u80af<\u5543" + "<\u57a6<\u6073<\u5751<\u542d<\u7a7a<\u6050<\u5b54" + "<\u63a7<\u62a0<\u53e3<\u6263<\u5bc7<\u67af<\u54ed" + "<\u7a9f<\u82e6<\u9177<\u5e93<\u88e4<\u5938<\u57ae" + "<\u630e<\u8de8<\u80ef<\u5757<\u7b77<\u4fa9<\u5feb" + "<\u5bbd<\u6b3e<\u5321<\u7b50<\u72c2<\u6846<\u77ff" + "<\u7736<\u65f7<\u51b5<\u4e8f<\u76d4<\u5cbf<\u7aa5" + "<\u8475<\u594e<\u9b41<\u5080<\u9988<\u6127<\u6e83" + "<\u5764<\u6606<\u6346<\u56f0<\u62ec<\u6269<\u5ed3" + "<\u9614<\u5783<\u62c9<\u5587<\u8721<\u814a<\u8fa3" + "<\u5566<\u83b1<\u6765<\u8d56<\u84dd<\u5a6a<\u680f" + "<\u62e6<\u7bee<\u9611<\u5170<\u6f9c<\u8c30<\u63fd" + "<\u89c8<\u61d2<\u7f06<\u70c2<\u6ee5<\u7405<\u6994" + "<\u72fc<\u5eca<\u90ce<\u6717<\u6d6a<\u635e<\u52b3" + "<\u7262<\u8001<\u4f6c<\u59e5<\u916a<\u70d9<\u6d9d" + "<\u52d2<\u4e50<\u96f7<\u956d<\u857e<\u78ca<\u7d2f" + "<\u5121<\u5792<\u64c2<\u808b<\u7c7b<\u6cea<\u68f1" + "<\u695e<\u51b7<\u5398<\u68a8<\u7281<\u9ece<\u7bf1" + "<\u72f8<\u79bb<\u6f13<\u7406<\u674e<\u91cc<\u9ca4" + "<\u793c<\u8389<\u8354<\u540f<\u6817<\u4e3d<\u5389" + "<\u52b1<\u783e<\u5386<\u5229<\u5088<\u4f8b<\u4fd0" + "<\u75e2<\u7acb<\u7c92<\u6ca5<\u96b6<\u529b<\u7483" + "<\u54e9<\u4fe9<\u8054<\u83b2<\u8fde<\u9570<\u5ec9" + "<\u601c<\u6d9f<\u5e18<\u655b<\u8138<\u94fe<\u604b" + "<\u70bc<\u7ec3<\u7cae<\u51c9<\u6881<\u7cb1<\u826f" + "<\u4e24<\u8f86<\u91cf<\u667e<\u4eae<\u8c05<\u64a9" + "<\u804a<\u50da<\u7597<\u71ce<\u5be5<\u8fbd<\u6f66" + "<\u4e86<\u6482<\u9563<\u5ed6<\u6599<\u5217<\u88c2" + "<\u70c8<\u52a3<\u730e<\u7433<\u6797<\u78f7<\u9716" + "<\u4e34<\u90bb<\u9cde<\u6dcb<\u51db<\u8d41<\u541d" + "<\u62ce<\u73b2<\u83f1<\u96f6<\u9f84<\u94c3<\u4f36" + "<\u7f9a<\u51cc<\u7075<\u9675<\u5cad<\u9886<\u53e6" + "<\u4ee4<\u6e9c<\u7409<\u69b4<\u786b<\u998f<\u7559" + "<\u5218<\u7624<\u6d41<\u67f3<\u516d<\u9f99<\u804b" + "<\u5499<\u7b3c<\u7abf<\u9686<\u5784<\u62e2<\u9647" + "<\u697c<\u5a04<\u6402<\u7bd3<\u6f0f<\u964b<\u82a6" + "<\u5362<\u9885<\u5e90<\u7089<\u63b3<\u5364<\u864f" + "<\u9c81<\u9e93<\u788c<\u9732<\u8def<\u8d42<\u9e7f" + "<\u6f5e<\u7984<\u5f55<\u9646<\u622e<\u9a74<\u5415" + "<\u94dd<\u4fa3<\u65c5<\u5c65<\u5c61<\u7f15<\u8651" + "<\u6c2f<\u5f8b<\u7387<\u6ee4<\u7eff<\u5ce6<\u631b" + "<\u5b6a<\u6ee6<\u5375<\u4e71<\u63a0<\u7565<\u62a1" + "<\u8f6e<\u4f26<\u4ed1<\u6ca6<\u7eb6<\u8bba<\u841d" + "<\u87ba<\u7f57<\u903b<\u9523<\u7ba9<\u9aa1<\u88f8" + "<\u843d<\u6d1b<\u9a86<\u7edc<\u5988<\u9ebb<\u739b" + "<\u7801<\u8682<\u9a6c<\u9a82<\u561b<\u5417<\u57cb" + "<\u4e70<\u9ea6<\u5356<\u8fc8<\u8109<\u7792<\u9992" + "<\u86ee<\u6ee1<\u8513<\u66fc<\u6162<\u6f2b<\u8c29" + "<\u8292<\u832b<\u76f2<\u6c13<\u5fd9<\u83bd<\u732b" + "<\u8305<\u951a<\u6bdb<\u77db<\u94c6<\u536f<\u8302" + "<\u5192<\u5e3d<\u8c8c<\u8d38<\u4e48<\u73ab<\u679a" + "<\u6885<\u9176<\u9709<\u7164<\u6ca1<\u7709<\u5a92" + "<\u9541<\u6bcf<\u7f8e<\u6627<\u5bd0<\u59b9<\u5a9a" + "<\u95e8<\u95f7<\u4eec<\u840c<\u8499<\u6aac<\u76df" + "<\u9530<\u731b<\u68a6<\u5b5f<\u772f<\u919a<\u9761" + "<\u7cdc<\u8ff7<\u8c1c<\u5f25<\u7c73<\u79d8<\u89c5" + "<\u6ccc<\u871c<\u5bc6<\u5e42<\u68c9<\u7720<\u7ef5" + "<\u5195<\u514d<\u52c9<\u5a29<\u7f05<\u9762<\u82d7" + "<\u63cf<\u7784<\u85d0<\u79d2<\u6e3a<\u5e99<\u5999" + "<\u8511<\u706d<\u6c11<\u62bf<\u76bf<\u654f<\u60af" + "<\u95fd<\u660e<\u879f<\u9e23<\u94ed<\u540d<\u547d" + "<\u8c2c<\u6478<\u6479<\u8611<\u6a21<\u819c<\u78e8" + "<\u6469<\u9b54<\u62b9<\u672b<\u83ab<\u58a8<\u9ed8" + "<\u6cab<\u6f20<\u5bde<\u964c<\u8c0b<\u725f<\u67d0" + "<\u62c7<\u7261<\u4ea9<\u59c6<\u6bcd<\u5893<\u66ae" + "<\u5e55<\u52df<\u6155<\u6728<\u76ee<\u7766<\u7267" + "<\u7a46<\u62ff<\u54ea<\u5450<\u94a0<\u90a3<\u5a1c" + "<\u7eb3<\u6c16<\u4e43<\u5976<\u8010<\u5948<\u5357" + "<\u7537<\u96be<\u56ca<\u6320<\u8111<\u607c<\u95f9" + "<\u6dd6<\u5462<\u9981<\u5185<\u5ae9<\u80fd<\u59ae" + "<\u9713<\u502a<\u6ce5<\u5c3c<\u62df<\u4f60<\u533f" + "<\u817b<\u9006<\u6eba<\u852b<\u62c8<\u5e74<\u78be" + "<\u64b5<\u637b<\u5ff5<\u5a18<\u917f<\u9e1f<\u5c3f" + "<\u634f<\u8042<\u5b7d<\u556e<\u954a<\u954d<\u6d85" + "<\u60a8<\u67e0<\u72de<\u51dd<\u5b81<\u62e7<\u6cde" + "<\u725b<\u626d<\u94ae<\u7ebd<\u8113<\u6d53<\u519c" + "<\u5f04<\u5974<\u52aa<\u6012<\u5973<\u6696<\u8650" + "<\u759f<\u632a<\u61e6<\u7cef<\u8bfa<\u54e6<\u6b27" + "<\u9e25<\u6bb4<\u85d5<\u5455<\u5076<\u6ca4<\u556a" + "<\u8db4<\u722c<\u5e15<\u6015<\u7436<\u62cd<\u6392" + "<\u724c<\u5f98<\u6e43<\u6d3e<\u6500<\u6f58<\u76d8" + "<\u78d0<\u76fc<\u7554<\u5224<\u53db<\u4e53<\u5e9e" + "<\u65c1<\u802a<\u80d6<\u629b<\u5486<\u5228<\u70ae" + "<\u888d<\u8dd1<\u6ce1<\u5478<\u80da<\u57f9<\u88f4" + "<\u8d54<\u966a<\u914d<\u4f69<\u6c9b<\u55b7<\u76c6" + "<\u7830<\u62a8<\u70f9<\u6f8e<\u5f6d<\u84ec<\u68da" + "<\u787c<\u7bf7<\u81a8<\u670b<\u9e4f<\u6367<\u78b0" + "<\u576f<\u7812<\u9739<\u6279<\u62ab<\u5288<\u7435" + "<\u6bd7<\u5564<\u813e<\u75b2<\u76ae<\u5339<\u75de" + "<\u50fb<\u5c41<\u8b6c<\u7bc7<\u504f<\u7247<\u9a97" + "<\u98d8<\u6f02<\u74e2<\u7968<\u6487<\u77a5<\u62fc" + "<\u9891<\u8d2b<\u54c1<\u8058<\u4e52<\u576a<\u82f9" + "<\u840d<\u5e73<\u51ed<\u74f6<\u8bc4<\u5c4f<\u5761" + "<\u6cfc<\u9887<\u5a46<\u7834<\u9b44<\u8feb<\u7c95" + "<\u5256<\u6251<\u94fa<\u4ec6<\u8386<\u8461<\u83e9" + "<\u84b2<\u57d4<\u6734<\u5703<\u666e<\u6d66<\u8c31" + "<\u66dd<\u7011<\u671f<\u6b3a<\u6816<\u621a<\u59bb" + "<\u4e03<\u51c4<\u6f06<\u67d2<\u6c8f<\u5176<\u68cb" + "<\u5947<\u6b67<\u7566<\u5d0e<\u8110<\u9f50<\u65d7" + "<\u7948<\u7941<\u9a91<\u8d77<\u5c82<\u4e5e<\u4f01" + "<\u542f<\u5951<\u780c<\u5668<\u6c14<\u8fc4<\u5f03" + "<\u6c7d<\u6ce3<\u8bab<\u6390<\u6070<\u6d3d<\u7275" + "<\u6266<\u948e<\u94c5<\u5343<\u8fc1<\u7b7e<\u4edf" + "<\u8c26<\u4e7e<\u9ed4<\u94b1<\u94b3<\u524d<\u6f5c" + "<\u9063<\u6d45<\u8c34<\u5811<\u5d4c<\u6b20<\u6b49" + "<\u67aa<\u545b<\u8154<\u7f8c<\u5899<\u8537<\u5f3a" + "<\u62a2<\u6a47<\u9539<\u6572<\u6084<\u6865<\u77a7" + "<\u4e54<\u4fa8<\u5de7<\u9798<\u64ac<\u7fd8<\u5ced" + "<\u4fcf<\u7a8d<\u5207<\u8304<\u4e14<\u602f<\u7a83" + "<\u94a6<\u4fb5<\u4eb2<\u79e6<\u7434<\u52e4<\u82b9" + "<\u64d2<\u79bd<\u5bdd<\u6c81<\u9752<\u8f7b<\u6c22" + "<\u503e<\u537f<\u6e05<\u64ce<\u6674<\u6c30<\u60c5" + "<\u9877<\u8bf7<\u5e86<\u743c<\u7a77<\u79cb<\u4e18" + "<\u90b1<\u7403<\u6c42<\u56da<\u914b<\u6cc5<\u8d8b" + "<\u533a<\u86c6<\u66f2<\u8eaf<\u5c48<\u9a71<\u6e20" + "<\u53d6<\u5a36<\u9f8b<\u8da3<\u53bb<\u5708<\u98a7" + "<\u6743<\u919b<\u6cc9<\u5168<\u75ca<\u62f3<\u72ac" + "<\u5238<\u529d<\u7f3a<\u7094<\u7638<\u5374<\u9e4a" + "<\u69b7<\u786e<\u96c0<\u88d9<\u7fa4<\u7136<\u71c3" + "<\u5189<\u67d3<\u74e4<\u58e4<\u6518<\u56b7<\u8ba9" + "<\u9976<\u6270<\u7ed5<\u60f9<\u70ed<\u58ec<\u4ec1" + "<\u4eba<\u5fcd<\u97e7<\u4efb<\u8ba4<\u5203<\u598a" + "<\u7eab<\u6254<\u4ecd<\u65e5<\u620e<\u8338<\u84c9" + "<\u8363<\u878d<\u7194<\u6eb6<\u5bb9<\u7ed2<\u5197" + "<\u63c9<\u67d4<\u8089<\u8339<\u8815<\u5112<\u5b7a" + "<\u5982<\u8fb1<\u4e73<\u6c5d<\u5165<\u8925<\u8f6f" + "<\u962e<\u854a<\u745e<\u9510<\u95f0<\u6da6<\u82e5" + "<\u5f31<\u6492<\u6d12<\u8428<\u816e<\u9cc3<\u585e" + "<\u8d5b<\u4e09<\u53c1<\u4f1e<\u6563<\u6851<\u55d3" + "<\u4e27<\u6414<\u9a9a<\u626b<\u5ac2<\u745f<\u8272" + "<\u6da9<\u68ee<\u50e7<\u838e<\u7802<\u6740<\u5239" + "<\u6c99<\u7eb1<\u50bb<\u5565<\u715e<\u7b5b<\u6652" + "<\u73ca<\u82eb<\u6749<\u5c71<\u5220<\u717d<\u886b" + "<\u95ea<\u9655<\u64c5<\u8d61<\u81b3<\u5584<\u6c55" + "<\u6247<\u7f2e<\u5892<\u4f24<\u5546<\u8d4f<\u664c" + "<\u4e0a<\u5c1a<\u88f3<\u68a2<\u634e<\u7a0d<\u70e7" + "<\u828d<\u52fa<\u97f6<\u5c11<\u54e8<\u90b5<\u7ecd" + "<\u5962<\u8d4a<\u86c7<\u820c<\u820d<\u8d66<\u6444" + "<\u5c04<\u6151<\u6d89<\u793e<\u8bbe<\u7837<\u7533" + "<\u547b<\u4f38<\u8eab<\u6df1<\u5a20<\u7ec5<\u795e" + "<\u6c88<\u5ba1<\u5a76<\u751a<\u80be<\u614e<\u6e17" + "<\u58f0<\u751f<\u7525<\u7272<\u5347<\u7ef3<\u7701" + "<\u76db<\u5269<\u80dc<\u5723<\u5e08<\u5931<\u72ee" + "<\u65bd<\u6e7f<\u8bd7<\u5c38<\u8671<\u5341<\u77f3" + "<\u62fe<\u65f6<\u4ec0<\u98df<\u8680<\u5b9e<\u8bc6" + "<\u53f2<\u77e2<\u4f7f<\u5c4e<\u9a76<\u59cb<\u5f0f" + "<\u793a<\u58eb<\u4e16<\u67ff<\u4e8b<\u62ed<\u8a93" + "<\u901d<\u52bf<\u662f<\u55dc<\u566c<\u9002<\u4ed5" + "<\u4f8d<\u91ca<\u9970<\u6c0f<\u5e02<\u6043<\u5ba4" + "<\u89c6<\u8bd5<\u6536<\u624b<\u9996<\u5b88<\u5bff" + "<\u6388<\u552e<\u53d7<\u7626<\u517d<\u852c<\u67a2" + "<\u68b3<\u6b8a<\u6292<\u8f93<\u53d4<\u8212<\u6dd1" + "<\u758f<\u4e66<\u8d4e<\u5b70<\u719f<\u85af<\u6691" + "<\u66d9<\u7f72<\u8700<\u9ecd<\u9f20<\u5c5e<\u672f" + "<\u8ff0<\u6811<\u675f<\u620d<\u7ad6<\u5885<\u5eb6" + "<\u6570<\u6f31<\u6055<\u5237<\u800d<\u6454<\u8870" + "<\u7529<\u5e05<\u6813<\u62f4<\u971c<\u53cc<\u723d" + "<\u8c01<\u6c34<\u7761<\u7a0e<\u542e<\u77ac<\u987a" + "<\u821c<\u8bf4<\u7855<\u6714<\u70c1<\u65af<\u6495" + "<\u5636<\u601d<\u79c1<\u53f8<\u4e1d<\u6b7b<\u8086" + "<\u5bfa<\u55e3<\u56db<\u4f3a<\u4f3c<\u9972<\u5df3" + "<\u677e<\u8038<\u6002<\u9882<\u9001<\u5b8b<\u8bbc" + "<\u8bf5<\u641c<\u8258<\u64de<\u55fd<\u82cf<\u9165" + "<\u4fd7<\u7d20<\u901f<\u7c9f<\u50f3<\u5851<\u6eaf" + "<\u5bbf<\u8bc9<\u8083<\u9178<\u849c<\u7b97<\u867d" + "<\u968b<\u968f<\u7ee5<\u9ad3<\u788e<\u5c81<\u7a57" + "<\u9042<\u96a7<\u795f<\u5b59<\u635f<\u7b0b<\u84d1" + "<\u68ad<\u5506<\u7f29<\u7410<\u7d22<\u9501<\u6240" + "<\u584c<\u4ed6<\u5b83<\u5979<\u5854<\u736d<\u631e" + "<\u8e4b<\u8e0f<\u80ce<\u82d4<\u62ac<\u53f0<\u6cf0" + "<\u915e<\u592a<\u6001<\u6c70<\u574d<\u644a<\u8d2a" + "<\u762b<\u6ee9<\u575b<\u6a80<\u75f0<\u6f6d<\u8c2d" + "<\u8c08<\u5766<\u6bef<\u8892<\u78b3<\u63a2<\u53f9" + "<\u70ad<\u6c64<\u5858<\u642a<\u5802<\u68e0<\u819b" + "<\u5510<\u7cd6<\u5018<\u8eba<\u6dcc<\u8d9f<\u70eb" + "<\u638f<\u6d9b<\u6ed4<\u7ee6<\u8404<\u6843<\u9003" + "<\u6dd8<\u9676<\u8ba8<\u5957<\u7279<\u85e4<\u817e" + "<\u75bc<\u8a8a<\u68af<\u5254<\u8e22<\u9511<\u63d0" + "<\u9898<\u8e44<\u557c<\u4f53<\u66ff<\u568f<\u60d5" + "<\u6d95<\u5243<\u5c49<\u5929<\u6dfb<\u586b<\u7530" + "<\u751c<\u606c<\u8214<\u8146<\u6311<\u6761<\u8fe2" + "<\u773a<\u8df3<\u8d34<\u94c1<\u5e16<\u5385<\u542c" + "<\u70c3<\u6c40<\u5ef7<\u505c<\u4ead<\u5ead<\u633a" + "<\u8247<\u901a<\u6850<\u916e<\u77b3<\u540c<\u94dc" + "<\u5f64<\u7ae5<\u6876<\u6345<\u7b52<\u7edf<\u75db" + "<\u5077<\u6295<\u5934<\u900f<\u51f8<\u79c3<\u7a81" + "<\u56fe<\u5f92<\u9014<\u6d82<\u5c60<\u571f<\u5410" + "<\u5154<\u6e4d<\u56e2<\u63a8<\u9893<\u817f<\u8715" + "<\u892a<\u9000<\u541e<\u5c6f<\u81c0<\u62d6<\u6258" + "<\u8131<\u9e35<\u9640<\u9a6e<\u9a7c<\u692d<\u59a5" + "<\u62d3<\u553e<\u6316<\u54c7<\u86d9<\u6d3c<\u5a03" + "<\u74e6<\u889c<\u6b6a<\u5916<\u8c4c<\u5f2f<\u6e7e" + "<\u73a9<\u987d<\u4e38<\u70f7<\u5b8c<\u7897<\u633d" + "<\u665a<\u7696<\u60cb<\u5b9b<\u5a49<\u4e07<\u8155" + "<\u6c6a<\u738b<\u4ea1<\u6789<\u7f51<\u5f80<\u65fa" + "<\u671b<\u5fd8<\u5984<\u5a01<\u5dcd<\u5fae<\u5371" + "<\u97e6<\u8fdd<\u6845<\u56f4<\u552f<\u60df<\u4e3a" + "<\u6f4d<\u7ef4<\u82c7<\u840e<\u59d4<\u4f1f<\u4f2a" + "<\u5c3e<\u7eac<\u672a<\u851a<\u5473<\u754f<\u80c3" + "<\u5582<\u9b4f<\u4f4d<\u6e2d<\u8c13<\u5c09<\u6170" + "<\u536b<\u761f<\u6e29<\u868a<\u6587<\u95fb<\u7eb9" + "<\u543b<\u7a33<\u7d0a<\u95ee<\u55e1<\u7fc1<\u74ee" + "<\u631d<\u8717<\u6da1<\u7a9d<\u6211<\u65a1<\u5367" + "<\u63e1<\u6c83<\u5deb<\u545c<\u94a8<\u4e4c<\u6c61" + "<\u8bec<\u5c4b<\u65e0<\u829c<\u68a7<\u543e<\u5434" + "<\u6bcb<\u6b66<\u4e94<\u6342<\u5348<\u821e<\u4f0d" + "<\u4fae<\u575e<\u620a<\u96fe<\u6664<\u7269<\u52ff" + "<\u52a1<\u609f<\u8bef<\u6614<\u7199<\u6790<\u897f" + "<\u7852<\u77fd<\u6670<\u563b<\u5438<\u9521<\u727a" + "<\u7a00<\u606f<\u5e0c<\u6089<\u819d<\u5915<\u60dc" + "<\u7184<\u70ef<\u6eaa<\u6c50<\u7280<\u6a84<\u88ad" + "<\u5e2d<\u4e60<\u5ab3<\u559c<\u94e3<\u6d17<\u7cfb" + "<\u9699<\u620f<\u7ec6<\u778e<\u867e<\u5323<\u971e" + "<\u8f96<\u6687<\u5ce1<\u4fa0<\u72ed<\u4e0b<\u53a6" + "<\u590f<\u5413<\u6380<\u9528<\u5148<\u4ed9<\u9c9c" + "<\u7ea4<\u54b8<\u8d24<\u8854<\u8237<\u95f2<\u6d8e" + "<\u5f26<\u5acc<\u663e<\u9669<\u73b0<\u732e<\u53bf" + "<\u817a<\u9985<\u7fa1<\u5baa<\u9677<\u9650<\u7ebf" + "<\u76f8<\u53a2<\u9576<\u9999<\u7bb1<\u8944<\u6e58" + "<\u4e61<\u7fd4<\u7965<\u8be6<\u60f3<\u54cd<\u4eab" + "<\u9879<\u5df7<\u6a61<\u50cf<\u5411<\u8c61<\u8427" + "<\u785d<\u9704<\u524a<\u54ee<\u56a3<\u9500<\u6d88" + "<\u5bb5<\u6dc6<\u6653<\u5c0f<\u5b5d<\u6821<\u8096" + "<\u5578<\u7b11<\u6548<\u6954<\u4e9b<\u6b47<\u874e" + "<\u978b<\u534f<\u631f<\u643a<\u90aa<\u659c<\u80c1" + "<\u8c10<\u5199<\u68b0<\u5378<\u87f9<\u61c8<\u6cc4" + "<\u6cfb<\u8c22<\u5c51<\u85aa<\u82af<\u950c<\u6b23" + "<\u8f9b<\u65b0<\u5ffb<\u5fc3<\u4fe1<\u8845<\u661f" + "<\u8165<\u7329<\u60fa<\u5174<\u5211<\u578b<\u5f62" + "<\u90a2<\u884c<\u9192<\u5e78<\u674f<\u6027<\u59d3" + "<\u5144<\u51f6<\u80f8<\u5308<\u6c79<\u96c4<\u718a" + "<\u4f11<\u4fee<\u7f9e<\u673d<\u55c5<\u9508<\u79c0" + "<\u8896<\u7ee3<\u589f<\u620c<\u9700<\u865a<\u5618" + "<\u987b<\u5f90<\u8bb8<\u84c4<\u9157<\u53d9<\u65ed" + "<\u5e8f<\u755c<\u6064<\u7d6e<\u5a7f<\u7eea<\u7eed" + "<\u8f69<\u55a7<\u5ba3<\u60ac<\u65cb<\u7384<\u9009" + "<\u7663<\u7729<\u7eda<\u9774<\u859b<\u5b66<\u7a74" + "<\u96ea<\u8840<\u52cb<\u718f<\u5faa<\u65ec<\u8be2" + "<\u5bfb<\u9a6f<\u5de1<\u6b89<\u6c5b<\u8bad<\u8baf" + "<\u900a<\u8fc5<\u538b<\u62bc<\u9e26<\u9e2d<\u5440" + "<\u4e2b<\u82bd<\u7259<\u869c<\u5d16<\u8859<\u6daf" + "<\u96c5<\u54d1<\u4e9a<\u8bb6<\u7109<\u54bd<\u9609" + "<\u70df<\u6df9<\u76d0<\u4e25<\u7814<\u8712<\u5ca9" + "<\u5ef6<\u8a00<\u989c<\u960e<\u708e<\u6cbf<\u5944" + "<\u63a9<\u773c<\u884d<\u6f14<\u8273<\u5830<\u71d5" + "<\u538c<\u781a<\u96c1<\u5501<\u5f66<\u7130<\u5bb4" + "<\u8c1a<\u9a8c<\u6b83<\u592e<\u9e2f<\u79e7<\u6768" + "<\u626c<\u4f6f<\u75a1<\u7f8a<\u6d0b<\u9633<\u6c27" + "<\u4ef0<\u75d2<\u517b<\u6837<\u6f3e<\u9080<\u8170" + "<\u5996<\u7476<\u6447<\u5c27<\u9065<\u7a91<\u8c23" + "<\u59da<\u54ac<\u8200<\u836f<\u8981<\u8000<\u6930" + "<\u564e<\u8036<\u7237<\u91ce<\u51b6<\u4e5f<\u9875" + "<\u6396<\u4e1a<\u53f6<\u66f3<\u814b<\u591c<\u6db2" + "<\u4e00<\u58f9<\u533b<\u63d6<\u94f1<\u4f9d<\u4f0a" + "<\u8863<\u9890<\u5937<\u9057<\u79fb<\u4eea<\u80f0" + "<\u7591<\u6c82<\u5b9c<\u59e8<\u5f5d<\u6905<\u8681" + "<\u501a<\u5df2<\u4e59<\u77e3<\u4ee5<\u827a<\u6291" + "<\u6613<\u9091<\u5c79<\u4ebf<\u5f79<\u81c6<\u9038" + "<\u8084<\u75ab<\u4ea6<\u88d4<\u610f<\u6bc5<\u5fc6" + "<\u4e49<\u76ca<\u6ea2<\u8be3<\u8bae<\u8c0a<\u8bd1" + "<\u5f02<\u7ffc<\u7fcc<\u7ece<\u8335<\u836b<\u56e0" + "<\u6bb7<\u97f3<\u9634<\u59fb<\u541f<\u94f6<\u6deb" + "<\u5bc5<\u996e<\u5c39<\u5f15<\u9690<\u5370<\u82f1" + "<\u6a31<\u5a74<\u9e70<\u5e94<\u7f28<\u83b9<\u8424" + "<\u8425<\u8367<\u8747<\u8fce<\u8d62<\u76c8<\u5f71" + "<\u9896<\u786c<\u6620<\u54df<\u62e5<\u4f63<\u81c3" + "<\u75c8<\u5eb8<\u96cd<\u8e0a<\u86f9<\u548f<\u6cf3" + "<\u6d8c<\u6c38<\u607f<\u52c7<\u7528<\u5e7d<\u4f18" + "<\u60a0<\u5fe7<\u5c24<\u7531<\u90ae<\u94c0<\u72b9" + "<\u6cb9<\u6e38<\u9149<\u6709<\u53cb<\u53f3<\u4f51" + "<\u91c9<\u8bf1<\u53c8<\u5e7c<\u8fc2<\u6de4<\u4e8e" + "<\u76c2<\u6986<\u865e<\u611a<\u8206<\u4f59<\u4fde" + "<\u903e<\u9c7c<\u6109<\u6e1d<\u6e14<\u9685<\u4e88" + "<\u5a31<\u96e8<\u4e0e<\u5c7f<\u79b9<\u5b87<\u8bed" + "<\u7fbd<\u7389<\u57df<\u828b<\u90c1<\u5401<\u9047" + "<\u55bb<\u5cea<\u5fa1<\u6108<\u6b32<\u72f1<\u80b2" + "<\u8a89<\u6d74<\u5bd3<\u88d5<\u9884<\u8c6b<\u9a6d" + "<\u9e33<\u6e0a<\u51a4<\u5143<\u57a3<\u8881<\u539f" + "<\u63f4<\u8f95<\u56ed<\u5458<\u5706<\u733f<\u6e90" + "<\u7f18<\u8fdc<\u82d1<\u613f<\u6028<\u9662<\u66f0" + "<\u7ea6<\u8d8a<\u8dc3<\u94a5<\u5cb3<\u7ca4<\u6708" + "<\u60a6<\u9605<\u8018<\u4e91<\u90e7<\u5300<\u9668" + "<\u5141<\u8fd0<\u8574<\u915d<\u6655<\u97f5<\u5b55" + "<\u531d<\u7838<\u6742<\u683d<\u54c9<\u707e<\u5bb0" + "<\u8f7d<\u518d<\u5728<\u54b1<\u6512<\u6682<\u8d5e" + "<\u8d43<\u810f<\u846c<\u906d<\u7cdf<\u51ff<\u85fb" + "<\u67a3<\u65e9<\u6fa1<\u86a4<\u8e81<\u566a<\u9020" + "<\u7682<\u7076<\u71e5<\u8d23<\u62e9<\u5219<\u6cfd" + "<\u8d3c<\u600e<\u589e<\u618e<\u66fe<\u8d60<\u624e" + "<\u55b3<\u6e23<\u672d<\u8f67<\u94e1<\u95f8<\u7728" + "<\u6805<\u69a8<\u548b<\u4e4d<\u70b8<\u8bc8<\u6458" + "<\u658b<\u5b85<\u7a84<\u503a<\u5be8<\u77bb<\u6be1" + "<\u8a79<\u7c98<\u6cbe<\u76cf<\u65a9<\u8f97<\u5d2d" + "<\u5c55<\u8638<\u6808<\u5360<\u6218<\u7ad9<\u6e5b" + "<\u7efd<\u6a1f<\u7ae0<\u5f70<\u6f33<\u5f20<\u638c" + "<\u6da8<\u6756<\u4e08<\u5e10<\u8d26<\u4ed7<\u80c0" + "<\u7634<\u969c<\u62db<\u662d<\u627e<\u6cbc<\u8d75" + "<\u7167<\u7f69<\u5146<\u8087<\u53ec<\u906e<\u6298" + "<\u54f2<\u86f0<\u8f99<\u8005<\u9517<\u8517<\u8fd9" + "<\u6d59<\u73cd<\u659f<\u771f<\u7504<\u7827<\u81fb" + "<\u8d1e<\u9488<\u4fa6<\u6795<\u75b9<\u8bca<\u9707" + "<\u632f<\u9547<\u9635<\u84b8<\u6323<\u7741<\u5f81" + "<\u72f0<\u4e89<\u6014<\u6574<\u62ef<\u6b63<\u653f" + "<\u5e27<\u75c7<\u90d1<\u8bc1<\u829d<\u679d<\u652f" + "<\u5431<\u8718<\u77e5<\u80a2<\u8102<\u6c41<\u4e4b" + "<\u7ec7<\u804c<\u76f4<\u690d<\u6b96<\u6267<\u503c" + "<\u4f84<\u5740<\u6307<\u6b62<\u8dbe<\u53ea<\u65e8" + "<\u7eb8<\u5fd7<\u631a<\u63b7<\u81f3<\u81f4<\u7f6e" + "<\u5e1c<\u5cd9<\u5236<\u667a<\u79e9<\u7a1a<\u8d28" + "<\u7099<\u75d4<\u6ede<\u6cbb<\u7a92<\u4e2d<\u76c5" + "<\u5fe0<\u949f<\u8877<\u7ec8<\u79cd<\u80bf<\u91cd" + "<\u4ef2<\u4f17<\u821f<\u5468<\u5dde<\u6d32<\u8bcc" + "<\u7ca5<\u8f74<\u8098<\u5e1a<\u5492<\u76b1<\u5b99" + "<\u663c<\u9aa4<\u73e0<\u682a<\u86db<\u6731<\u732a" + "<\u8bf8<\u8bdb<\u9010<\u7af9<\u70db<\u716e<\u62c4" + "<\u77a9<\u5631<\u4e3b<\u8457<\u67f1<\u52a9<\u86c0" + "<\u8d2e<\u94f8<\u7b51<\u4f4f<\u6ce8<\u795d<\u9a7b" + "<\u6293<\u722a<\u62fd<\u4e13<\u7816<\u8f6c<\u64b0" + "<\u8d5a<\u7bc6<\u6869<\u5e84<\u88c5<\u5986<\u649e" + "<\u58ee<\u72b6<\u690e<\u9525<\u8ffd<\u8d58<\u5760" + "<\u7f00<\u8c06<\u51c6<\u6349<\u62d9<\u5353<\u684c" + "<\u7422<\u8301<\u914c<\u5544<\u7740<\u707c<\u6d4a" + "<\u5179<\u54a8<\u8d44<\u59ff<\u6ecb<\u6dc4<\u5b5c" + "<\u7d2b<\u4ed4<\u7c7d<\u6ed3<\u5b50<\u81ea<\u6e0d" + "<\u5b57<\u9b03<\u68d5<\u8e2a<\u5b97<\u7efc<\u603b" + "<\u7eb5<\u90b9<\u8d70<\u594f<\u63cd<\u79df<\u8db3" + "<\u5352<\u65cf<\u7956<\u8bc5<\u963b<\u7ec4<\u94bb" + "<\u7e82<\u5634<\u9189<\u6700<\u7f6a<\u5c0a<\u9075" + "<\u6628<\u5de6<\u4f50<\u67de<\u505a<\u4f5c<\u5750" + "<\u5ea7<\ue2d8<\ue2d9<\ue2da<\ue2db<\ue2dc<\u4e8d" + "<\u4e0c<\u5140<\u4e10<\u5eff<\u5345<\u4e15<\u4e98" + "<\u4e1e<\u9b32<\u5b6c<\u5669<\u4e28<\u79ba<\u4e3f" + "<\u5315<\u4e47<\u592d<\u723b<\u536e<\u6c10<\u56df" + "<\u80e4<\u9997<\u6bd3<\u777e<\u9f17<\u4e36<\u4e9f" + "<\u9f10<\u4e5c<\u4e69<\u4e93<\u8288<\u5b5b<\u556c" + "<\u560f<\u4ec4<\u538d<\u539d<\u53a3<\u53a5<\u53ae" + "<\u9765<\u8d5d<\u531a<\u53f5<\u5326<\u532e<\u533e" + "<\u8d5c<\u5366<\u5363<\u5202<\u5208<\u520e<\u522d" + "<\u5233<\u523f<\u5240<\u524c<\u525e<\u5261<\u525c" + "<\u84af<\u527d<\u5282<\u5281<\u5290<\u5293<\u5182" + "<\u7f54<\u4ebb<\u4ec3<\u4ec9<\u4ec2<\u4ee8<\u4ee1" + "<\u4eeb<\u4ede<\u4f1b<\u4ef3<\u4f22<\u4f64<\u4ef5" + "<\u4f25<\u4f27<\u4f09<\u4f2b<\u4f5e<\u4f67<\u6538" + "<\u4f5a<\u4f5d<\u4f5f<\u4f57<\u4f32<\u4f3d<\u4f76" + "<\u4f74<\u4f91<\u4f89<\u4f83<\u4f8f<\u4f7e<\u4f7b" + "<\u4faa<\u4f7c<\u4fac<\u4f94<\u4fe6<\u4fe8<\u4fea" + "<\u4fc5<\u4fda<\u4fe3<\u4fdc<\u4fd1<\u4fdf<\u4ff8" + "<\u5029<\u504c<\u4ff3<\u502c<\u500f<\u502e<\u502d" + "<\u4ffe<\u501c<\u500c<\u5025<\u5028<\u507e<\u5043" + "<\u5055<\u5048<\u504e<\u506c<\u507b<\u50a5<\u50a7" + "<\u50a9<\u50ba<\u50d6<\u5106<\u50ed<\u50ec<\u50e6" + "<\u50ee<\u5107<\u510b<\u4edd<\u6c3d<\u4f58<\u4f65" + "<\u4fce<\u9fa0<\u6c46<\u7c74<\u516e<\u5dfd<\u9ec9" + "<\u9998<\u5181<\u5914<\u52f9<\u530d<\u8a07<\u5310" + "<\u51eb<\u5919<\u5155<\u4ea0<\u5156<\u4eb3<\u886e" + "<\u88a4<\u4eb5<\u8114<\u88d2<\u7980<\u5b34<\u8803" + "<\u7fb8<\u51ab<\u51b1<\u51bd<\u51bc<\u51c7<\u5196" + "<\u51a2<\u51a5<\u8ba0<\u8ba6<\u8ba7<\u8baa<\u8bb4" + "<\u8bb5<\u8bb7<\u8bc2<\u8bc3<\u8bcb<\u8bcf<\u8bce" + "<\u8bd2<\u8bd3<\u8bd4<\u8bd6<\u8bd8<\u8bd9<\u8bdc" + "<\u8bdf<\u8be0<\u8be4<\u8be8<\u8be9<\u8bee<\u8bf0" + "<\u8bf3<\u8bf6<\u8bf9<\u8bfc<\u8bff<\u8c00<\u8c02" + "<\u8c04<\u8c07<\u8c0c<\u8c0f<\u8c11<\u8c12<\u8c14" + "<\u8c15<\u8c16<\u8c19<\u8c1b<\u8c18<\u8c1d<\u8c1f" + "<\u8c20<\u8c21<\u8c25<\u8c27<\u8c2a<\u8c2b<\u8c2e" + "<\u8c2f<\u8c32<\u8c33<\u8c35<\u8c36<\u5369<\u537a" + "<\u961d<\u9622<\u9621<\u9631<\u962a<\u963d<\u963c" + "<\u9642<\u9649<\u9654<\u965f<\u9667<\u966c<\u9672" + "<\u9674<\u9688<\u968d<\u9697<\u96b0<\u9097<\u909b" + "<\u909d<\u9099<\u90ac<\u90a1<\u90b4<\u90b3<\u90b6" + "<\u90ba<\u90b8<\u90b0<\u90cf<\u90c5<\u90be<\u90d0" + "<\u90c4<\u90c7<\u90d3<\u90e6<\u90e2<\u90dc<\u90d7" + "<\u90db<\u90eb<\u90ef<\u90fe<\u9104<\u9122<\u911e" + "<\u9123<\u9131<\u912f<\u9139<\u9143<\u9146<\u520d" + "<\u5942<\u52a2<\u52ac<\u52ad<\u52be<\u54ff<\u52d0" + "<\u52d6<\u52f0<\u53df<\u71ee<\u77cd<\u5ef4<\u51f5" + "<\u51fc<\u9b2f<\u53b6<\u5f01<\u755a<\u5def<\u574c" + "<\u57a9<\u57a1<\u587e<\u58bc<\u58c5<\u58d1<\u5729" + "<\u572c<\u572a<\u5733<\u5739<\u572e<\u572f<\u575c" + "<\u573b<\u5742<\u5769<\u5785<\u576b<\u5786<\u577c" + "<\u577b<\u5768<\u576d<\u5776<\u5773<\u57ad<\u57a4" + "<\u578c<\u57b2<\u57cf<\u57a7<\u57b4<\u5793<\u57a0" + "<\u57d5<\u57d8<\u57da<\u57d9<\u57d2<\u57b8<\u57f4" + "<\u57ef<\u57f8<\u57e4<\u57dd<\u580b<\u580d<\u57fd" + "<\u57ed<\u5800<\u581e<\u5819<\u5844<\u5820<\u5865" + "<\u586c<\u5881<\u5889<\u589a<\u5880<\u99a8<\u9f19" + "<\u61ff<\u8279<\u827d<\u827f<\u828f<\u828a<\u82a8" + "<\u8284<\u828e<\u8291<\u8297<\u8299<\u82ab<\u82b8" + "<\u82be<\u82b0<\u82c8<\u82ca<\u82e3<\u8298<\u82b7" + "<\u82ae<\u82cb<\u82cc<\u82c1<\u82a9<\u82b4<\u82a1" + "<\u82aa<\u829f<\u82c4<\u82ce<\u82a4<\u82e1<\u8309" + "<\u82f7<\u82e4<\u830f<\u8307<\u82dc<\u82f4<\u82d2" + "<\u82d8<\u830c<\u82fb<\u82d3<\u8311<\u831a<\u8306" + "<\u8314<\u8315<\u82e0<\u82d5<\u831c<\u8351<\u835b" + "<\u835c<\u8308<\u8392<\u833c<\u8334<\u8331<\u839b" + "<\u835e<\u832f<\u834f<\u8347<\u8343<\u835f<\u8340" + "<\u8317<\u8360<\u832d<\u833a<\u8333<\u8366<\u8365" + "<\u8368<\u831b<\u8369<\u836c<\u836a<\u836d<\u836e" + "<\u83b0<\u8378<\u83b3<\u83b4<\u83a0<\u83aa<\u8393" + "<\u839c<\u8385<\u837c<\u83b6<\u83a9<\u837d<\u83b8" + "<\u837b<\u8398<\u839e<\u83a8<\u83ba<\u83bc<\u83c1" + "<\u8401<\u83e5<\u83d8<\u5807<\u8418<\u840b<\u83dd" + "<\u83fd<\u83d6<\u841c<\u8438<\u8411<\u8406<\u83d4" + "<\u83df<\u840f<\u8403<\u83f8<\u83f9<\u83ea<\u83c5" + "<\u83c0<\u8426<\u83f0<\u83e1<\u845c<\u8451<\u845a" + "<\u8459<\u8473<\u8487<\u8488<\u847a<\u8489<\u8478" + "<\u843c<\u8446<\u8469<\u8476<\u848c<\u848e<\u8431" + "<\u846d<\u84c1<\u84cd<\u84d0<\u84e6<\u84bd<\u84d3" + "<\u84ca<\u84bf<\u84ba<\u84e0<\u84a1<\u84b9<\u84b4" + "<\u8497<\u84e5<\u84e3<\u850c<\u750d<\u8538<\u84f0" + "<\u8539<\u851f<\u853a<\u8556<\u853b<\u84ff<\u84fc" + "<\u8559<\u8548<\u8568<\u8564<\u855e<\u857a<\u77a2" + "<\u8543<\u8572<\u857b<\u85a4<\u85a8<\u8587<\u858f" + "<\u8579<\u85ae<\u859c<\u8585<\u85b9<\u85b7<\u85b0" + "<\u85d3<\u85c1<\u85dc<\u85ff<\u8627<\u8605<\u8629" + "<\u8616<\u863c<\u5efe<\u5f08<\u593c<\u5941<\u8037" + "<\u5955<\u595a<\u5958<\u530f<\u5c22<\u5c25<\u5c2c" + "<\u5c34<\u624c<\u626a<\u629f<\u62bb<\u62ca<\u62da" + "<\u62d7<\u62ee<\u6322<\u62f6<\u6339<\u634b<\u6343" + "<\u63ad<\u63f6<\u6371<\u637a<\u638e<\u63b4<\u636d" + "<\u63ac<\u638a<\u6369<\u63ae<\u63bc<\u63f2<\u63f8" + "<\u63e0<\u63ff<\u63c4<\u63de<\u63ce<\u6452<\u63c6" + "<\u63be<\u6445<\u6441<\u640b<\u641b<\u6420<\u640c" + "<\u6426<\u6421<\u645e<\u6484<\u646d<\u6496<\u647a" + "<\u64b7<\u64b8<\u6499<\u64ba<\u64c0<\u64d0<\u64d7" + "<\u64e4<\u64e2<\u6509<\u6525<\u652e<\u5f0b<\u5fd2" + "<\u7519<\u5f11<\u535f<\u53f1<\u53fd<\u53e9<\u53e8" + "<\u53fb<\u5412<\u5416<\u5406<\u544b<\u5452<\u5453" + "<\u5454<\u5456<\u5443<\u5421<\u5457<\u5459<\u5423" + "<\u5432<\u5482<\u5494<\u5477<\u5471<\u5464<\u549a" + "<\u549b<\u5484<\u5476<\u5466<\u549d<\u54d0<\u54ad" + "<\u54c2<\u54b4<\u54d2<\u54a7<\u54a6<\u54d3<\u54d4" + "<\u5472<\u54a3<\u54d5<\u54bb<\u54bf<\u54cc<\u54d9" + "<\u54da<\u54dc<\u54a9<\u54aa<\u54a4<\u54dd<\u54cf" + "<\u54de<\u551b<\u54e7<\u5520<\u54fd<\u5514<\u54f3" + "<\u5522<\u5523<\u550f<\u5511<\u5527<\u552a<\u5567" + "<\u558f<\u55b5<\u5549<\u556d<\u5541<\u5555<\u553f" + "<\u5550<\u553c<\u5537<\u5556<\u5575<\u5576<\u5577" + "<\u5533<\u5530<\u555c<\u558b<\u55d2<\u5583<\u55b1" + "<\u55b9<\u5588<\u5581<\u559f<\u557e<\u55d6<\u5591" + "<\u557b<\u55df<\u55bd<\u55be<\u5594<\u5599<\u55ea" + "<\u55f7<\u55c9<\u561f<\u55d1<\u55eb<\u55ec<\u55d4" + "<\u55e6<\u55dd<\u55c4<\u55ef<\u55e5<\u55f2<\u55f3" + "<\u55cc<\u55cd<\u55e8<\u55f5<\u55e4<\u8f94<\u561e" + "<\u5608<\u560c<\u5601<\u5624<\u5623<\u55fe<\u5600" + "<\u5627<\u562d<\u5658<\u5639<\u5657<\u562c<\u564d" + "<\u5662<\u5659<\u565c<\u564c<\u5654<\u5686<\u5664" + "<\u5671<\u566b<\u567b<\u567c<\u5685<\u5693<\u56af" + "<\u56d4<\u56d7<\u56dd<\u56e1<\u56f5<\u56eb<\u56f9" + "<\u56ff<\u5704<\u570a<\u5709<\u571c<\u5e0f<\u5e19" + "<\u5e14<\u5e11<\u5e31<\u5e3b<\u5e3c<\u5e37<\u5e44" + "<\u5e54<\u5e5b<\u5e5e<\u5e61<\u5c8c<\u5c7a<\u5c8d" + "<\u5c90<\u5c96<\u5c88<\u5c98<\u5c99<\u5c91<\u5c9a" + "<\u5c9c<\u5cb5<\u5ca2<\u5cbd<\u5cac<\u5cab<\u5cb1" + "<\u5ca3<\u5cc1<\u5cb7<\u5cc4<\u5cd2<\u5ce4<\u5ccb" + "<\u5ce5<\u5d02<\u5d03<\u5d27<\u5d26<\u5d2e<\u5d24" + "<\u5d1e<\u5d06<\u5d1b<\u5d58<\u5d3e<\u5d34<\u5d3d" + "<\u5d6c<\u5d5b<\u5d6f<\u5d5d<\u5d6b<\u5d4b<\u5d4a" + "<\u5d69<\u5d74<\u5d82<\u5d99<\u5d9d<\u8c73<\u5db7" + "<\u5dc5<\u5f73<\u5f77<\u5f82<\u5f87<\u5f89<\u5f8c" + "<\u5f95<\u5f99<\u5f9c<\u5fa8<\u5fad<\u5fb5<\u5fbc" + "<\u8862<\u5f61<\u72ad<\u72b0<\u72b4<\u72b7<\u72b8" + "<\u72c3<\u72c1<\u72ce<\u72cd<\u72d2<\u72e8<\u72ef" + "<\u72e9<\u72f2<\u72f4<\u72f7<\u7301<\u72f3<\u7303" + "<\u72fa<\u72fb<\u7317<\u7313<\u7321<\u730a<\u731e" + "<\u731d<\u7315<\u7322<\u7339<\u7325<\u732c<\u7338" + "<\u7331<\u7350<\u734d<\u7357<\u7360<\u736c<\u736f" + "<\u737e<\u821b<\u5925<\u98e7<\u5924<\u5902<\u9963" + "<\u9967<\u9968<\u9969<\u996a<\u996b<\u996c<\u9974" + "<\u9977<\u997d<\u9980<\u9984<\u9987<\u998a<\u998d" + "<\u9990<\u9991<\u9993<\u9994<\u9995<\u5e80<\u5e91" + "<\u5e8b<\u5e96<\u5ea5<\u5ea0<\u5eb9<\u5eb5<\u5ebe" + "<\u5eb3<\u8d53<\u5ed2<\u5ed1<\u5edb<\u5ee8<\u5eea" + "<\u81ba<\u5fc4<\u5fc9<\u5fd6<\u5fcf<\u6003<\u5fee" + "<\u6004<\u5fe1<\u5fe4<\u5ffe<\u6005<\u6006<\u5fea" + "<\u5fed<\u5ff8<\u6019<\u6035<\u6026<\u601b<\u600f" + "<\u600d<\u6029<\u602b<\u600a<\u603f<\u6021<\u6078" + "<\u6079<\u607b<\u607a<\u6042<\u606a<\u607d<\u6096" + "<\u609a<\u60ad<\u609d<\u6083<\u6092<\u608c<\u609b" + "<\u60ec<\u60bb<\u60b1<\u60dd<\u60d8<\u60c6<\u60da" + "<\u60b4<\u6120<\u6126<\u6115<\u6123<\u60f4<\u6100" + "<\u610e<\u612b<\u614a<\u6175<\u61ac<\u6194<\u61a7" + "<\u61b7<\u61d4<\u61f5<\u5fdd<\u96b3<\u95e9<\u95eb" + "<\u95f1<\u95f3<\u95f5<\u95f6<\u95fc<\u95fe<\u9603" + "<\u9604<\u9606<\u9608<\u960a<\u960b<\u960c<\u960d" + "<\u960f<\u9612<\u9615<\u9616<\u9617<\u9619<\u961a" + "<\u4e2c<\u723f<\u6215<\u6c35<\u6c54<\u6c5c<\u6c4a" + "<\u6ca3<\u6c85<\u6c90<\u6c94<\u6c8c<\u6c68<\u6c69" + "<\u6c74<\u6c76<\u6c86<\u6ca9<\u6cd0<\u6cd4<\u6cad" + "<\u6cf7<\u6cf8<\u6cf1<\u6cd7<\u6cb2<\u6ce0<\u6cd6" + "<\u6cfa<\u6ceb<\u6cee<\u6cb1<\u6cd3<\u6cef<\u6cfe" + "<\u6d39<\u6d27<\u6d0c<\u6d43<\u6d48<\u6d07<\u6d04" + "<\u6d19<\u6d0e<\u6d2b<\u6d4d<\u6d2e<\u6d35<\u6d1a" + "<\u6d4f<\u6d52<\u6d54<\u6d33<\u6d91<\u6d6f<\u6d9e" + "<\u6da0<\u6d5e<\u6d93<\u6d94<\u6d5c<\u6d60<\u6d7c" + "<\u6d63<\u6e1a<\u6dc7<\u6dc5<\u6dde<\u6e0e<\u6dbf" + "<\u6de0<\u6e11<\u6de6<\u6ddd<\u6dd9<\u6e16<\u6dab" + "<\u6e0c<\u6dae<\u6e2b<\u6e6e<\u6e4e<\u6e6b<\u6eb2" + "<\u6e5f<\u6e86<\u6e53<\u6e54<\u6e32<\u6e25<\u6e44" + "<\u6edf<\u6eb1<\u6e98<\u6ee0<\u6f2d<\u6ee2<\u6ea5" + "<\u6ea7<\u6ebd<\u6ebb<\u6eb7<\u6ed7<\u6eb4<\u6ecf" + "<\u6e8f<\u6ec2<\u6e9f<\u6f62<\u6f46<\u6f47<\u6f24" + "<\u6f15<\u6ef9<\u6f2f<\u6f36<\u6f4b<\u6f74<\u6f2a" + "<\u6f09<\u6f29<\u6f89<\u6f8d<\u6f8c<\u6f78<\u6f72" + "<\u6f7c<\u6f7a<\u6fd1<\u6fc9<\u6fa7<\u6fb9<\u6fb6" + "<\u6fc2<\u6fe1<\u6fee<\u6fde<\u6fe0<\u6fef<\u701a" + "<\u7023<\u701b<\u7039<\u7035<\u704f<\u705e<\u5b80" + "<\u5b84<\u5b95<\u5b93<\u5ba5<\u5bb8<\u752f<\u9a9e" + "<\u6434<\u5be4<\u5bee<\u8930<\u5bf0<\u8e47<\u8b07" + "<\u8fb6<\u8fd3<\u8fd5<\u8fe5<\u8fee<\u8fe4<\u8fe9" + "<\u8fe6<\u8ff3<\u8fe8<\u9005<\u9004<\u900b<\u9026" + "<\u9011<\u900d<\u9016<\u9021<\u9035<\u9036<\u902d" + "<\u902f<\u9044<\u9051<\u9052<\u9050<\u9068<\u9058" + "<\u9062<\u905b<\u66b9<\u9074<\u907d<\u9082<\u9088" + "<\u9083<\u908b<\u5f50<\u5f57<\u5f56<\u5f58<\u5c3b" + "<\u54ab<\u5c50<\u5c59<\u5b71<\u5c63<\u5c66<\u7fbc" + "<\u5f2a<\u5f29<\u5f2d<\u8274<\u5f3c<\u9b3b<\u5c6e" + "<\u5981<\u5983<\u598d<\u59a9<\u59aa<\u59a3<\u5997" + "<\u59ca<\u59ab<\u599e<\u59a4<\u59d2<\u59b2<\u59af" + "<\u59d7<\u59be<\u5a05<\u5a06<\u59dd<\u5a08<\u59e3" + "<\u59d8<\u59f9<\u5a0c<\u5a09<\u5a32<\u5a34<\u5a11" + "<\u5a23<\u5a13<\u5a40<\u5a67<\u5a4a<\u5a55<\u5a3c" + "<\u5a62<\u5a75<\u80ec<\u5aaa<\u5a9b<\u5a77<\u5a7a" + "<\u5abe<\u5aeb<\u5ab2<\u5ad2<\u5ad4<\u5ab8<\u5ae0" + "<\u5ae3<\u5af1<\u5ad6<\u5ae6<\u5ad8<\u5adc<\u5b09" + "<\u5b17<\u5b16<\u5b32<\u5b37<\u5b40<\u5c15<\u5c1c" + "<\u5b5a<\u5b65<\u5b73<\u5b51<\u5b53<\u5b62<\u9a75" + "<\u9a77<\u9a78<\u9a7a<\u9a7f<\u9a7d<\u9a80<\u9a81" + "<\u9a85<\u9a88<\u9a8a<\u9a90<\u9a92<\u9a93<\u9a96" + "<\u9a98<\u9a9b<\u9a9c<\u9a9d<\u9a9f<\u9aa0<\u9aa2" + "<\u9aa3<\u9aa5<\u9aa7<\u7e9f<\u7ea1<\u7ea3<\u7ea5" + "<\u7ea8<\u7ea9<\u7ead<\u7eb0<\u7ebe<\u7ec0<\u7ec1" + "<\u7ec2<\u7ec9<\u7ecb<\u7ecc<\u7ed0<\u7ed4<\u7ed7" + "<\u7edb<\u7ee0<\u7ee1<\u7ee8<\u7eeb<\u7eee<\u7eef" + "<\u7ef1<\u7ef2<\u7f0d<\u7ef6<\u7efa<\u7efb<\u7efe" + "<\u7f01<\u7f02<\u7f03<\u7f07<\u7f08<\u7f0b<\u7f0c" + "<\u7f0f<\u7f11<\u7f12<\u7f17<\u7f19<\u7f1c<\u7f1b" + "<\u7f1f<\u7f21<\u7f22<\u7f23<\u7f24<\u7f25<\u7f26" + "<\u7f27<\u7f2a<\u7f2b<\u7f2c<\u7f2d<\u7f2f<\u7f30" + "<\u7f31<\u7f32<\u7f33<\u7f35<\u5e7a<\u757f<\u5ddb" + "<\u753e<\u9095<\u738e<\u7391<\u73ae<\u73a2<\u739f" + "<\u73cf<\u73c2<\u73d1<\u73b7<\u73b3<\u73c0<\u73c9" + "<\u73c8<\u73e5<\u73d9<\u987c<\u740a<\u73e9<\u73e7" + "<\u73de<\u73ba<\u73f2<\u740f<\u742a<\u745b<\u7426" + "<\u7425<\u7428<\u7430<\u742e<\u742c<\u741b<\u741a" + "<\u7441<\u745c<\u7457<\u7455<\u7459<\u7477<\u746d" + "<\u747e<\u749c<\u748e<\u7480<\u7481<\u7487<\u748b" + "<\u749e<\u74a8<\u74a9<\u7490<\u74a7<\u74d2<\u74ba" + "<\u97ea<\u97eb<\u97ec<\u674c<\u6753<\u675e<\u6748" + "<\u6769<\u67a5<\u6787<\u676a<\u6773<\u6798<\u67a7" + "<\u6775<\u67a8<\u679e<\u67ad<\u678b<\u6777<\u677c" + "<\u67f0<\u6809<\u67d8<\u680a<\u67e9<\u67b0<\u680c" + "<\u67d9<\u67b5<\u67da<\u67b3<\u67dd<\u6800<\u67c3" + "<\u67b8<\u67e2<\u680e<\u67c1<\u67fd<\u6832<\u6833" + "<\u6860<\u6861<\u684e<\u6862<\u6844<\u6864<\u6883" + "<\u681d<\u6855<\u6866<\u6841<\u6867<\u6840<\u683e" + "<\u684a<\u6849<\u6829<\u68b5<\u688f<\u6874<\u6877" + "<\u6893<\u686b<\u68c2<\u696e<\u68fc<\u691f<\u6920" + "<\u68f9<\u6924<\u68f0<\u690b<\u6901<\u6957<\u68e3" + "<\u6910<\u6971<\u6939<\u6960<\u6942<\u695d<\u6984" + "<\u696b<\u6980<\u6998<\u6978<\u6934<\u69cc<\u6987" + "<\u6988<\u69ce<\u6989<\u6966<\u6963<\u6979<\u699b" + "<\u69a7<\u69bb<\u69ab<\u69ad<\u69d4<\u69b1<\u69c1" + "<\u69ca<\u69df<\u6995<\u69e0<\u698d<\u69ff<\u6a2f" + "<\u69ed<\u6a17<\u6a18<\u6a65<\u69f2<\u6a44<\u6a3e" + "<\u6aa0<\u6a50<\u6a5b<\u6a35<\u6a8e<\u6a79<\u6a3d" + "<\u6a28<\u6a58<\u6a7c<\u6a91<\u6a90<\u6aa9<\u6a97" + "<\u6aab<\u7337<\u7352<\u6b81<\u6b82<\u6b87<\u6b84" + "<\u6b92<\u6b93<\u6b8d<\u6b9a<\u6b9b<\u6ba1<\u6baa" + "<\u8f6b<\u8f6d<\u8f71<\u8f72<\u8f73<\u8f75<\u8f76" + "<\u8f78<\u8f77<\u8f79<\u8f7a<\u8f7c<\u8f7e<\u8f81" + "<\u8f82<\u8f84<\u8f87<\u8f8b<\u8f8d<\u8f8e<\u8f8f" + "<\u8f98<\u8f9a<\u8ece<\u620b<\u6217<\u621b<\u621f" + "<\u6222<\u6221<\u6225<\u6224<\u622c<\u81e7<\u74ef" + "<\u74f4<\u74ff<\u750f<\u7511<\u7513<\u6534<\u65ee" + "<\u65ef<\u65f0<\u660a<\u6619<\u6772<\u6603<\u6615" + "<\u6600<\u7085<\u66f7<\u661d<\u6634<\u6631<\u6636" + "<\u6635<\u8006<\u665f<\u6654<\u6641<\u664f<\u6656" + "<\u6661<\u6657<\u6677<\u6684<\u668c<\u66a7<\u669d" + "<\u66be<\u66db<\u66dc<\u66e6<\u66e9<\u8d32<\u8d33" + "<\u8d36<\u8d3b<\u8d3d<\u8d40<\u8d45<\u8d46<\u8d48" + "<\u8d49<\u8d47<\u8d4d<\u8d55<\u8d59<\u89c7<\u89ca" + "<\u89cb<\u89cc<\u89ce<\u89cf<\u89d0<\u89d1<\u726e" + "<\u729f<\u725d<\u7266<\u726f<\u727e<\u727f<\u7284" + "<\u728b<\u728d<\u728f<\u7292<\u6308<\u6332<\u63b0" + "<\u643f<\u64d8<\u8004<\u6bea<\u6bf3<\u6bfd<\u6bf5" + "<\u6bf9<\u6c05<\u6c07<\u6c06<\u6c0d<\u6c15<\u6c18" + "<\u6c19<\u6c1a<\u6c21<\u6c29<\u6c24<\u6c2a<\u6c32" + "<\u6535<\u6555<\u656b<\u724d<\u7252<\u7256<\u7230" + "<\u8662<\u5216<\u809f<\u809c<\u8093<\u80bc<\u670a" + "<\u80bd<\u80b1<\u80ab<\u80ad<\u80b4<\u80b7<\u80e7" + "<\u80e8<\u80e9<\u80ea<\u80db<\u80c2<\u80c4<\u80d9" + "<\u80cd<\u80d7<\u6710<\u80dd<\u80eb<\u80f1<\u80f4" + "<\u80ed<\u810d<\u810e<\u80f2<\u80fc<\u6715<\u8112" + "<\u8c5a<\u8136<\u811e<\u812c<\u8118<\u8132<\u8148" + "<\u814c<\u8153<\u8174<\u8159<\u815a<\u8171<\u8160" + "<\u8169<\u817c<\u817d<\u816d<\u8167<\u584d<\u5ab5" + "<\u8188<\u8182<\u8191<\u6ed5<\u81a3<\u81aa<\u81cc" + "<\u6726<\u81ca<\u81bb<\u81c1<\u81a6<\u6b24<\u6b37" + "<\u6b39<\u6b43<\u6b46<\u6b59<\u98d1<\u98d2<\u98d3" + "<\u98d5<\u98d9<\u98da<\u6bb3<\u5f40<\u6bc2<\u89f3" + "<\u6590<\u9f51<\u6593<\u65bc<\u65c6<\u65c4<\u65c3" + "<\u65cc<\u65ce<\u65d2<\u65d6<\u7080<\u709c<\u7096" + "<\u709d<\u70bb<\u70c0<\u70b7<\u70ab<\u70b1<\u70e8" + "<\u70ca<\u7110<\u7113<\u7116<\u712f<\u7131<\u7173" + "<\u715c<\u7168<\u7145<\u7172<\u714a<\u7178<\u717a" + "<\u7198<\u71b3<\u71b5<\u71a8<\u71a0<\u71e0<\u71d4" + "<\u71e7<\u71f9<\u721d<\u7228<\u706c<\u7118<\u7166" + "<\u71b9<\u623e<\u623d<\u6243<\u6248<\u6249<\u793b" + "<\u7940<\u7946<\u7949<\u795b<\u795c<\u7953<\u795a" + "<\u7962<\u7957<\u7960<\u796f<\u7967<\u797a<\u7985" + "<\u798a<\u799a<\u79a7<\u79b3<\u5fd1<\u5fd0<\u603c" + "<\u605d<\u605a<\u6067<\u6041<\u6059<\u6063<\u60ab" + "<\u6106<\u610d<\u615d<\u61a9<\u619d<\u61cb<\u61d1" + "<\u6206<\u8080<\u807f<\u6c93<\u6cf6<\u6dfc<\u77f6" + "<\u77f8<\u7800<\u7809<\u7817<\u7818<\u7811<\u65ab" + "<\u782d<\u781c<\u781d<\u7839<\u783a<\u783b<\u781f" + "<\u783c<\u7825<\u782c<\u7823<\u7829<\u784e<\u786d" + "<\u7856<\u7857<\u7826<\u7850<\u7847<\u784c<\u786a" + "<\u789b<\u7893<\u789a<\u7887<\u789c<\u78a1<\u78a3" + "<\u78b2<\u78b9<\u78a5<\u78d4<\u78d9<\u78c9<\u78ec" + "<\u78f2<\u7905<\u78f4<\u7913<\u7924<\u791e<\u7934" + "<\u9f9b<\u9ef9<\u9efb<\u9efc<\u76f1<\u7704<\u770d" + "<\u76f9<\u7707<\u7708<\u771a<\u7722<\u7719<\u772d" + "<\u7726<\u7735<\u7738<\u7750<\u7751<\u7747<\u7743" + "<\u775a<\u7768<\u7762<\u7765<\u777f<\u778d<\u777d" + "<\u7780<\u778c<\u7791<\u779f<\u77a0<\u77b0<\u77b5" + "<\u77bd<\u753a<\u7540<\u754e<\u754b<\u7548<\u755b" + "<\u7572<\u7579<\u7583<\u7f58<\u7f61<\u7f5f<\u8a48" + "<\u7f68<\u7f74<\u7f71<\u7f79<\u7f81<\u7f7e<\u76cd" + "<\u76e5<\u8832<\u9485<\u9486<\u9487<\u948b<\u948a" + "<\u948c<\u948d<\u948f<\u9490<\u9494<\u9497<\u9495" + "<\u949a<\u949b<\u949c<\u94a3<\u94a4<\u94ab<\u94aa" + "<\u94ad<\u94ac<\u94af<\u94b0<\u94b2<\u94b4<\u94b6" + "<\u94b7<\u94b8<\u94b9<\u94ba<\u94bc<\u94bd<\u94bf" + "<\u94c4<\u94c8<\u94c9<\u94ca<\u94cb<\u94cc<\u94cd" + "<\u94ce<\u94d0<\u94d1<\u94d2<\u94d5<\u94d6<\u94d7" + "<\u94d9<\u94d8<\u94db<\u94de<\u94df<\u94e0<\u94e2" + "<\u94e4<\u94e5<\u94e7<\u94e8<\u94ea<\u94e9<\u94eb" + "<\u94ee<\u94ef<\u94f3<\u94f4<\u94f5<\u94f7<\u94f9" + "<\u94fc<\u94fd<\u94ff<\u9503<\u9502<\u9506<\u9507" + "<\u9509<\u950a<\u950d<\u950e<\u950f<\u9512<\u9513" + "<\u9514<\u9515<\u9516<\u9518<\u951b<\u951d<\u951e" + "<\u951f<\u9522<\u952a<\u952b<\u9529<\u952c<\u9531" + "<\u9532<\u9534<\u9536<\u9537<\u9538<\u953c<\u953e" + "<\u953f<\u9542<\u9535<\u9544<\u9545<\u9546<\u9549" + "<\u954c<\u954e<\u954f<\u9552<\u9553<\u9554<\u9556" + "<\u9557<\u9558<\u9559<\u955b<\u955e<\u955f<\u955d" + "<\u9561<\u9562<\u9564<\u9565<\u9566<\u9567<\u9568" + "<\u9569<\u956a<\u956b<\u956c<\u956f<\u9571<\u9572" + "<\u9573<\u953a<\u77e7<\u77ec<\u96c9<\u79d5<\u79ed" + "<\u79e3<\u79eb<\u7a06<\u5d47<\u7a03<\u7a02<\u7a1e" + "<\u7a14<\u7a39<\u7a37<\u7a51<\u9ecf<\u99a5<\u7a70" + "<\u7688<\u768e<\u7693<\u7699<\u76a4<\u74de<\u74e0" + "<\u752c<\u9e20<\u9e22<\u9e28<\u9e29<\u9e2a<\u9e2b" + "<\u9e2c<\u9e32<\u9e31<\u9e36<\u9e38<\u9e37<\u9e39" + "<\u9e3a<\u9e3e<\u9e41<\u9e42<\u9e44<\u9e46<\u9e47" + "<\u9e48<\u9e49<\u9e4b<\u9e4c<\u9e4e<\u9e51<\u9e55" + "<\u9e57<\u9e5a<\u9e5b<\u9e5c<\u9e5e<\u9e63<\u9e66" + "<\u9e67<\u9e68<\u9e69<\u9e6a<\u9e6b<\u9e6c<\u9e71" + "<\u9e6d<\u9e73<\u7592<\u7594<\u7596<\u75a0<\u759d" + "<\u75ac<\u75a3<\u75b3<\u75b4<\u75b8<\u75c4<\u75b1" + "<\u75b0<\u75c3<\u75c2<\u75d6<\u75cd<\u75e3<\u75e8" + "<\u75e6<\u75e4<\u75eb<\u75e7<\u7603<\u75f1<\u75fc" + "<\u75ff<\u7610<\u7600<\u7605<\u760c<\u7617<\u760a" + "<\u7625<\u7618<\u7615<\u7619<\u761b<\u763c<\u7622" + "<\u7620<\u7640<\u762d<\u7630<\u763f<\u7635<\u7643" + "<\u763e<\u7633<\u764d<\u765e<\u7654<\u765c<\u7656" + "<\u766b<\u766f<\u7fca<\u7ae6<\u7a78<\u7a79<\u7a80" + "<\u7a86<\u7a88<\u7a95<\u7aa6<\u7aa0<\u7aac<\u7aa8" + "<\u7aad<\u7ab3<\u8864<\u8869<\u8872<\u887d<\u887f" + "<\u8882<\u88a2<\u88c6<\u88b7<\u88bc<\u88c9<\u88e2" + "<\u88ce<\u88e3<\u88e5<\u88f1<\u891a<\u88fc<\u88e8" + "<\u88fe<\u88f0<\u8921<\u8919<\u8913<\u891b<\u890a" + "<\u8934<\u892b<\u8936<\u8941<\u8966<\u897b<\u758b" + "<\u80e5<\u76b2<\u76b4<\u77dc<\u8012<\u8014<\u8016" + "<\u801c<\u8020<\u8022<\u8025<\u8026<\u8027<\u8029" + "<\u8028<\u8031<\u800b<\u8035<\u8043<\u8046<\u804d" + "<\u8052<\u8069<\u8071<\u8983<\u9878<\u9880<\u9883" + "<\u9889<\u988c<\u988d<\u988f<\u9894<\u989a<\u989b" + "<\u989e<\u989f<\u98a1<\u98a2<\u98a5<\u98a6<\u864d" + "<\u8654<\u866c<\u866e<\u867f<\u867a<\u867c<\u867b" + "<\u86a8<\u868d<\u868b<\u86ac<\u869d<\u86a7<\u86a3" + "<\u86aa<\u8693<\u86a9<\u86b6<\u86c4<\u86b5<\u86ce" + "<\u86b0<\u86ba<\u86b1<\u86af<\u86c9<\u86cf<\u86b4" + "<\u86e9<\u86f1<\u86f2<\u86ed<\u86f3<\u86d0<\u8713" + "<\u86de<\u86f4<\u86df<\u86d8<\u86d1<\u8703<\u8707" + "<\u86f8<\u8708<\u870a<\u870d<\u8709<\u8723<\u873b" + "<\u871e<\u8725<\u872e<\u871a<\u873e<\u8748<\u8734" + "<\u8731<\u8729<\u8737<\u873f<\u8782<\u8722<\u877d" + "<\u877e<\u877b<\u8760<\u8770<\u874c<\u876e<\u878b" + "<\u8753<\u8763<\u877c<\u8764<\u8759<\u8765<\u8793" + "<\u87af<\u87a8<\u87d2<\u87c6<\u8788<\u8785<\u87ad" + "<\u8797<\u8783<\u87ab<\u87e5<\u87ac<\u87b5<\u87b3" + "<\u87cb<\u87d3<\u87bd<\u87d1<\u87c0<\u87ca<\u87db" + "<\u87ea<\u87e0<\u87ee<\u8816<\u8813<\u87fe<\u880a" + "<\u881b<\u8821<\u8839<\u883c<\u7f36<\u7f42<\u7f44" + "<\u7f45<\u8210<\u7afa<\u7afd<\u7b08<\u7b03<\u7b04" + "<\u7b15<\u7b0a<\u7b2b<\u7b0f<\u7b47<\u7b38<\u7b2a" + "<\u7b19<\u7b2e<\u7b31<\u7b20<\u7b25<\u7b24<\u7b33" + "<\u7b3e<\u7b1e<\u7b58<\u7b5a<\u7b45<\u7b75<\u7b4c" + "<\u7b5d<\u7b60<\u7b6e<\u7b7b<\u7b62<\u7b72<\u7b71" + "<\u7b90<\u7ba6<\u7ba7<\u7bb8<\u7bac<\u7b9d<\u7ba8" + "<\u7b85<\u7baa<\u7b9c<\u7ba2<\u7bab<\u7bb4<\u7bd1" + "<\u7bc1<\u7bcc<\u7bdd<\u7bda<\u7be5<\u7be6<\u7bea" + "<\u7c0c<\u7bfe<\u7bfc<\u7c0f<\u7c16<\u7c0b<\u7c1f" + "<\u7c2a<\u7c26<\u7c38<\u7c41<\u7c40<\u81fe<\u8201" + "<\u8202<\u8204<\u81ec<\u8844<\u8221<\u8222<\u8223" + "<\u822d<\u822f<\u8228<\u822b<\u8238<\u823b<\u8233" + "<\u8234<\u823e<\u8244<\u8249<\u824b<\u824f<\u825a" + "<\u825f<\u8268<\u887e<\u8885<\u8888<\u88d8<\u88df" + "<\u895e<\u7f9d<\u7f9f<\u7fa7<\u7faf<\u7fb0<\u7fb2" + "<\u7c7c<\u6549<\u7c91<\u7c9d<\u7c9c<\u7c9e<\u7ca2" + "<\u7cb2<\u7cbc<\u7cbd<\u7cc1<\u7cc7<\u7ccc<\u7ccd" + "<\u7cc8<\u7cc5<\u7cd7<\u7ce8<\u826e<\u66a8<\u7fbf" + "<\u7fce<\u7fd5<\u7fe5<\u7fe1<\u7fe6<\u7fe9<\u7fee" + "<\u7ff3<\u7cf8<\u7d77<\u7da6<\u7dae<\u7e47<\u7e9b" + "<\u9eb8<\u9eb4<\u8d73<\u8d84<\u8d94<\u8d91<\u8db1" + "<\u8d67<\u8d6d<\u8c47<\u8c49<\u914a<\u9150<\u914e" + "<\u914f<\u9164<\u9162<\u9161<\u9170<\u9169<\u916f" + "<\u917d<\u917e<\u9172<\u9174<\u9179<\u918c<\u9185" + "<\u9190<\u918d<\u9191<\u91a2<\u91a3<\u91aa<\u91ad" + "<\u91ae<\u91af<\u91b5<\u91b4<\u91ba<\u8c55<\u9e7e" + "<\u8db8<\u8deb<\u8e05<\u8e59<\u8e69<\u8db5<\u8dbf" + "<\u8dbc<\u8dba<\u8dc4<\u8dd6<\u8dd7<\u8dda<\u8dde" + "<\u8dce<\u8dcf<\u8ddb<\u8dc6<\u8dec<\u8df7<\u8df8" + "<\u8de3<\u8df9<\u8dfb<\u8de4<\u8e09<\u8dfd<\u8e14" + "<\u8e1d<\u8e1f<\u8e2c<\u8e2e<\u8e23<\u8e2f<\u8e3a" + "<\u8e40<\u8e39<\u8e35<\u8e3d<\u8e31<\u8e49<\u8e41" + "<\u8e42<\u8e51<\u8e52<\u8e4a<\u8e70<\u8e76<\u8e7c" + "<\u8e6f<\u8e74<\u8e85<\u8e8f<\u8e94<\u8e90<\u8e9c" + "<\u8e9e<\u8c78<\u8c82<\u8c8a<\u8c85<\u8c98<\u8c94" + "<\u659b<\u89d6<\u89de<\u89da<\u89dc<\u89e5<\u89eb" + "<\u89ef<\u8a3e<\u8b26<\u9753<\u96e9<\u96f3<\u96ef" + "<\u9706<\u9701<\u9708<\u970f<\u970e<\u972a<\u972d" + "<\u9730<\u973e<\u9f80<\u9f83<\u9f85<\u9f86<\u9f87" + "<\u9f88<\u9f89<\u9f8a<\u9f8c<\u9efe<\u9f0b<\u9f0d" + "<\u96b9<\u96bc<\u96bd<\u96ce<\u96d2<\u77bf<\u96e0" + "<\u928e<\u92ae<\u92c8<\u933e<\u936a<\u93ca<\u938f" + "<\u943e<\u946b<\u9c7f<\u9c82<\u9c85<\u9c86<\u9c87" + "<\u9c88<\u7a23<\u9c8b<\u9c8e<\u9c90<\u9c91<\u9c92" + "<\u9c94<\u9c95<\u9c9a<\u9c9b<\u9c9e<\u9c9f<\u9ca0" + "<\u9ca1<\u9ca2<\u9ca3<\u9ca5<\u9ca6<\u9ca7<\u9ca8" + "<\u9ca9<\u9cab<\u9cad<\u9cae<\u9cb0<\u9cb1<\u9cb2" + "<\u9cb3<\u9cb4<\u9cb5<\u9cb6<\u9cb7<\u9cba<\u9cbb" + "<\u9cbc<\u9cbd<\u9cc4<\u9cc5<\u9cc6<\u9cc7<\u9cca" + "<\u9ccb<\u9ccc<\u9ccd<\u9cce<\u9ccf<\u9cd0<\u9cd3" + "<\u9cd4<\u9cd5<\u9cd7<\u9cd8<\u9cd9<\u9cdc<\u9cdd" + "<\u9cdf<\u9ce2<\u977c<\u9785<\u9791<\u9792<\u9794" + "<\u97af<\u97ab<\u97a3<\u97b2<\u97b4<\u9ab1<\u9ab0" + "<\u9ab7<\u9e58<\u9ab6<\u9aba<\u9abc<\u9ac1<\u9ac0" + "<\u9ac5<\u9ac2<\u9acb<\u9acc<\u9ad1<\u9b45<\u9b43" + "<\u9b47<\u9b49<\u9b48<\u9b4d<\u9b51<\u98e8<\u990d" + "<\u992e<\u9955<\u9954<\u9adf<\u9ae1<\u9ae6<\u9aef" + "<\u9aeb<\u9afb<\u9aed<\u9af9<\u9b08<\u9b0f<\u9b13" + "<\u9b1f<\u9b23<\u9ebd<\u9ebe<\u7e3b<\u9e82<\u9e87" + "<\u9e88<\u9e8b<\u9e92<\u93d6<\u9e9d<\u9e9f<\u9edb" + "<\u9edc<\u9edd<\u9ee0<\u9edf<\u9ee2<\u9ee9<\u9ee7" + "<\u9ee5<\u9eea<\u9eef<\u9f22<\u9f2c<\u9f2f<\u9f39" + "<\u9f37<\u9f3d<\u9f3e<\u9f44" } }; } }
rokn/Count_Words_2015
testing/openjdk/jdk/src/share/classes/sun/text/resources/CollationData_zh.java
Java
mit
77,384
/* * Copyright (c) 2000, 2008, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * */ package bench.rmi; import bench.ConfigFormatException; import bench.Harness; import bench.HtmlReporter; import bench.Reporter; import bench.TextReporter; import bench.XmlReporter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.rmi.RemoteException; import java.rmi.RMISecurityManager; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.RemoteObject; import java.util.Timer; import java.util.TimerTask; /* * RMI/Serialization benchmark tests. */ public class Main { /** * RMI-specific benchmark harness. */ static class RMIHarness extends Harness { /** * Construct new RMI benchmark harness. */ RMIHarness(InputStream in) throws IOException, ConfigFormatException { super(in); } /** * Cleanup both client and server side in between each benchmark. */ protected void cleanup() { System.gc(); if (Main.runmode == CLIENT) { try { Main.server.gc(); } catch (Exception e) { System.err.println("Warning: server gc failed: " + e); } } } } static final String CONFFILE = "/bench/rmi/config"; static final String VERSION = "1.3"; static final String REGNAME = "server"; static final int SAMEVM = 0; static final int CLIENT = 1; static final int SERVER = 2; static final int TEXT = 0; static final int HTML = 1; static final int XML = 2; static boolean verbose; static boolean list; static boolean exitOnTimer; static int testDurationSeconds; static volatile boolean exitRequested; static Timer timer; static int format = TEXT; static int runmode; static InputStream confstr; static OutputStream repstr; static String host; static int port; static RMIHarness harness; static Reporter reporter; static BenchServer server; static BenchServerImpl serverImpl; /** * Returns reference to benchmark server. */ public static BenchServer getBenchServer() { return server; } /** * Prints help message. */ static void usage() { PrintStream p = System.err; p.println("\nUsage: java -jar rmibench.jar [-options]"); p.println("\nwhere options are:"); p.println(" -h print this message"); p.println(" -v verbose mode"); p.println(" -l list configuration file"); p.println(" -t <num hours> repeat benchmarks for specified number of hours"); p.println(" -o <file> specify output file"); p.println(" -c <file> specify (non-default) " + "configuration file"); p.println(" -html format output as html " + "(default is text)"); p.println(" -xml format output as xml"); p.println(" -client <host:port> run benchmark client using server " + "on specified host/port"); p.println(" -server <port> run benchmark server on given port"); } /** * Print error message and exit. */ static void die(String mesg) { System.err.println(mesg); System.exit(1); } /** * Stop server and exit. */ public static void exit() { switch (runmode) { case CLIENT: if (server != null) { try { server.terminate(0); } catch (RemoteException re) { // ignore } } default: System.exit(0); } } /** * Benchmark mainline. */ public static void main(String[] args) { setupSecurity(); parseArgs(args); setupStreams(); if (list) { listConfig(); } else { setupServer(); if (runmode != SERVER) { setupHarness(); setupReporter(); if (exitOnTimer) { setupTimer(testDurationSeconds); while (true) { runBenchmarks(); if (exitRequested) { exit(); } } } else { runBenchmarks(); exit(); } } } } /** * Parse command-line arguments. */ static void parseArgs(String[] args) { for (int i = 0; i < args.length; i++) { if (args[i].equals("-h")) { usage(); System.exit(0); } else if (args[i].equals("-v")) { verbose = true; } else if (args[i].equals("-l")) { list = true; } else if (args[i].equals("-t")) { if (++i >= args.length) die("Error: no timeout value specified"); try { exitOnTimer = true; testDurationSeconds = Integer.parseInt(args[i]) * 3600; } catch (Exception e) { die("Error: unable to determine timeout value"); } } else if (args[i].equals("-o")) { if (++i >= args.length) die("Error: no output file specified"); try { repstr = new FileOutputStream(args[i]); } catch (IOException e) { die("Error: unable to open \"" + args[i] + "\""); } } else if (args[i].equals("-c")) { if (++i >= args.length) die("Error: no config file specified"); try { confstr = new FileInputStream(args[i]); } catch (IOException e) { die("Error: unable to open \"" + args[i] + "\""); } } else if (args[i].equals("-html")) { if (format != TEXT) die("Error: conflicting formats"); format = HTML; } else if (args[i].equals("-xml")) { if (format != TEXT) die("Error: conflicting formats"); format = XML; } else if (args[i].equals("-client")) { if (runmode == CLIENT) die("Error: multiple -client options"); if (runmode == SERVER) die("Error: -client and -server options conflict"); if (++i >= args.length) die("Error: -client missing host/port"); try { int sepi = args[i].indexOf(':'); host = args[i].substring(0, sepi); port = Integer.parseInt(args[i].substring(sepi + 1)); } catch (Exception e) { die("Error: illegal host/port specified for -client"); } runmode = CLIENT; } else if (args[i].equals("-server")) { if (runmode == CLIENT) die("Error: -client and -server options conflict"); if (runmode == SERVER) die("Error: multiple -server options"); if (++i >= args.length) die("Error: -server missing port"); try { port = Integer.parseInt(args[i]); } catch (Exception e) { die("Error: illegal port specified for -server"); } runmode = SERVER; } else { System.err.println("Illegal option: \"" + args[i] + "\""); usage(); System.exit(1); } } } /** * Set up security manager and policy, if not set already. */ static void setupSecurity() { if (System.getSecurityManager() != null) return; /* As of 1.4, it is too late to set the security policy * file at this point so these line have been commented out. */ //System.setProperty("java.security.policy", // Main.class.getResource("/bench/rmi/policy.all").toString()); System.setSecurityManager(new RMISecurityManager()); } /** * Set up configuration file and report streams, if not set already. */ static void setupStreams() { if (repstr == null) repstr = System.out; if (confstr == null) confstr = (new Main()).getClass().getResourceAsStream(CONFFILE); if (confstr == null) die("Error: unable to find default config file"); } /** * Print contents of configuration file to selected output stream. */ static void listConfig() { try { byte[] buf = new byte[256]; int len; while ((len = confstr.read(buf)) != -1) repstr.write(buf, 0, len); } catch (IOException e) { die("Error: failed to list config file"); } } /** * Setup benchmark server. */ static void setupServer() { switch (runmode) { case SAMEVM: try { serverImpl = new BenchServerImpl(); server = (BenchServer) RemoteObject.toStub(serverImpl); } catch (Exception e) { die("Error: failed to create local server: " + e); } if (verbose) System.out.println("Benchmark server created locally"); break; case CLIENT: try { Registry reg = LocateRegistry.getRegistry(host, port); server = (BenchServer) reg.lookup(REGNAME); } catch (Exception e) { die("Error: failed to connect to server: " + e); } if (server == null) { die("Error: server not found"); } if (verbose) { System.out.println("Connected to benchmark server on " + host + ":" + port); } break; case SERVER: try { Registry reg = LocateRegistry.createRegistry(port); serverImpl = new BenchServerImpl(); reg.bind(REGNAME, serverImpl); } catch (Exception e) { die("Error: failed to initialize server: " + e); } if (verbose) { System.out.println("Benchmark server started on port " + port); } break; default: throw new InternalError("illegal runmode"); } } /** * Set up the timer to end the test. * * @param delay the amount of delay, in seconds, before requesting * the process exit */ static void setupTimer(int delay) { timer = new Timer(true); timer.schedule( new TimerTask() { public void run() { exitRequested = true; } }, delay * 1000); } /** * Set up benchmark harness. */ static void setupHarness() { try { harness = new RMIHarness(confstr); } catch (ConfigFormatException e) { String errmsg = e.getMessage(); if (errmsg != null) { die("Error parsing config file: " + errmsg); } else { die("Error: illegal config file syntax"); } } catch (IOException e) { die("Error: failed to read config file"); } } /** * Setup benchmark reporter. */ static void setupReporter() { String title = "RMI Benchmark, v" + VERSION; switch (format) { case TEXT: reporter = new TextReporter(repstr, title); break; case HTML: reporter = new HtmlReporter(repstr, title); break; case XML: reporter = new XmlReporter(repstr, title); break; default: die("Error: unrecognized format type"); } } /** * Run benchmarks. */ static void runBenchmarks() { harness.runBenchmarks(reporter, verbose); } }
rokn/Count_Words_2015
testing/openjdk/jdk/test/java/rmi/reliability/benchmark/bench/rmi/Main.java
Java
mit
13,971
/* * 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.facebook.presto.spi; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.type.Type; import io.airlift.slice.Slice; import java.util.Collection; import java.util.List; import java.util.concurrent.CompletableFuture; import static java.util.Objects.requireNonNull; import static java.util.concurrent.CompletableFuture.completedFuture; public class RecordPageSink implements ConnectorPageSink { private final RecordSink recordSink; public RecordPageSink(RecordSink recordSink) { this.recordSink = requireNonNull(recordSink, "recordSink is null"); } @Override public CompletableFuture<Collection<Slice>> finish() { return completedFuture(recordSink.commit()); } @Override public void abort() { recordSink.rollback(); } @Override public CompletableFuture<?> appendPage(Page page) { Block[] blocks = page.getBlocks(); List<Type> columnTypes = recordSink.getColumnTypes(); for (int position = 0; position < page.getPositionCount(); position++) { recordSink.beginRecord(); for (int i = 0; i < blocks.length; i++) { writeField(position, blocks[i], columnTypes.get(i)); } recordSink.finishRecord(); } return NOT_BLOCKED; } private void writeField(int position, Block block, Type type) { if (block.isNull(position)) { recordSink.appendNull(); return; } if (type.getJavaType() == boolean.class) { recordSink.appendBoolean(type.getBoolean(block, position)); } else if (type.getJavaType() == long.class) { recordSink.appendLong(type.getLong(block, position)); } else if (type.getJavaType() == double.class) { recordSink.appendDouble(type.getDouble(block, position)); } else if (type.getJavaType() == Slice.class) { recordSink.appendString(type.getSlice(block, position).getBytes()); } else { recordSink.appendObject(type.getObject(block, position)); } } }
marsorp/blog
presto166/presto-spi/src/main/java/com/facebook/presto/spi/RecordPageSink.java
Java
apache-2.0
2,740
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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 io.undertow.servlet.test.errorpage; /** * @author Stuart Douglas */ public class ParentException extends Exception { }
jasonchaffee/undertow
servlet/src/test/java/io/undertow/servlet/test/errorpage/ParentException.java
Java
apache-2.0
843
// Copyright 2004-present Facebook. All Rights Reserved. package com.facebook.react.uimanager; import javax.annotation.Nullable; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import android.view.View; import com.facebook.common.logging.FLog; import com.facebook.react.bridge.Dynamic; import com.facebook.react.bridge.JSApplicationIllegalArgumentException; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.uimanager.annotations.ReactProp; import com.facebook.react.uimanager.annotations.ReactPropGroup; /** * This class is responsible for holding view manager property setters and is used in a process of * updating views with the new properties set in JS. */ /*package*/ class ViewManagersPropertyCache { private static final Map<Class, Map<String, PropSetter>> CLASS_PROPS_CACHE = new HashMap<>(); private static final Map<String, PropSetter> EMPTY_PROPS_MAP = new HashMap<>(); public static void clear() { CLASS_PROPS_CACHE.clear(); EMPTY_PROPS_MAP.clear(); } /*package*/ static abstract class PropSetter { protected final String mPropName; protected final String mPropType; protected final Method mSetter; protected final @Nullable Integer mIndex; /* non-null only for group setters */ // The following Object arrays are used to prevent extra allocations from varargs when we call // Method.invoke. It's safe for those objects to be static as we update properties in a single // thread sequentially private static final Object[] VIEW_MGR_ARGS = new Object[2]; private static final Object[] VIEW_MGR_GROUP_ARGS = new Object[3]; private static final Object[] SHADOW_ARGS = new Object[1]; private static final Object[] SHADOW_GROUP_ARGS = new Object[2]; private PropSetter(ReactProp prop, String defaultType, Method setter) { mPropName = prop.name(); mPropType = ReactProp.USE_DEFAULT_TYPE.equals(prop.customType()) ? defaultType : prop.customType(); mSetter = setter; mIndex = null; } private PropSetter(ReactPropGroup prop, String defaultType, Method setter, int index) { mPropName = prop.names()[index]; mPropType = ReactPropGroup.USE_DEFAULT_TYPE.equals(prop.customType()) ? defaultType : prop.customType(); mSetter = setter; mIndex = index; } public String getPropName() { return mPropName; } public String getPropType() { return mPropType; } public void updateViewProp( ViewManager viewManager, View viewToUpdate, ReactStylesDiffMap props) { try { if (mIndex == null) { VIEW_MGR_ARGS[0] = viewToUpdate; VIEW_MGR_ARGS[1] = extractProperty(props); mSetter.invoke(viewManager, VIEW_MGR_ARGS); Arrays.fill(VIEW_MGR_ARGS, null); } else { VIEW_MGR_GROUP_ARGS[0] = viewToUpdate; VIEW_MGR_GROUP_ARGS[1] = mIndex; VIEW_MGR_GROUP_ARGS[2] = extractProperty(props); mSetter.invoke(viewManager, VIEW_MGR_GROUP_ARGS); Arrays.fill(VIEW_MGR_GROUP_ARGS, null); } } catch (Throwable t) { FLog.e(ViewManager.class, "Error while updating prop " + mPropName, t); throw new JSApplicationIllegalArgumentException("Error while updating property '" + mPropName + "' of a view managed by: " + viewManager.getName(), t); } } public void updateShadowNodeProp( ReactShadowNode nodeToUpdate, ReactStylesDiffMap props) { try { if (mIndex == null) { SHADOW_ARGS[0] = extractProperty(props); mSetter.invoke(nodeToUpdate, SHADOW_ARGS); Arrays.fill(SHADOW_ARGS, null); } else { SHADOW_GROUP_ARGS[0] = mIndex; SHADOW_GROUP_ARGS[1] = extractProperty(props); mSetter.invoke(nodeToUpdate, SHADOW_GROUP_ARGS); Arrays.fill(SHADOW_GROUP_ARGS, null); } } catch (Throwable t) { FLog.e(ViewManager.class, "Error while updating prop " + mPropName, t); throw new JSApplicationIllegalArgumentException("Error while updating property '" + mPropName + "' in shadow node of type: " + nodeToUpdate.getViewClass(), t); } } protected abstract @Nullable Object extractProperty(ReactStylesDiffMap props); } private static class DynamicPropSetter extends PropSetter { public DynamicPropSetter(ReactProp prop, Method setter) { super(prop, "mixed", setter); } public DynamicPropSetter(ReactPropGroup prop, Method setter, int index) { super(prop, "mixed", setter, index); } @Override protected Object extractProperty(ReactStylesDiffMap props) { return props.getDynamic(mPropName); } } private static class IntPropSetter extends PropSetter { private final int mDefaultValue; public IntPropSetter(ReactProp prop, Method setter, int defaultValue) { super(prop, "number", setter); mDefaultValue = defaultValue; } public IntPropSetter(ReactPropGroup prop, Method setter, int index, int defaultValue) { super(prop, "number", setter, index); mDefaultValue = defaultValue; } @Override protected Object extractProperty(ReactStylesDiffMap props) { return props.getInt(mPropName, mDefaultValue); } } private static class DoublePropSetter extends PropSetter { private final double mDefaultValue; public DoublePropSetter(ReactProp prop, Method setter, double defaultValue) { super(prop, "number", setter); mDefaultValue = defaultValue; } public DoublePropSetter(ReactPropGroup prop, Method setter, int index, double defaultValue) { super(prop, "number", setter, index); mDefaultValue = defaultValue; } @Override protected Object extractProperty(ReactStylesDiffMap props) { return props.getDouble(mPropName, mDefaultValue); } } private static class BooleanPropSetter extends PropSetter { private final boolean mDefaultValue; public BooleanPropSetter(ReactProp prop, Method setter, boolean defaultValue) { super(prop, "boolean", setter); mDefaultValue = defaultValue; } @Override protected Object extractProperty(ReactStylesDiffMap props) { return props.getBoolean(mPropName, mDefaultValue) ? Boolean.TRUE : Boolean.FALSE; } } private static class FloatPropSetter extends PropSetter { private final float mDefaultValue; public FloatPropSetter(ReactProp prop, Method setter, float defaultValue) { super(prop, "number", setter); mDefaultValue = defaultValue; } public FloatPropSetter(ReactPropGroup prop, Method setter, int index, float defaultValue) { super(prop, "number", setter, index); mDefaultValue = defaultValue; } @Override protected Object extractProperty(ReactStylesDiffMap props) { return props.getFloat(mPropName, mDefaultValue); } } private static class ArrayPropSetter extends PropSetter { public ArrayPropSetter(ReactProp prop, Method setter) { super(prop, "Array", setter); } @Override protected @Nullable Object extractProperty(ReactStylesDiffMap props) { return props.getArray(mPropName); } } private static class MapPropSetter extends PropSetter { public MapPropSetter(ReactProp prop, Method setter) { super(prop, "Map", setter); } @Override protected @Nullable Object extractProperty(ReactStylesDiffMap props) { return props.getMap(mPropName); } } private static class StringPropSetter extends PropSetter { public StringPropSetter(ReactProp prop, Method setter) { super(prop, "String", setter); } @Override protected @Nullable Object extractProperty(ReactStylesDiffMap props) { return props.getString(mPropName); } } private static class BoxedBooleanPropSetter extends PropSetter { public BoxedBooleanPropSetter(ReactProp prop, Method setter) { super(prop, "boolean", setter); } @Override protected @Nullable Object extractProperty(ReactStylesDiffMap props) { if (!props.isNull(mPropName)) { return props.getBoolean(mPropName, /* ignored */ false) ? Boolean.TRUE : Boolean.FALSE; } return null; } } private static class BoxedIntPropSetter extends PropSetter { public BoxedIntPropSetter(ReactProp prop, Method setter) { super(prop, "number", setter); } public BoxedIntPropSetter(ReactPropGroup prop, Method setter, int index) { super(prop, "number", setter, index); } @Override protected @Nullable Object extractProperty(ReactStylesDiffMap props) { if (!props.isNull(mPropName)) { return props.getInt(mPropName, /* ignored */ 0); } return null; } } /*package*/ static Map<String, String> getNativePropsForView( Class<? extends ViewManager> viewManagerTopClass, Class<? extends ReactShadowNode> shadowNodeTopClass) { Map<String, String> nativeProps = new HashMap<>(); Map<String, PropSetter> viewManagerProps = getNativePropSettersForViewManagerClass(viewManagerTopClass); for (PropSetter setter : viewManagerProps.values()) { nativeProps.put(setter.getPropName(), setter.getPropType()); } Map<String, PropSetter> shadowNodeProps = getNativePropSettersForShadowNodeClass(shadowNodeTopClass); for (PropSetter setter : shadowNodeProps.values()) { nativeProps.put(setter.getPropName(), setter.getPropType()); } return nativeProps; } /** * Returns map from property name to setter instances for all the property setters annotated with * {@link ReactProp} in the given {@link ViewManager} class plus all the setter declared by its * parent classes. */ /*package*/ static Map<String, PropSetter> getNativePropSettersForViewManagerClass( Class<? extends ViewManager> cls) { if (cls == ViewManager.class) { return EMPTY_PROPS_MAP; } Map<String, PropSetter> props = CLASS_PROPS_CACHE.get(cls); if (props != null) { return props; } // This is to include all the setters from parent classes. Once calculated the result will be // stored in CLASS_PROPS_CACHE so that we only scan for @ReactProp annotations once per class. props = new HashMap<>( getNativePropSettersForViewManagerClass( (Class<? extends ViewManager>) cls.getSuperclass())); extractPropSettersFromViewManagerClassDefinition(cls, props); CLASS_PROPS_CACHE.put(cls, props); return props; } /** * Returns map from property name to setter instances for all the property setters annotated with * {@link ReactProp} (or {@link ReactPropGroup} in the given {@link ReactShadowNode} subclass plus * all the setters declared by its parent classes up to {@link ReactShadowNode} which is treated * as a base class. */ /*package*/ static Map<String, PropSetter> getNativePropSettersForShadowNodeClass( Class<? extends ReactShadowNode> cls) { if (cls == ReactShadowNode.class) { return EMPTY_PROPS_MAP; } Map<String, PropSetter> props = CLASS_PROPS_CACHE.get(cls); if (props != null) { return props; } // This is to include all the setters from parent classes up to ReactShadowNode class props = new HashMap<>( getNativePropSettersForShadowNodeClass( (Class<? extends ReactShadowNode>) cls.getSuperclass())); extractPropSettersFromShadowNodeClassDefinition(cls, props); CLASS_PROPS_CACHE.put(cls, props); return props; } private static PropSetter createPropSetter( ReactProp annotation, Method method, Class<?> propTypeClass) { if (propTypeClass == Dynamic.class) { return new DynamicPropSetter(annotation, method); } else if (propTypeClass == boolean.class) { return new BooleanPropSetter(annotation, method, annotation.defaultBoolean()); } else if (propTypeClass == int.class) { return new IntPropSetter(annotation, method, annotation.defaultInt()); } else if (propTypeClass == float.class) { return new FloatPropSetter(annotation, method, annotation.defaultFloat()); } else if (propTypeClass == double.class) { return new DoublePropSetter(annotation, method, annotation.defaultDouble()); } else if (propTypeClass == String.class) { return new StringPropSetter(annotation, method); } else if (propTypeClass == Boolean.class) { return new BoxedBooleanPropSetter(annotation, method); } else if (propTypeClass == Integer.class) { return new BoxedIntPropSetter(annotation, method); } else if (propTypeClass == ReadableArray.class) { return new ArrayPropSetter(annotation, method); } else if (propTypeClass == ReadableMap.class) { return new MapPropSetter(annotation, method); } else { throw new RuntimeException("Unrecognized type: " + propTypeClass + " for method: " + method.getDeclaringClass().getName() + "#" + method.getName()); } } private static void createPropSetters( ReactPropGroup annotation, Method method, Class<?> propTypeClass, Map<String, PropSetter> props) { String[] names = annotation.names(); if (propTypeClass == Dynamic.class) { for (int i = 0; i < names.length; i++) { props.put( names[i], new DynamicPropSetter(annotation, method, i)); } } else if (propTypeClass == int.class) { for (int i = 0; i < names.length; i++) { props.put( names[i], new IntPropSetter(annotation, method, i, annotation.defaultInt())); } } else if (propTypeClass == float.class) { for (int i = 0; i < names.length; i++) { props.put( names[i], new FloatPropSetter(annotation, method, i, annotation.defaultFloat())); } } else if (propTypeClass == double.class) { for (int i = 0; i < names.length; i++) { props.put( names[i], new DoublePropSetter(annotation, method, i, annotation.defaultDouble())); } } else if (propTypeClass == Integer.class) { for (int i = 0; i < names.length; i++) { props.put( names[i], new BoxedIntPropSetter(annotation, method, i)); } } else { throw new RuntimeException("Unrecognized type: " + propTypeClass + " for method: " + method.getDeclaringClass().getName() + "#" + method.getName()); } } private static void extractPropSettersFromViewManagerClassDefinition( Class<? extends ViewManager> cls, Map<String, PropSetter> props) { Method[] declaredMethods = cls.getDeclaredMethods(); for (int i = 0; i < declaredMethods.length; i++) { Method method = declaredMethods[i]; ReactProp annotation = method.getAnnotation(ReactProp.class); if (annotation != null) { Class<?>[] paramTypes = method.getParameterTypes(); if (paramTypes.length != 2) { throw new RuntimeException("Wrong number of args for prop setter: " + cls.getName() + "#" + method.getName()); } if (!View.class.isAssignableFrom(paramTypes[0])) { throw new RuntimeException("First param should be a view subclass to be updated: " + cls.getName() + "#" + method.getName()); } props.put(annotation.name(), createPropSetter(annotation, method, paramTypes[1])); } ReactPropGroup groupAnnotation = method.getAnnotation(ReactPropGroup.class); if (groupAnnotation != null) { Class<?> [] paramTypes = method.getParameterTypes(); if (paramTypes.length != 3) { throw new RuntimeException("Wrong number of args for group prop setter: " + cls.getName() + "#" + method.getName()); } if (!View.class.isAssignableFrom(paramTypes[0])) { throw new RuntimeException("First param should be a view subclass to be updated: " + cls.getName() + "#" + method.getName()); } if (paramTypes[1] != int.class) { throw new RuntimeException("Second argument should be property index: " + cls.getName() + "#" + method.getName()); } createPropSetters(groupAnnotation, method, paramTypes[2], props); } } } private static void extractPropSettersFromShadowNodeClassDefinition( Class<? extends ReactShadowNode> cls, Map<String, PropSetter> props) { for (Method method : cls.getDeclaredMethods()) { ReactProp annotation = method.getAnnotation(ReactProp.class); if (annotation != null) { Class<?>[] paramTypes = method.getParameterTypes(); if (paramTypes.length != 1) { throw new RuntimeException("Wrong number of args for prop setter: " + cls.getName() + "#" + method.getName()); } props.put(annotation.name(), createPropSetter(annotation, method, paramTypes[0])); } ReactPropGroup groupAnnotation = method.getAnnotation(ReactPropGroup.class); if (groupAnnotation != null) { Class<?> [] paramTypes = method.getParameterTypes(); if (paramTypes.length != 2) { throw new RuntimeException("Wrong number of args for group prop setter: " + cls.getName() + "#" + method.getName()); } if (paramTypes[0] != int.class) { throw new RuntimeException("Second argument should be property index: " + cls.getName() + "#" + method.getName()); } createPropSetters(groupAnnotation, method, paramTypes[1], props); } } } }
gunaangs/Feedonymous
node_modules/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManagersPropertyCache.java
Java
mit
17,826
/* * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* @test @summary Test SoftReceiver send method */ import javax.sound.midi.*; import javax.sound.sampled.*; import com.sun.media.sound.*; public class Send_PolyPressure { private static void assertEquals(Object a, Object b) throws Exception { if(!a.equals(b)) throw new RuntimeException("assertEquals fails!"); } private static void assertTrue(boolean value) throws Exception { if(!value) throw new RuntimeException("assertTrue fails!"); } public static void main(String[] args) throws Exception { SoftTestUtils soft = new SoftTestUtils(); MidiChannel channel = soft.synth.getChannels()[0]; Receiver receiver = soft.synth.getReceiver(); ShortMessage smsg = new ShortMessage(); for (int i = 0; i < 128; i++) { smsg.setMessage(ShortMessage.POLY_PRESSURE,0, i, 10); receiver.send(smsg, -1); assertEquals(channel.getPolyPressure(i),10); smsg.setMessage(ShortMessage.POLY_PRESSURE,0, i, 100); receiver.send(smsg, -1); assertEquals(channel.getPolyPressure(i),100); } soft.close(); } }
rokn/Count_Words_2015
testing/openjdk/jdk/test/javax/sound/midi/Gervill/SoftReceiver/Send_PolyPressure.java
Java
mit
2,398
/* * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.xml.namespace; import java.io.Serializable; import java.security.AccessController; import java.security.PrivilegedAction; import javax.xml.XMLConstants; /** * <p><code>QName</code> represents a <strong>qualified name</strong> * as defined in the XML specifications: <a * href="http://www.w3.org/TR/xmlschema-2/#QName">XML Schema Part2: * Datatypes specification</a>, <a * href="http://www.w3.org/TR/REC-xml-names/#ns-qualnames">Namespaces * in XML</a>, <a * href="http://www.w3.org/XML/xml-names-19990114-errata">Namespaces * in XML Errata</a>.</p> * * <p>The value of a <code>QName</code> contains a <strong>Namespace * URI</strong>, <strong>local part</strong> and * <strong>prefix</strong>.</p> * * <p>The prefix is included in <code>QName</code> to retain lexical * information <strong><em>when present</em></strong> in an {@link * javax.xml.transform.Source XML input source}. The prefix is * <strong><em>NOT</em></strong> used in {@link #equals(Object) * QName.equals(Object)} or to compute the {@link #hashCode() * QName.hashCode()}. Equality and the hash code are defined using * <strong><em>only</em></strong> the Namespace URI and local part.</p> * * <p>If not specified, the Namespace URI is set to {@link * javax.xml.XMLConstants#NULL_NS_URI XMLConstants.NULL_NS_URI}. * If not specified, the prefix is set to {@link * javax.xml.XMLConstants#DEFAULT_NS_PREFIX * XMLConstants.DEFAULT_NS_PREFIX}.</p> * * <p><code>QName</code> is immutable.</p> * * @author <a href="mailto:[email protected]">Jeff Suttor</a> * @version $Revision: 1.8 $, $Date: 2010/03/18 03:06:17 $ * @see <a href="http://www.w3.org/TR/xmlschema-2/#QName"> * XML Schema Part2: Datatypes specification</a> * @see <a href="http://www.w3.org/TR/REC-xml-names/#ns-qualnames"> * Namespaces in XML</a> * @see <a href="http://www.w3.org/XML/xml-names-19990114-errata"> * Namespaces in XML Errata</a> * @since 1.5 */ public class QName implements Serializable { /** * <p>Stream Unique Identifier.</p> * * <p>Due to a historical defect, QName was released with multiple * serialVersionUID values even though its serialization was the * same.</p> * * <p>To workaround this issue, serialVersionUID is set with either * a default value or a compatibility value. To use the * compatiblity value, set the system property:</p> * * <code>com.sun.xml.namespace.QName.useCompatibleSerialVersionUID=1.0</code> * * <p>This workaround was inspired by classes in the javax.management * package, e.g. ObjectName, etc. * See CR6267224 for original defect report.</p> */ private static final long serialVersionUID; /** * <p>Default <code>serialVersionUID</code> value.</p> */ private static final long defaultSerialVersionUID = -9120448754896609940L; /** * <p>Compatibility <code>serialVersionUID</code> value.</p> */ private static final long compatibleSerialVersionUID = 4418622981026545151L; /** * <p>Flag to use default or campatible serialVersionUID.</p> */ private static boolean useDefaultSerialVersionUID = true; static { try { // use a privileged block as reading a system property String valueUseCompatibleSerialVersionUID = (String) AccessController.doPrivileged( new PrivilegedAction() { public Object run() { return System.getProperty("com.sun.xml.namespace.QName.useCompatibleSerialVersionUID"); } } ); useDefaultSerialVersionUID = (valueUseCompatibleSerialVersionUID != null && valueUseCompatibleSerialVersionUID.equals("1.0")) ? false : true; } catch (Exception exception) { // use default if any Exceptions useDefaultSerialVersionUID = true; } // set serialVersionUID to desired value if (useDefaultSerialVersionUID) { serialVersionUID = defaultSerialVersionUID; } else { serialVersionUID = compatibleSerialVersionUID; } } /** * <p>Namespace URI of this <code>QName</code>.</p> */ private final String namespaceURI; /** * <p>local part of this <code>QName</code>.</p> */ private final String localPart; /** * <p>prefix of this <code>QName</code>.</p> */ private final String prefix; /** * <p><code>QName</code> constructor specifying the Namespace URI * and local part.</p> * * <p>If the Namespace URI is <code>null</code>, it is set to * {@link javax.xml.XMLConstants#NULL_NS_URI * XMLConstants.NULL_NS_URI}. This value represents no * explicitly defined Namespace as defined by the <a * href="http://www.w3.org/TR/REC-xml-names/#ns-qualnames">Namespaces * in XML</a> specification. This action preserves compatible * behavior with QName 1.0. Explicitly providing the {@link * javax.xml.XMLConstants#NULL_NS_URI * XMLConstants.NULL_NS_URI} value is the preferred coding * style.</p> * * <p>If the local part is <code>null</code> an * <code>IllegalArgumentException</code> is thrown. * A local part of "" is allowed to preserve * compatible behavior with QName 1.0. </p> * * <p>When using this constructor, the prefix is set to {@link * javax.xml.XMLConstants#DEFAULT_NS_PREFIX * XMLConstants.DEFAULT_NS_PREFIX}.</p> * * <p>The Namespace URI is not validated as a * <a href="http://www.ietf.org/rfc/rfc2396.txt">URI reference</a>. * The local part is not validated as a * <a href="http://www.w3.org/TR/REC-xml-names/#NT-NCName">NCName</a> * as specified in <a href="http://www.w3.org/TR/REC-xml-names/">Namespaces * in XML</a>.</p> * * @param namespaceURI Namespace URI of the <code>QName</code> * @param localPart local part of the <code>QName</code> * * @throws IllegalArgumentException When <code>localPart</code> is * <code>null</code> * * @see #QName(String namespaceURI, String localPart, String * prefix) QName(String namespaceURI, String localPart, String * prefix) */ public QName(final String namespaceURI, final String localPart) { this(namespaceURI, localPart, XMLConstants.DEFAULT_NS_PREFIX); } /** * <p><code>QName</code> constructor specifying the Namespace URI, * local part and prefix.</p> * * <p>If the Namespace URI is <code>null</code>, it is set to * {@link javax.xml.XMLConstants#NULL_NS_URI * XMLConstants.NULL_NS_URI}. This value represents no * explicitly defined Namespace as defined by the <a * href="http://www.w3.org/TR/REC-xml-names/#ns-qualnames">Namespaces * in XML</a> specification. This action preserves compatible * behavior with QName 1.0. Explicitly providing the {@link * javax.xml.XMLConstants#NULL_NS_URI * XMLConstants.NULL_NS_URI} value is the preferred coding * style.</p> * * <p>If the local part is <code>null</code> an * <code>IllegalArgumentException</code> is thrown. * A local part of "" is allowed to preserve * compatible behavior with QName 1.0. </p> * * <p>If the prefix is <code>null</code>, an * <code>IllegalArgumentException</code> is thrown. Use {@link * javax.xml.XMLConstants#DEFAULT_NS_PREFIX * XMLConstants.DEFAULT_NS_PREFIX} to explicitly indicate that no * prefix is present or the prefix is not relevant.</p> * * <p>The Namespace URI is not validated as a * <a href="http://www.ietf.org/rfc/rfc2396.txt">URI reference</a>. * The local part and prefix are not validated as a * <a href="http://www.w3.org/TR/REC-xml-names/#NT-NCName">NCName</a> * as specified in <a href="http://www.w3.org/TR/REC-xml-names/">Namespaces * in XML</a>.</p> * * @param namespaceURI Namespace URI of the <code>QName</code> * @param localPart local part of the <code>QName</code> * @param prefix prefix of the <code>QName</code> * * @throws IllegalArgumentException When <code>localPart</code> * or <code>prefix</code> is <code>null</code> */ public QName(String namespaceURI, String localPart, String prefix) { // map null Namespace URI to default // to preserve compatibility with QName 1.0 if (namespaceURI == null) { this.namespaceURI = XMLConstants.NULL_NS_URI; } else { this.namespaceURI = namespaceURI; } // local part is required. // "" is allowed to preserve compatibility with QName 1.0 if (localPart == null) { throw new IllegalArgumentException( "local part cannot be \"null\" when creating a QName"); } this.localPart = localPart; // prefix is required if (prefix == null) { throw new IllegalArgumentException( "prefix cannot be \"null\" when creating a QName"); } this.prefix = prefix; } /** * <p><code>QName</code> constructor specifying the local part.</p> * * <p>If the local part is <code>null</code> an * <code>IllegalArgumentException</code> is thrown. * A local part of "" is allowed to preserve * compatible behavior with QName 1.0. </p> * * <p>When using this constructor, the Namespace URI is set to * {@link javax.xml.XMLConstants#NULL_NS_URI * XMLConstants.NULL_NS_URI} and the prefix is set to {@link * javax.xml.XMLConstants#DEFAULT_NS_PREFIX * XMLConstants.DEFAULT_NS_PREFIX}.</p> * * <p><em>In an XML context, all Element and Attribute names exist * in the context of a Namespace. Making this explicit during the * construction of a <code>QName</code> helps prevent hard to * diagnosis XML validity errors. The constructors {@link * #QName(String namespaceURI, String localPart) QName(String * namespaceURI, String localPart)} and * {@link #QName(String namespaceURI, String localPart, String prefix)} * are preferred.</em></p> * * <p>The local part is not validated as a * <a href="http://www.w3.org/TR/REC-xml-names/#NT-NCName">NCName</a> * as specified in <a href="http://www.w3.org/TR/REC-xml-names/">Namespaces * in XML</a>.</p> * * @param localPart local part of the <code>QName</code> * * @throws IllegalArgumentException When <code>localPart</code> is * <code>null</code> * * @see #QName(String namespaceURI, String localPart) QName(String * namespaceURI, String localPart) * @see #QName(String namespaceURI, String localPart, String * prefix) QName(String namespaceURI, String localPart, String * prefix) */ public QName(String localPart) { this( XMLConstants.NULL_NS_URI, localPart, XMLConstants.DEFAULT_NS_PREFIX); } /** * <p>Get the Namespace URI of this <code>QName</code>.</p> * * @return Namespace URI of this <code>QName</code> */ public String getNamespaceURI() { return namespaceURI; } /** * <p>Get the local part of this <code>QName</code>.</p> * * @return local part of this <code>QName</code> */ public String getLocalPart() { return localPart; } /** * <p>Get the prefix of this <code>QName</code>.</p> * * <p>The prefix assigned to a <code>QName</code> might * <strong><em>NOT</em></strong> be valid in a different * context. For example, a <code>QName</code> may be assigned a * prefix in the context of parsing a document but that prefix may * be invalid in the context of a different document.</p> * * @return prefix of this <code>QName</code> */ public String getPrefix() { return prefix; } /** * <p>Test this <code>QName</code> for equality with another * <code>Object</code>.</p> * * <p>If the <code>Object</code> to be tested is not a * <code>QName</code> or is <code>null</code>, then this method * returns <code>false</code>.</p> * * <p>Two <code>QName</code>s are considered equal if and only if * both the Namespace URI and local part are equal. This method * uses <code>String.equals()</code> to check equality of the * Namespace URI and local part. The prefix is * <strong><em>NOT</em></strong> used to determine equality.</p> * * <p>This method satisfies the general contract of {@link * java.lang.Object#equals(Object) Object.equals(Object)}</p> * * @param objectToTest the <code>Object</code> to test for * equality with this <code>QName</code> * @return <code>true</code> if the given <code>Object</code> is * equal to this <code>QName</code> else <code>false</code> */ public final boolean equals(Object objectToTest) { if (objectToTest == this) { return true; } if (objectToTest == null || !(objectToTest instanceof QName)) { return false; } QName qName = (QName) objectToTest; return localPart.equals(qName.localPart) && namespaceURI.equals(qName.namespaceURI); } /** * <p>Generate the hash code for this <code>QName</code>.</p> * * <p>The hash code is calculated using both the Namespace URI and * the local part of the <code>QName</code>. The prefix is * <strong><em>NOT</em></strong> used to calculate the hash * code.</p> * * <p>This method satisfies the general contract of {@link * java.lang.Object#hashCode() Object.hashCode()}.</p> * * @return hash code for this <code>QName</code> <code>Object</code> */ public final int hashCode() { return namespaceURI.hashCode() ^ localPart.hashCode(); } /** * <p><code>String</code> representation of this * <code>QName</code>.</p> * * <p>The commonly accepted way of representing a <code>QName</code> * as a <code>String</code> was * <a href="http://jclark.com/xml/xmlns.htm">defined</a> * by James Clark. Although this is not a <em>standard</em> * specification, it is in common use, e.g. {@link * javax.xml.transform.Transformer#setParameter(String name, Object value)}. * This implementation represents a <code>QName</code> as: * "{" + Namespace URI + "}" + local part. If the Namespace URI * <code>.equals(XMLConstants.NULL_NS_URI)</code>, only the * local part is returned. An appropriate use of this method is * for debugging or logging for human consumption.</p> * * <p>Note the prefix value is <strong><em>NOT</em></strong> * returned as part of the <code>String</code> representation.</p> * * <p>This method satisfies the general contract of {@link * java.lang.Object#toString() Object.toString()}.</p> * * @return <code>String</code> representation of this <code>QName</code> */ public String toString() { if (namespaceURI.equals(XMLConstants.NULL_NS_URI)) { return localPart; } else { return "{" + namespaceURI + "}" + localPart; } } /** * <p><code>QName</code> derived from parsing the formatted * <code>String</code>.</p> * * <p>If the <code>String</code> is <code>null</code> or does not conform to * {@link #toString() QName.toString()} formatting, an * <code>IllegalArgumentException</code> is thrown.</p> * * <p><em>The <code>String</code> <strong>MUST</strong> be in the * form returned by {@link #toString() QName.toString()}.</em></p> * * <p>The commonly accepted way of representing a <code>QName</code> * as a <code>String</code> was * <a href="http://jclark.com/xml/xmlns.htm">defined</a> * by James Clark. Although this is not a <em>standard</em> * specification, it is in common use, e.g. {@link * javax.xml.transform.Transformer#setParameter(String name, Object value)}. * This implementation parses a <code>String</code> formatted * as: "{" + Namespace URI + "}" + local part. If the Namespace * URI <code>.equals(XMLConstants.NULL_NS_URI)</code>, only the * local part should be provided.</p> * * <p>The prefix value <strong><em>CANNOT</em></strong> be * represented in the <code>String</code> and will be set to * {@link javax.xml.XMLConstants#DEFAULT_NS_PREFIX * XMLConstants.DEFAULT_NS_PREFIX}.</p> * * <p>This method does not do full validation of the resulting * <code>QName</code>. * <p>The Namespace URI is not validated as a * <a href="http://www.ietf.org/rfc/rfc2396.txt">URI reference</a>. * The local part is not validated as a * <a href="http://www.w3.org/TR/REC-xml-names/#NT-NCName">NCName</a> * as specified in * <a href="http://www.w3.org/TR/REC-xml-names/">Namespaces in XML</a>.</p> * * @param qNameAsString <code>String</code> representation * of the <code>QName</code> * * @throws IllegalArgumentException When <code>qNameAsString</code> is * <code>null</code> or malformed * * @return <code>QName</code> corresponding to the given <code>String</code> * @see #toString() QName.toString() */ public static QName valueOf(String qNameAsString) { // null is not valid if (qNameAsString == null) { throw new IllegalArgumentException( "cannot create QName from \"null\" or \"\" String"); } // "" local part is valid to preserve compatible behavior with QName 1.0 if (qNameAsString.length() == 0) { return new QName( XMLConstants.NULL_NS_URI, qNameAsString, XMLConstants.DEFAULT_NS_PREFIX); } // local part only? if (qNameAsString.charAt(0) != '{') { return new QName( XMLConstants.NULL_NS_URI, qNameAsString, XMLConstants.DEFAULT_NS_PREFIX); } // Namespace URI improperly specified? if (qNameAsString.startsWith("{" + XMLConstants.NULL_NS_URI + "}")) { throw new IllegalArgumentException( "Namespace URI .equals(XMLConstants.NULL_NS_URI), " + ".equals(\"" + XMLConstants.NULL_NS_URI + "\"), " + "only the local part, " + "\"" + qNameAsString.substring(2 + XMLConstants.NULL_NS_URI.length()) + "\", " + "should be provided."); } // Namespace URI and local part specified int endOfNamespaceURI = qNameAsString.indexOf('}'); if (endOfNamespaceURI == -1) { throw new IllegalArgumentException( "cannot create QName from \"" + qNameAsString + "\", missing closing \"}\""); } return new QName( qNameAsString.substring(1, endOfNamespaceURI), qNameAsString.substring(endOfNamespaceURI + 1), XMLConstants.DEFAULT_NS_PREFIX); } }
rokn/Count_Words_2015
testing/openjdk2/jaxp/src/javax/xml/namespace/QName.java
Java
mit
20,635