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 com.tommy;
import java.security.*;
import java.security.spec.ECGenParameterSpec;
/**
* Created by Tommy on 2016/6/5.
*/
public class ECDSATest {
public static void main(String[] args) throws Exception {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ECDSA", "BC");
ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256k1");
keyGen.initialize(ecSpec, new SecureRandom());
KeyPair keyPair = keyGen.generateKeyPair();
Signature signature = Signature.getInstance("ECDSA", "BC");
signature.initSign(keyPair.getPrivate(), new SecureRandom());
byte[] message = "abc".getBytes();
signature.update(message);
byte[] sigBytes = signature.sign();
signature.initVerify(keyPair.getPublic());
signature.update(message);
System.out.println(signature.verify(sigBytes));
}
}
| tommy770221/EthereumJPractice | src/main/java/com/tommy/ECDSATest.java | Java | apache-2.0 | 981 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package se.mediaserver.tutorial.mediaweb.service;
import java.util.List;
import javax.persistence.EntityManager;
/**
*
* @author ingimar
*/
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0]);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}
| Inkimar/Mediaserver-RESTful | ImageWebProject/src/main/java/se/mediaserver/tutorial/mediaweb/service/AbstractFacade.java | Java | apache-2.0 | 1,910 |
/*
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Bob Jervis
* Google Inc.
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package com.google.javascript.rhino.jstype;
import static com.google.javascript.rhino.jstype.JSTypeNative.OBJECT_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.U2U_CONSTRUCTOR_TYPE;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.util.HashSet;
import com.google.javascript.rhino.ErrorReporter;
import com.google.javascript.rhino.FunctionTypeI;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.TypeI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* This derived type provides extended information about a function, including
* its return type and argument types.<p>
*
* Note: the parameters list is the LP node that is the parent of the
* actual NAME node containing the parsed argument list (annotated with
* JSDOC_TYPE_PROP's for the compile-time type of each argument.
*/
public class FunctionType extends PrototypeObjectType implements FunctionTypeI {
private static final long serialVersionUID = 1L;
private enum Kind {
ORDINARY,
CONSTRUCTOR,
INTERFACE
}
// relevant only for constructors
private enum PropAccess { ANY, STRUCT, DICT }
/**
* {@code [[Call]]} property.
*/
private ArrowType call;
/**
* The {@code prototype} property. This field is lazily initialized by
* {@code #getPrototype()}. The most important reason for lazily
* initializing this field is that there are cycles in the native types
* graph, so some prototypes must temporarily be {@code null} during
* the construction of the graph.
*
* If non-null, the type must be a PrototypeObjectType.
*/
private Property prototypeSlot;
/**
* Whether a function is a constructor, an interface, or just an ordinary
* function.
*/
private final Kind kind;
/**
* Whether the instances are structs, dicts, or unrestricted.
*/
private PropAccess propAccess;
/**
* The type of {@code this} in the scope of this function.
*/
private JSType typeOfThis;
/**
* The function node which this type represents. It may be {@code null}.
*/
private Node source;
/**
* if this is an interface, indicate whether or not it supports
* structural interface matching
*/
private boolean isStructuralInterface;
/**
* The interfaces directly implemented by this function (for constructors)
* It is only relevant for constructors. May not be {@code null}.
*/
private ImmutableList<ObjectType> implementedInterfaces = ImmutableList.of();
/**
* The interfaces directly extended by this function (for interfaces)
* It is only relevant for constructors. May not be {@code null}.
*/
private ImmutableList<ObjectType> extendedInterfaces = ImmutableList.of();
/**
* The types which are subtypes of this function. It is only relevant for
* constructors and may be {@code null}.
*/
private List<FunctionType> subTypes;
/** Creates an instance for a function that might be a constructor. */
FunctionType(JSTypeRegistry registry, String name, Node source,
ArrowType arrowType, JSType typeOfThis,
TemplateTypeMap templateTypeMap,
boolean isConstructor, boolean nativeType) {
super(registry, name,
registry.getNativeObjectType(JSTypeNative.FUNCTION_INSTANCE_TYPE),
nativeType, templateTypeMap);
setPrettyPrint(true);
Preconditions.checkArgument(source == null ||
Token.FUNCTION == source.getType());
Preconditions.checkNotNull(arrowType);
this.source = source;
if (isConstructor) {
this.kind = Kind.CONSTRUCTOR;
this.propAccess = PropAccess.ANY;
this.typeOfThis = typeOfThis != null ?
typeOfThis : new InstanceObjectType(registry, this, nativeType);
} else {
this.kind = Kind.ORDINARY;
this.typeOfThis = typeOfThis != null ?
typeOfThis :
registry.getNativeObjectType(JSTypeNative.UNKNOWN_TYPE);
}
this.call = arrowType;
this.isStructuralInterface = false;
}
/** Creates an instance for a function that is an interface. */
private FunctionType(JSTypeRegistry registry, String name, Node source,
TemplateTypeMap typeParameters) {
super(registry, name,
registry.getNativeObjectType(JSTypeNative.FUNCTION_INSTANCE_TYPE),
false, typeParameters);
setPrettyPrint(true);
Preconditions.checkArgument(source == null ||
Token.FUNCTION == source.getType());
Preconditions.checkArgument(name != null);
this.source = source;
this.call = new ArrowType(registry, new Node(Token.PARAM_LIST), null);
this.kind = Kind.INTERFACE;
this.typeOfThis = new InstanceObjectType(registry, this);
this.isStructuralInterface = false;
}
/** Creates an instance for a function that is an interface. */
static FunctionType forInterface(
JSTypeRegistry registry, String name, Node source,
TemplateTypeMap typeParameters) {
return new FunctionType(registry, name, source, typeParameters);
}
@Override
public boolean isInstanceType() {
// The universal constructor is its own instance, bizarrely. It overrides
// getConstructor() appropriately when it's declared.
return this == registry.getNativeType(U2U_CONSTRUCTOR_TYPE);
}
@Override
public boolean isConstructor() {
return kind == Kind.CONSTRUCTOR;
}
@Override
public boolean isInterface() {
return kind == Kind.INTERFACE;
}
@Override
public boolean isOrdinaryFunction() {
return kind == Kind.ORDINARY;
}
/**
* When a class B inherits from A and A is annotated as a struct, then B
* automatically gets the annotation, even if B's constructor is not
* explicitly annotated.
*/
public boolean makesStructs() {
if (!hasInstanceType()) {
return false;
}
if (propAccess == PropAccess.STRUCT) {
return true;
}
FunctionType superc = getSuperClassConstructor();
if (superc != null && superc.makesStructs()) {
setStruct();
return true;
}
return false;
}
/**
* When a class B inherits from A and A is annotated as a dict, then B
* automatically gets the annotation, even if B's constructor is not
* explicitly annotated.
*/
public boolean makesDicts() {
if (!isConstructor()) {
return false;
}
if (propAccess == PropAccess.DICT) {
return true;
}
FunctionType superc = getSuperClassConstructor();
if (superc != null && superc.makesDicts()) {
setDict();
return true;
}
return false;
}
public void setStruct() {
propAccess = PropAccess.STRUCT;
}
public void setDict() {
propAccess = PropAccess.DICT;
}
@Override
public FunctionType toMaybeFunctionType() {
return this;
}
@Override
public boolean canBeCalled() {
return true;
}
public boolean hasImplementedInterfaces() {
if (!implementedInterfaces.isEmpty()){
return true;
}
FunctionType superCtor = isConstructor() ?
getSuperClassConstructor() : null;
if (superCtor != null) {
return superCtor.hasImplementedInterfaces();
}
return false;
}
public Iterable<Node> getParameters() {
Node n = getParametersNode();
if (n != null) {
return n.children();
} else {
return Collections.emptySet();
}
}
/** Gets an LP node that contains all params. May be null. */
public Node getParametersNode() {
return call.parameters;
}
/** Gets the minimum number of arguments that this function requires. */
public int getMinArguments() {
// NOTE(nicksantos): There are some native functions that have optional
// parameters before required parameters. This algorithm finds the position
// of the last required parameter.
int i = 0;
int min = 0;
for (Node n : getParameters()) {
i++;
if (!n.isOptionalArg() && !n.isVarArgs()) {
min = i;
}
}
return min;
}
/**
* Gets the maximum number of arguments that this function requires,
* or Integer.MAX_VALUE if this is a variable argument function.
*/
public int getMaxArguments() {
Node params = getParametersNode();
if (params != null) {
Node lastParam = params.getLastChild();
if (lastParam == null || !lastParam.isVarArgs()) {
return params.getChildCount();
}
}
return Integer.MAX_VALUE;
}
public JSType getReturnType() {
return call.returnType;
}
public boolean isReturnTypeInferred() {
return call.returnTypeInferred;
}
/** Gets the internal arrow type. For use by subclasses only. */
ArrowType getInternalArrowType() {
return call;
}
@Override
public Property getSlot(String name) {
if ("prototype".equals(name)) {
// Lazy initialization of the prototype field.
getPrototype();
return prototypeSlot;
} else {
return super.getSlot(name);
}
}
/**
* Includes the prototype iff someone has created it. We do not want
* to expose the prototype for ordinary functions.
*/
@Override
public Set<String> getOwnPropertyNames() {
if (prototypeSlot == null) {
return super.getOwnPropertyNames();
} else {
ImmutableSet.Builder<String> names = ImmutableSet.builder();
names.add("prototype");
names.addAll(super.getOwnPropertyNames());
return names.build();
}
}
/**
* Gets the {@code prototype} property of this function type. This is
* equivalent to {@code (ObjectType) getPropertyType("prototype")}.
*/
public ObjectType getPrototype() {
// lazy initialization of the prototype field
if (prototypeSlot == null) {
String refName = getReferenceName();
if (refName == null) {
// Someone is trying to access the prototype of a structural function.
// We don't want to give real properties to this prototype, because
// then it would propagate to all structural functions.
setPrototypeNoCheck(
registry.getNativeObjectType(JSTypeNative.UNKNOWN_TYPE),
null);
} else {
setPrototype(
new PrototypeObjectType(
registry,
getReferenceName() + ".prototype",
registry.getNativeObjectType(OBJECT_TYPE),
isNativeObjectType(), null),
null);
}
}
return (ObjectType) prototypeSlot.getType();
}
/**
* Sets the prototype, creating the prototype object from the given
* base type.
* @param baseType The base type.
*/
public void setPrototypeBasedOn(ObjectType baseType) {
setPrototypeBasedOn(baseType, null);
}
void setPrototypeBasedOn(ObjectType baseType, Node propertyNode) {
// This is a bit weird. We need to successfully handle these
// two cases:
// Foo.prototype = new Bar();
// and
// Foo.prototype = {baz: 3};
// In the first case, we do not want new properties to get
// added to Bar. In the second case, we do want new properties
// to get added to the type of the anonymous object.
//
// We handle this by breaking it into two cases:
//
// In the first case, we create a new PrototypeObjectType and set
// its implicit prototype to the type being assigned. This ensures
// that Bar will not get any properties of Foo.prototype, but properties
// later assigned to Bar will get inherited properly.
//
// In the second case, we just use the anonymous object as the prototype.
if (baseType.hasReferenceName() ||
isNativeObjectType() ||
baseType.isFunctionPrototypeType()) {
baseType = new PrototypeObjectType(
registry, getReferenceName() + ".prototype", baseType);
}
setPrototype(baseType, propertyNode);
}
/**
* Extends the TemplateTypeMap of the function's this type, based on the
* specified type.
* @param type
*/
public void extendTemplateTypeMapBasedOn(ObjectType type) {
typeOfThis.extendTemplateTypeMap(type.getTemplateTypeMap());
}
/**
* Sets the prototype.
* @param prototype the prototype. If this value is {@code null} it will
* silently be discarded.
*/
boolean setPrototype(ObjectType prototype, Node propertyNode) {
if (prototype == null) {
return false;
}
// getInstanceType fails if the function is not a constructor
if (isConstructor() && prototype == getInstanceType()) {
return false;
}
return setPrototypeNoCheck(prototype, propertyNode);
}
/** Set the prototype without doing any sanity checks. */
private boolean setPrototypeNoCheck(ObjectType prototype, Node propertyNode) {
ObjectType oldPrototype = prototypeSlot == null
? null : (ObjectType) prototypeSlot.getType();
boolean replacedPrototype = oldPrototype != null;
this.prototypeSlot = new Property("prototype", prototype, true,
propertyNode == null ? source : propertyNode);
prototype.setOwnerFunction(this);
if (oldPrototype != null) {
// Disassociating the old prototype makes this easier to debug--
// we don't have to worry about two prototypes running around.
oldPrototype.setOwnerFunction(null);
}
if (isConstructor() || isInterface()) {
FunctionType superClass = getSuperClassConstructor();
if (superClass != null) {
superClass.addSubType(this);
}
if (isInterface()) {
for (ObjectType interfaceType : getExtendedInterfaces()) {
if (interfaceType.getConstructor() != null) {
interfaceType.getConstructor().addSubType(this);
}
}
}
}
if (replacedPrototype) {
clearCachedValues();
}
return true;
}
/**
* check whether or not this function type has implemented
* the given interface
* if this function is an interface, check whether or not
* this interface has extended the given interface
* @param interfaceType the interface type
* @return true if implemented
*/
public boolean explicitlyImplOrExtInterface(FunctionType interfaceType) {
Preconditions.checkArgument(interfaceType.isInterface());
for (ObjectType implementedInterface : getAllImplementedInterfaces()) {
FunctionType ctor = implementedInterface.getConstructor();
if (ctor != null && ctor.checkEquivalenceHelper(
interfaceType, EquivalenceMethod.IDENTITY)) {
return true;
}
}
for (ObjectType implementedInterface : getExtendedInterfaces()) {
FunctionType ctor = implementedInterface.getConstructor();
if (ctor != null && ctor.checkEquivalenceHelper(
interfaceType, EquivalenceMethod.IDENTITY)) {
return true;
} else if (ctor != null) {
return ctor.explicitlyImplOrExtInterface(interfaceType);
}
}
return false;
}
/**
* Returns all interfaces implemented by a class or its superclass and any
* superclasses for any of those interfaces. If this is called before all
* types are resolved, it may return an incomplete set.
*/
public Iterable<ObjectType> getAllImplementedInterfaces() {
// Store them in a linked hash set, so that the compile job is
// deterministic.
Set<ObjectType> interfaces = new LinkedHashSet<>();
for (ObjectType type : getImplementedInterfaces()) {
addRelatedInterfaces(type, interfaces);
}
return interfaces;
}
private void addRelatedInterfaces(ObjectType instance, Set<ObjectType> set) {
FunctionType constructor = instance.getConstructor();
if (constructor != null) {
if (!constructor.isInterface()) {
return;
}
if (!set.add(instance)) {
return;
}
for (ObjectType interfaceType : instance.getCtorExtendedInterfaces()) {
addRelatedInterfaces(interfaceType, set);
}
}
}
/** Returns interfaces implemented directly by a class or its superclass. */
public Iterable<ObjectType> getImplementedInterfaces() {
FunctionType superCtor =
isConstructor() ? getSuperClassConstructor() : null;
if (superCtor == null) {
return implementedInterfaces;
}
ImmutableList.Builder<ObjectType> builder = ImmutableList.builder();
builder.addAll(implementedInterfaces);
while (superCtor != null) {
builder.addAll(superCtor.implementedInterfaces);
superCtor = superCtor.getSuperClassConstructor();
}
return builder.build();
}
/** Returns interfaces directly implemented by the class. */
public Iterable<ObjectType> getOwnImplementedInterfaces() {
return implementedInterfaces;
}
public void setImplementedInterfaces(List<ObjectType> implementedInterfaces) {
if (isConstructor()) {
// Records this type for each implemented interface.
for (ObjectType type : implementedInterfaces) {
registry.registerTypeImplementingInterface(this, type);
typeOfThis.extendTemplateTypeMap(type.getTemplateTypeMap());
}
this.implementedInterfaces = ImmutableList.copyOf(implementedInterfaces);
} else {
throw new UnsupportedOperationException();
}
}
private void addRelatedExtendedInterfaces(ObjectType instance,
Set<ObjectType> set) {
FunctionType constructor = instance.getConstructor();
if (constructor != null) {
if (!set.add(instance)) {
return;
}
for (ObjectType interfaceType : constructor.getExtendedInterfaces()) {
addRelatedExtendedInterfaces(interfaceType, set);
}
}
}
/** Returns interfaces directly extended by an interface */
public Iterable<ObjectType> getExtendedInterfaces() {
return extendedInterfaces;
}
/** Returns the number of interfaces directly extended by an interface */
public int getExtendedInterfacesCount() {
return extendedInterfaces.size();
}
public void setExtendedInterfaces(List<ObjectType> extendedInterfaces)
throws UnsupportedOperationException {
if (isInterface()) {
this.extendedInterfaces = ImmutableList.copyOf(extendedInterfaces);
for (ObjectType extendedInterface : this.extendedInterfaces) {
typeOfThis.extendTemplateTypeMap(
extendedInterface.getTemplateTypeMap());
}
} else {
throw new UnsupportedOperationException();
}
}
@Override
public JSType getPropertyType(String name) {
if (!hasOwnProperty(name)) {
// Define the "call", "apply", and "bind" functions lazily.
boolean isCall = "call".equals(name);
boolean isBind = "bind".equals(name);
if (isCall || isBind) {
defineDeclaredProperty(name, getCallOrBindSignature(isCall), source);
} else if ("apply".equals(name)) {
// Define the "apply" function lazily.
FunctionParamBuilder builder = new FunctionParamBuilder(registry);
// ECMA-262 says that apply's second argument must be an Array
// or an arguments object. We don't model the arguments object,
// so let's just be forgiving for now.
// TODO(nicksantos): Model the Arguments object.
builder.addOptionalParams(
registry.createNullableType(getTypeOfThis()),
registry.createNullableType(
registry.getNativeType(JSTypeNative.OBJECT_TYPE)));
defineDeclaredProperty(name,
new FunctionBuilder(registry)
.withParamsNode(builder.build())
.withReturnType(getReturnType())
.withTemplateKeys(getTemplateTypeMap().getTemplateKeys())
.build(),
source);
}
}
return super.getPropertyType(name);
}
/**
* Get the return value of calling "bind" on this function
* with the specified number of arguments.
*
* If -1 is passed, then we will return a result that accepts
* any parameters.
*/
public FunctionType getBindReturnType(int argsToBind) {
FunctionBuilder builder = new FunctionBuilder(registry)
.withReturnType(getReturnType())
.withTemplateKeys(getTemplateTypeMap().getTemplateKeys());
if (argsToBind >= 0) {
Node origParams = getParametersNode();
if (origParams != null) {
Node params = origParams.cloneTree();
for (int i = 1; i < argsToBind && params.getFirstChild() != null; i++) {
if (params.getFirstChild().isVarArgs()) {
break;
}
params.removeFirstChild();
}
builder.withParamsNode(params);
}
}
return builder.build();
}
/**
* Notice that "call" and "bind" have the same argument signature,
* except that all the arguments of "bind" (except the first)
* are optional.
*/
private FunctionType getCallOrBindSignature(boolean isCall) {
boolean isBind = !isCall;
FunctionBuilder builder = new FunctionBuilder(registry)
.withReturnType(isCall ? getReturnType() : getBindReturnType(-1))
.withTemplateKeys(getTemplateTypeMap().getTemplateKeys());
Node origParams = getParametersNode();
if (origParams != null) {
Node params = origParams.cloneTree();
Node thisTypeNode = Node.newString(Token.NAME, "thisType");
thisTypeNode.setJSType(
registry.createOptionalNullableType(getTypeOfThis()));
params.addChildToFront(thisTypeNode);
if (isBind) {
// The arguments of bind() are unique in that they are all
// optional but not undefinable.
for (Node current = thisTypeNode.getNext();
current != null; current = current.getNext()) {
current.setOptionalArg(true);
}
} else if (isCall) {
// The first argument of call() is optional iff all the arguments
// are optional. It's sufficient to check the first argument.
Node firstArg = thisTypeNode.getNext();
if (firstArg == null
|| firstArg.isOptionalArg()
|| firstArg.isVarArgs()) {
thisTypeNode.setOptionalArg(true);
}
}
builder.withParamsNode(params);
}
return builder.build();
}
@Override
boolean defineProperty(String name, JSType type,
boolean inferred, Node propertyNode) {
if ("prototype".equals(name)) {
ObjectType objType = type.toObjectType();
if (objType != null) {
if (prototypeSlot != null &&
objType.isEquivalentTo(prototypeSlot.getType())) {
return true;
}
setPrototypeBasedOn(objType, propertyNode);
return true;
} else {
return false;
}
}
return super.defineProperty(name, type, inferred, propertyNode);
}
/**
* Computes the supremum or infimum of two functions.
* Because sup() and inf() share a lot of logic for functions, we use
* a single helper.
* @param leastSuper If true, compute the supremum of {@code this} with
* {@code that}. Otherwise, compute the infimum.
* @return The least supertype or greatest subtype.
*/
FunctionType supAndInfHelper(FunctionType that, boolean leastSuper) {
// NOTE(nicksantos): When we remove the unknown type, the function types
// form a lattice with the universal constructor at the top of the lattice,
// and the LEAST_FUNCTION_TYPE type at the bottom of the lattice.
//
// When we introduce the unknown type, it's much more difficult to make
// heads or tails of the partial ordering of types, because there's no
// clear hierarchy between the different components (parameter types and
// return types) in the ArrowType.
//
// Rather than make the situation more complicated by introducing new
// types (like unions of functions), we just fallback on the simpler
// approach of getting things right at the top and the bottom of the
// lattice.
//
// If there are unknown parameters or return types making things
// ambiguous, then sup(A, B) is always the top function type, and
// inf(A, B) is always the bottom function type.
Preconditions.checkNotNull(that);
if (isEquivalentTo(that)) {
return this;
}
// If these are ordinary functions, then merge them.
// Don't do this if any of the params/return
// values are unknown, because then there will be cycles in
// their local lattice and they will merge in weird ways.
if (isOrdinaryFunction() && that.isOrdinaryFunction() &&
!this.call.hasUnknownParamsOrReturn() &&
!that.call.hasUnknownParamsOrReturn()) {
// Check for the degenerate case, but double check
// that there's not a cycle.
boolean isSubtypeOfThat = isSubtype(that);
boolean isSubtypeOfThis = that.isSubtype(this);
if (isSubtypeOfThat && !isSubtypeOfThis) {
return leastSuper ? that : this;
} else if (isSubtypeOfThis && !isSubtypeOfThat) {
return leastSuper ? this : that;
}
// Merge the two functions component-wise.
FunctionType merged = tryMergeFunctionPiecewise(that, leastSuper);
if (merged != null) {
return merged;
}
}
// The function instance type is a special case
// that lives above the rest of the lattice.
JSType functionInstance = registry.getNativeType(
JSTypeNative.FUNCTION_INSTANCE_TYPE);
if (functionInstance.isEquivalentTo(that)) {
return leastSuper ? that : this;
} else if (functionInstance.isEquivalentTo(this)) {
return leastSuper ? this : that;
}
// In theory, we should be using the GREATEST_FUNCTION_TYPE as the
// greatest function. In practice, we don't because it's way too
// broad. The greatest function takes var_args None parameters, which
// means that all parameters register a type warning.
//
// Instead, we use the U2U ctor type, which has unknown type args.
FunctionType greatestFn =
registry.getNativeFunctionType(JSTypeNative.U2U_CONSTRUCTOR_TYPE);
FunctionType leastFn =
registry.getNativeFunctionType(JSTypeNative.LEAST_FUNCTION_TYPE);
return leastSuper ? greatestFn : leastFn;
}
/**
* Try to get the sup/inf of two functions by looking at the
* piecewise components.
*/
private FunctionType tryMergeFunctionPiecewise(
FunctionType other, boolean leastSuper) {
Node newParamsNode = null;
if (call.hasEqualParameters(other.call, EquivalenceMethod.IDENTITY, EqCache.create())) {
newParamsNode = call.parameters;
} else {
// If the parameters are not equal, don't try to merge them.
// Someday, we should try to merge the individual params.
return null;
}
JSType newReturnType = leastSuper ?
call.returnType.getLeastSupertype(other.call.returnType) :
call.returnType.getGreatestSubtype(other.call.returnType);
JSType newTypeOfThis = null;
if (isEquivalent(typeOfThis, other.typeOfThis)) {
newTypeOfThis = typeOfThis;
} else {
JSType maybeNewTypeOfThis = leastSuper ?
typeOfThis.getLeastSupertype(other.typeOfThis) :
typeOfThis.getGreatestSubtype(other.typeOfThis);
newTypeOfThis = maybeNewTypeOfThis;
}
boolean newReturnTypeInferred =
call.returnTypeInferred || other.call.returnTypeInferred;
return new FunctionType(
registry, null, null,
new ArrowType(
registry, newParamsNode, newReturnType, newReturnTypeInferred),
newTypeOfThis, null, false, false);
}
/**
* Given a constructor or an interface type, get its superclass constructor
* or {@code null} if none exists.
*/
public FunctionType getSuperClassConstructor() {
Preconditions.checkArgument(isConstructor() || isInterface());
ObjectType maybeSuperInstanceType = getPrototype().getImplicitPrototype();
if (maybeSuperInstanceType == null) {
return null;
}
return maybeSuperInstanceType.getConstructor();
}
/**
* Given an interface and a property, finds the top-most super interface
* that has the property defined (including this interface).
*/
public static ObjectType getTopDefiningInterface(ObjectType type,
String propertyName) {
ObjectType foundType = null;
if (type.hasProperty(propertyName)) {
foundType = type;
}
for (ObjectType interfaceType : type.getCtorExtendedInterfaces()) {
if (interfaceType.hasProperty(propertyName)) {
foundType = getTopDefiningInterface(interfaceType, propertyName);
}
}
return foundType;
}
/**
* Given a constructor or an interface type and a property, finds the
* top-most superclass that has the property defined (including this
* constructor).
*/
public ObjectType getTopMostDefiningType(String propertyName) {
Preconditions.checkState(isConstructor() || isInterface());
Preconditions.checkArgument(getInstanceType().hasProperty(propertyName));
FunctionType ctor = this;
if (isInterface()) {
return getTopDefiningInterface(getInstanceType(), propertyName);
}
ObjectType topInstanceType = null;
do {
topInstanceType = ctor.getInstanceType();
ctor = ctor.getSuperClassConstructor();
} while (ctor != null
&& ctor.getPrototype().hasProperty(propertyName));
return topInstanceType;
}
/**
* Two function types are equal if their signatures match. Since they don't
* have signatures, two interfaces are equal if their names match.
*/
boolean checkFunctionEquivalenceHelper(
FunctionType that, EquivalenceMethod eqMethod, EqCache eqCache) {
if (isConstructor()) {
if (that.isConstructor()) {
return this == that;
}
return false;
}
if (isInterface()) {
if (that.isInterface()) {
if (getReferenceName().equals(that.getReferenceName())) {
return true;
} else {
if (this.isStructuralInterface()
&& that.isStructuralInterface()) {
return checkStructuralInterfaceEquivalenceHelper(
that, eqMethod, eqCache);
}
return false;
}
}
return false;
}
if (that.isInterface()) {
return false;
}
return typeOfThis.checkEquivalenceHelper(that.typeOfThis, eqMethod, eqCache) &&
call.checkArrowEquivalenceHelper(that.call, eqMethod, eqCache);
}
boolean checkStructuralInterfaceEquivalenceHelper(
final JSType that, EquivalenceMethod eqMethod, EqCache eqCache) {
Preconditions.checkState(eqCache.isStructuralTyping());
Preconditions.checkState(this.isStructuralInterface());
Preconditions.checkState(that.isRecordType() || that.isFunctionType());
MatchStatus result = eqCache.checkCache(this, that);
if (result != null) {
return result.subtypeValue();
}
if (this.hasAnyTemplateTypes() || that.hasAnyTemplateTypes()) {
return false;
}
Map<String, JSType> thisPropList = getPropertyTypeMap(this);
Map<String, JSType> thatPropList = that.isRecordType()
? that.toMaybeRecordType().getOwnPropertyTypeMap()
: getPropertyTypeMap(that.toMaybeFunctionType());
if (thisPropList.size() != thatPropList.size()) {
eqCache.updateCache(this, that, MatchStatus.NOT_MATCH);
return false;
}
for (String propName : thisPropList.keySet()) {
JSType typeInInterface = thisPropList.get(propName);
JSType typeInFunction = thatPropList.get(propName);
if (typeInFunction == null
|| !typeInFunction.checkEquivalenceHelper(
typeInInterface, eqMethod, eqCache)) {
eqCache.updateCache(this, that, MatchStatus.NOT_MATCH);
return false;
}
}
eqCache.updateCache(this, that, MatchStatus.MATCH);
return true;
}
@Override
public int hashCode() {
return isInterface() ? getReferenceName().hashCode() : call.hashCode();
}
public boolean hasEqualCallType(FunctionType otherType) {
return this.call.checkArrowEquivalenceHelper(
otherType.call, EquivalenceMethod.IDENTITY, EqCache.create());
}
/**
* Informally, a function is represented by
* {@code function (params): returnType} where the {@code params} is a comma
* separated list of types, the first one being a special
* {@code this:T} if the function expects a known type for {@code this}.
*/
@Override
String toStringHelper(boolean forAnnotations) {
if (!isPrettyPrint() ||
this == registry.getNativeType(JSTypeNative.FUNCTION_INSTANCE_TYPE)) {
return "Function";
}
setPrettyPrint(false);
StringBuilder b = new StringBuilder(32);
b.append("function (");
int paramNum = call.parameters.getChildCount();
boolean hasKnownTypeOfThis = !(typeOfThis instanceof UnknownType);
if (hasKnownTypeOfThis) {
if (isConstructor()) {
b.append("new:");
} else {
b.append("this:");
}
b.append(typeOfThis.toStringHelper(forAnnotations));
}
if (paramNum > 0) {
if (hasKnownTypeOfThis) {
b.append(", ");
}
Node p = call.parameters.getFirstChild();
appendArgString(b, p, forAnnotations);
p = p.getNext();
while (p != null) {
b.append(", ");
appendArgString(b, p, forAnnotations);
p = p.getNext();
}
}
b.append("): ");
b.append(call.returnType.toStringHelper(forAnnotations));
setPrettyPrint(true);
return b.toString();
}
private void appendArgString(
StringBuilder b, Node p, boolean forAnnotations) {
if (p.isVarArgs()) {
appendVarArgsString(b, p.getJSType(), forAnnotations);
} else if (p.isOptionalArg()) {
appendOptionalArgString(b, p.getJSType(), forAnnotations);
} else {
b.append(p.getJSType().toStringHelper(forAnnotations));
}
}
/** Gets the string representation of a var args param. */
private void appendVarArgsString(StringBuilder builder, JSType paramType,
boolean forAnnotations) {
if (paramType.isUnionType()) {
// Remove the optionality from the var arg.
paramType = paramType.toMaybeUnionType().getRestrictedUnion(
registry.getNativeType(JSTypeNative.VOID_TYPE));
}
builder.append("...").append(
paramType.toStringHelper(forAnnotations));
}
/** Gets the string representation of an optional param. */
private void appendOptionalArgString(
StringBuilder builder, JSType paramType, boolean forAnnotations) {
if (paramType.isUnionType()) {
// Remove the optionality from the var arg.
paramType = paramType.toMaybeUnionType().getRestrictedUnion(
registry.getNativeType(JSTypeNative.VOID_TYPE));
}
builder.append(paramType.toStringHelper(forAnnotations)).append("=");
}
/**
* A function is a subtype of another if their call methods are related via
* subtyping and {@code this} is a subtype of {@code that} with regard to
* the prototype chain.
*/
@Override
public boolean isSubtype(JSType that) {
return isSubtype(that, ImplCache.create());
}
@Override
protected boolean isSubtype(JSType that,
ImplCache implicitImplCache) {
if (JSType.isSubtypeHelper(this, that, implicitImplCache)) {
return true;
}
if (that.isFunctionType()) {
FunctionType other = that.toMaybeFunctionType();
if (other.isInterface()) {
// Any function can be assigned to an interface function.
return true;
}
if (isInterface()) {
// An interface function cannot be assigned to anything.
return false;
}
return treatThisTypesAsCovariant(other, implicitImplCache)
&& this.call.isSubtype(other.call, implicitImplCache);
}
return getNativeType(JSTypeNative.FUNCTION_PROTOTYPE)
.isSubtype(that, implicitImplCache);
}
protected boolean treatThisTypesAsCovariant(FunctionType other,
ImplCache implicitImplCache) {
// If functionA is a subtype of functionB, then their "this" types
// should be contravariant. However, this causes problems because
// of the way we enforce overrides. Because function(this:SubFoo)
// is not a subtype of function(this:Foo), our override check treats
// this as an error. Let's punt on all this for now.
// TODO(nicksantos): fix this.
boolean treatThisTypesAsCovariant =
// An interface 'this'-type is non-restrictive.
// In practical terms, if C implements I, and I has a method m,
// then any m doesn't necessarily have to C#m's 'this'
// type doesn't need to match I.
(other.typeOfThis.toObjectType() != null &&
other.typeOfThis.toObjectType().getConstructor() != null &&
other.typeOfThis.toObjectType().getConstructor().isInterface()) ||
// If one of the 'this' types is covariant of the other,
// then we'll treat them as covariant (see comment above).
other.typeOfThis.isSubtype(this.typeOfThis, implicitImplCache) ||
this.typeOfThis.isSubtype(other.typeOfThis, implicitImplCache);
return treatThisTypesAsCovariant;
}
@Override
public <T> T visit(Visitor<T> visitor) {
return visitor.caseFunctionType(this);
}
@Override <T> T visit(RelationshipVisitor<T> visitor, JSType that) {
return visitor.caseFunctionType(this, that);
}
/**
* Gets the type of instance of this function.
* @throws IllegalStateException if this function is not a constructor
* (see {@link #isConstructor()}).
*/
@Override
public ObjectType getInstanceType() {
Preconditions.checkState(hasInstanceType());
return typeOfThis.toObjectType();
}
/**
* Sets the instance type. This should only be used for special
* native types.
*/
void setInstanceType(ObjectType instanceType) {
typeOfThis = instanceType;
}
/**
* Returns whether this function type has an instance type.
*/
public boolean hasInstanceType() {
return isConstructor() || isInterface();
}
/**
* Gets the type of {@code this} in this function.
*/
@Override
public JSType getTypeOfThis() {
return typeOfThis.isEmptyType() ?
registry.getNativeObjectType(JSTypeNative.UNKNOWN_TYPE) : typeOfThis;
}
/**
* Gets the source node or null if this is an unknown function.
*/
@Override
public Node getSource() {
return source;
}
/**
* Sets the source node.
*/
@Override
public void setSource(Node source) {
if (prototypeSlot != null) {
// NOTE(bashir): On one hand when source is null we want to drop any
// references to old nodes retained in prototypeSlot. On the other hand
// we cannot simply drop prototypeSlot, so we retain all information
// except the propertyNode for which we use an approximation! These
// details mostly matter in hot-swap passes.
if (source == null || prototypeSlot.getNode() == null) {
prototypeSlot = new Property(prototypeSlot.getName(),
prototypeSlot.getType(), prototypeSlot.isTypeInferred(), source);
}
}
this.source = source;
}
void addSubTypeIfNotPresent(FunctionType subType) {
if (subTypes == null || !subTypes.contains(subType)) {
addSubType(subType);
}
}
/** Adds a type to the list of subtypes for this type. */
private void addSubType(FunctionType subType) {
if (subTypes == null) {
subTypes = new ArrayList<>();
}
subTypes.add(subType);
}
@Override
public void clearCachedValues() {
super.clearCachedValues();
if (subTypes != null) {
for (FunctionType subType : subTypes) {
subType.clearCachedValues();
}
}
if (!isNativeObjectType()) {
if (hasInstanceType()) {
getInstanceType().clearCachedValues();
}
if (prototypeSlot != null) {
((ObjectType) prototypeSlot.getType()).clearCachedValues();
}
}
}
/**
* Returns a list of types that are subtypes of this type. This is only valid
* for constructor functions, and may be null. This allows a downward
* traversal of the subtype graph.
*/
@Override
public List<FunctionType> getSubTypes() {
return subTypes;
}
@Override
public boolean hasCachedValues() {
return prototypeSlot != null || super.hasCachedValues();
}
@Override
JSType resolveInternal(ErrorReporter t, StaticTypedScope<JSType> scope) {
setResolvedTypeInternal(this);
call = (ArrowType) safeResolve(call, t, scope);
if (prototypeSlot != null) {
prototypeSlot.setType(
safeResolve(prototypeSlot.getType(), t, scope));
}
// Warning about typeOfThis if it doesn't resolve to an ObjectType
// is handled further upstream.
//
// TODO(nicksantos): Handle this correctly if we have a UnionType.
JSType maybeTypeOfThis = safeResolve(typeOfThis, t, scope);
if (maybeTypeOfThis != null) {
if (maybeTypeOfThis.isNullType() || maybeTypeOfThis.isVoidType()) {
typeOfThis = maybeTypeOfThis;
} else {
maybeTypeOfThis = ObjectType.cast(
maybeTypeOfThis.restrictByNotNullOrUndefined());
if (maybeTypeOfThis != null) {
typeOfThis = maybeTypeOfThis;
}
}
}
ImmutableList<ObjectType> resolvedImplemented =
resolveTypeListHelper(implementedInterfaces, t, scope);
if (resolvedImplemented != null) {
implementedInterfaces = resolvedImplemented;
}
ImmutableList<ObjectType> resolvedExtended =
resolveTypeListHelper(extendedInterfaces, t, scope);
if (resolvedExtended != null) {
extendedInterfaces = resolvedExtended;
}
if (subTypes != null) {
for (int i = 0; i < subTypes.size(); i++) {
subTypes.set(
i, JSType.toMaybeFunctionType(subTypes.get(i).resolve(t, scope)));
}
}
return super.resolveInternal(t, scope);
}
/**
* Resolve each item in the list, and return a new list if any
* references changed. Otherwise, return null.
*/
private ImmutableList<ObjectType> resolveTypeListHelper(
ImmutableList<ObjectType> list,
ErrorReporter t,
StaticTypedScope<JSType> scope) {
boolean changed = false;
ImmutableList.Builder<ObjectType> resolvedList =
ImmutableList.builder();
for (ObjectType type : list) {
ObjectType resolved = (ObjectType) type.resolve(t, scope);
resolvedList.add(resolved);
changed |= (resolved != type);
}
return changed ? resolvedList.build() : null;
}
@Override
public String toDebugHashCodeString() {
if (this == registry.getNativeType(JSTypeNative.FUNCTION_INSTANCE_TYPE)) {
return super.toDebugHashCodeString();
}
StringBuilder b = new StringBuilder(32);
b.append("function (");
int paramNum = call.parameters.getChildCount();
boolean hasKnownTypeOfThis = !typeOfThis.isUnknownType();
if (hasKnownTypeOfThis) {
b.append("this:");
b.append(getDebugHashCodeStringOf(typeOfThis));
}
if (paramNum > 0) {
if (hasKnownTypeOfThis) {
b.append(", ");
}
Node p = call.parameters.getFirstChild();
b.append(getDebugHashCodeStringOf(p.getJSType()));
p = p.getNext();
while (p != null) {
b.append(", ");
b.append(getDebugHashCodeStringOf(p.getJSType()));
p = p.getNext();
}
}
b.append(")");
b.append(": ");
b.append(getDebugHashCodeStringOf(call.returnType));
return b.toString();
}
private String getDebugHashCodeStringOf(JSType type) {
if (type == this) {
return "me";
} else {
return type.toDebugHashCodeString();
}
}
/** Create a new constructor with the parameters and return type stripped. */
public FunctionType forgetParameterAndReturnTypes() {
FunctionType result = new FunctionType(
registry, getReferenceName(), source,
registry.createArrowType(null, null), getInstanceType(),
null, true, false);
result.setPrototypeBasedOn(getInstanceType());
return result;
}
@Override
public boolean hasAnyTemplateTypesInternal() {
return getTemplateTypeMap().numUnfilledTemplateKeys() > 0
|| typeOfThis.hasAnyTemplateTypes()
|| call.hasAnyTemplateTypes();
}
@Override
public TypeI convertMethodToFunction() {
List<JSType> paramTypes = new ArrayList<>();
paramTypes.add(getTypeOfThis());
for (Node param : getParameters()) {
paramTypes.add(param.getJSType());
}
return registry.createFunctionTypeWithInstanceType(
registry.getNativeObjectType(JSTypeNative.UNKNOWN_TYPE),
getReturnType(),
paramTypes);
}
@Override
public boolean hasProperties() {
if (prototypeSlot != null) {
return true;
}
return !super.getOwnPropertyNames().isEmpty();
}
/**
* sets the current interface type to support
* structural interface matching (abbr. SMI)
* @param flag indicates whether or not it should support SMI
*/
public void setImplicitMatch(boolean flag) {
Preconditions.checkState(isInterface());
isStructuralInterface = flag;
}
@Override
public boolean isStructuralInterface() {
return isInterface() && isStructuralInterface;
}
@Override
public boolean isStructuralType() {
return isStructuralInterface();
}
/**
* get the map of properties to types covered in a function type
* @return a Map that maps the property's name to the property's type
*/
@Override
public Map<String, JSType> getPropertyTypeMap() {
Map<String, JSType> propTypeMap = new LinkedHashMap<>();
updatePropertyTypeMap(this, propTypeMap, new HashSet<FunctionType>());
return propTypeMap;
}
// cache is added to prevent infinite recursion when retrieving
// the super type: see testInterfaceExtendsLoop in TypeCheckTest.java
private static void updatePropertyTypeMap(
FunctionType type, Map<String, JSType> propTypeMap,
HashSet<FunctionType> cache) {
if (type == null) { return; }
// retrieve all property types on the prototype of this class
ObjectType prototype = type.getPrototype();
if (prototype != null) {
Set<String> propNames = prototype.getOwnPropertyNames();
for (String name : propNames) {
if (!propTypeMap.containsKey(name)) {
JSType propType = prototype.getPropertyType(name);
propTypeMap.put(name, propType);
}
}
}
// retrieve all property types from its super class
Iterable<ObjectType> iterable = type.getExtendedInterfaces();
if (iterable != null) {
for (ObjectType interfaceType : iterable) {
FunctionType superConstructor = interfaceType.getConstructor();
if (superConstructor == null
|| cache.contains(superConstructor)) { continue; }
cache.add(superConstructor);
updatePropertyTypeMap(superConstructor, propTypeMap, cache);
cache.remove(superConstructor);
}
}
}
/**
* check if there is a loop in the type extends chain
* @return an array of all functions in the loop chain if
* a loop exists, otherwise returns null
*/
public List<FunctionType> checkExtendsLoop() {
return checkExtendsLoop(new HashSet<FunctionType>(),
new ArrayList<FunctionType>());
}
public List<FunctionType> checkExtendsLoop(HashSet<FunctionType> cache,
List<FunctionType> path) {
Iterable<ObjectType> iterable = this.getExtendedInterfaces();
if (iterable != null) {
for (ObjectType interfaceType : iterable) {
FunctionType superConstructor = interfaceType.getConstructor();
if (superConstructor == null) { continue; }
if (cache.contains(superConstructor)) {
// after detecting a loop, prune and return the path, e.g.,:
// A -> B -> C -> D -> C, will be pruned into:
// c -> D -> C
path.add(superConstructor);
while (path.get(0) != superConstructor) {
path.remove(0);
}
return path;
}
cache.add(superConstructor);
path.add(superConstructor);
List<FunctionType> result =
superConstructor.checkExtendsLoop(cache, path);
if (result != null) {
return result;
}
cache.remove(superConstructor);
path.remove(path.size() - 1);
}
}
return null;
}
}
| rintaro/closure-compiler | src/com/google/javascript/rhino/jstype/FunctionType.java | Java | apache-2.0 | 50,077 |
/*
* 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.
*/
/*
* This is not the original file distributed by the Apache Software Foundation
* It has been modified by the Hipparchus project
*/
package org.hipparchus.stat.descriptive.rank;
import java.io.Serializable;
import org.hipparchus.exception.MathIllegalArgumentException;
import org.hipparchus.exception.NullArgumentException;
import org.hipparchus.stat.descriptive.AbstractStorelessUnivariateStatistic;
import org.hipparchus.stat.descriptive.AggregatableStatistic;
import org.hipparchus.util.MathArrays;
import org.hipparchus.util.MathUtils;
/**
* Returns the maximum of the available values.
* <p>
* <ul>
* <li>The result is <code>NaN</code> iff all values are <code>NaN</code>
* (i.e. <code>NaN</code> values have no impact on the value of the statistic).</li>
* <li>If any of the values equals <code>Double.POSITIVE_INFINITY</code>,
* the result is <code>Double.POSITIVE_INFINITY.</code></li>
* </ul>
* <p>
* <strong>Note that this implementation is not synchronized.</strong> If
* multiple threads access an instance of this class concurrently, and at least
* one of the threads invokes the <code>increment()</code> or
* <code>clear()</code> method, it must be synchronized externally.
*/
public class Max extends AbstractStorelessUnivariateStatistic
implements AggregatableStatistic<Max>, Serializable {
/** Serializable version identifier */
private static final long serialVersionUID = 20150412L;
/** Number of values that have been added */
private long n;
/** Current value of the statistic */
private double value;
/**
* Create a Max instance.
*/
public Max() {
n = 0;
value = Double.NaN;
}
/**
* Copy constructor, creates a new {@code Max} identical
* to the {@code original}.
*
* @param original the {@code Max} instance to copy
* @throws NullArgumentException if original is null
*/
public Max(Max original) throws NullArgumentException {
MathUtils.checkNotNull(original);
this.n = original.n;
this.value = original.value;
}
/** {@inheritDoc} */
@Override
public void increment(final double d) {
if (d > value || Double.isNaN(value)) {
value = d;
}
n++;
}
/** {@inheritDoc} */
@Override
public void clear() {
value = Double.NaN;
n = 0;
}
/** {@inheritDoc} */
@Override
public double getResult() {
return value;
}
/** {@inheritDoc} */
@Override
public long getN() {
return n;
}
/** {@inheritDoc} */
@Override
public void aggregate(Max other) {
MathUtils.checkNotNull(other);
if (other.n > 0) {
if (other.value > this.value || Double.isNaN(this.value)) {
this.value = other.value;
}
this.n += other.n;
}
}
/**
* Returns the maximum of the entries in the specified portion of
* the input array, or <code>Double.NaN</code> if the designated subarray
* is empty.
* <p>
* Throws <code>MathIllegalArgumentException</code> if the array is null or
* the array index parameters are not valid.
* <p>
* <ul>
* <li>The result is <code>NaN</code> iff all values are <code>NaN</code>
* (i.e. <code>NaN</code> values have no impact on the value of the statistic).</li>
* <li>If any of the values equals <code>Double.POSITIVE_INFINITY</code>,
* the result is <code>Double.POSITIVE_INFINITY.</code></li>
* </ul>
*
* @param values the input array
* @param begin index of the first array element to include
* @param length the number of elements to include
* @return the maximum of the values or Double.NaN if length = 0
* @throws MathIllegalArgumentException if the array is null or the array index
* parameters are not valid
*/
@Override
public double evaluate(final double[] values, final int begin, final int length)
throws MathIllegalArgumentException {
double max = Double.NaN;
if (MathArrays.verifyValues(values, begin, length)) {
max = values[begin];
for (int i = begin; i < begin + length; i++) {
if (!Double.isNaN(values[i])) {
max = (max > values[i]) ? max : values[i];
}
}
}
return max;
}
/** {@inheritDoc} */
@Override
public Max copy() {
return new Max(this);
}
}
| sdinot/hipparchus | hipparchus-stat/src/main/java/org/hipparchus/stat/descriptive/rank/Max.java | Java | apache-2.0 | 5,341 |
/*
* Copyright (c) 2008-2021, Hazelcast, Inc. 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.hazelcast.sql.impl.exec.root;
import com.hazelcast.sql.impl.QueryResultProducer;
import com.hazelcast.sql.impl.row.Row;
import java.util.List;
/**
* Consumer of results from {@link RootExec}.
*/
public interface RootResultConsumer extends QueryResultProducer {
/**
* Perform one-time setup.
*
* @param scheduleCallback A callback to ask for more rows to be consumed
*/
void setup(ScheduleCallback scheduleCallback);
/**
* Consume rows from the root operator. The implementation should either consume all rows, or none. If the rows are consumed,
* the ownership is transferred to the consumer, i.e. no copy of the batch is required.
*
* @param batch Rows.
* @param last Whether this is the last batch.
* @return {@code true} if rows were consumed, {@code false} otherwise.
*/
boolean consume(List<Row> batch, boolean last);
}
| emre-aydin/hazelcast | hazelcast/src/main/java/com/hazelcast/sql/impl/exec/root/RootResultConsumer.java | Java | apache-2.0 | 1,541 |
/*******************************************************************************
*
* Copyright FUJITSU LIMITED 2017
*
* Creation Date: 2012-01-17
*
*******************************************************************************/
package org.oscm.internal.types.exception.beans;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import org.oscm.internal.types.exception.SubscriptionMigrationException;
import org.oscm.internal.types.exception.SubscriptionMigrationException.Reason;
/**
* Bean for JAX-WS exception serialization, specific for
* {@link SubscriptionMigrationException}.
*/
@XmlRootElement(name = "SubscriptionMigrationExceptionBean")
@XmlAccessorType(XmlAccessType.PROPERTY)
public class SubscriptionMigrationExceptionBean extends
ApplicationExceptionBean {
private static final long serialVersionUID = 397354781229340191L;
private Reason reason;
/**
* Default constructor.
*/
public SubscriptionMigrationExceptionBean() {
super();
}
/**
* Instantiates a <code>SubscriptionMigrationExceptionBean</code> based on
* the specified <code>ApplicationExceptionBean</code> and sets the given
* reason.
*
* @param sup
* the <code>ApplicationExceptionBean</code> to use as the base
* @param reason
* the reason for the exception
*/
public SubscriptionMigrationExceptionBean(ApplicationExceptionBean sup,
Reason reason) {
super(sup);
setReason(reason);
}
/**
* Returns the reason for the exception.
*
* @return the reason
*/
public Reason getReason() {
return reason;
}
/**
* Sets the reason for the exception.
*
* @param reason
* the reason
*/
public void setReason(Reason reason) {
this.reason = reason;
}
}
| opetrovski/development | oscm-extsvc-internal/javasrc/org/oscm/internal/types/exception/beans/SubscriptionMigrationExceptionBean.java | Java | apache-2.0 | 2,200 |
package org.hl7.v3;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for COCT_MT230100UV.Ingredient complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="COCT_MT230100UV.Ingredient">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <group ref="{urn:hl7-org:v3}InfrastructureRootElements"/>
* <element name="quantity" type="{urn:hl7-org:v3}RTO_QTY_QTY" minOccurs="0"/>
* <element name="ingredient" type="{urn:hl7-org:v3}COCT_MT230100UV.Substance" minOccurs="0"/>
* </sequence>
* <attGroup ref="{urn:hl7-org:v3}InfrastructureRootAttributes"/>
* <attribute name="nullFlavor" type="{urn:hl7-org:v3}NullFlavor" />
* <attribute name="classCode" use="required" type="{urn:hl7-org:v3}RoleClassIngredientEntity" />
* <attribute name="negationInd" type="{urn:hl7-org:v3}bl" default="false" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "COCT_MT230100UV.Ingredient", propOrder = {
"realmCode",
"typeId",
"templateId",
"quantity",
"ingredient"
})
public class COCTMT230100UVIngredient {
protected List<CS> realmCode;
protected II typeId;
protected List<II> templateId;
protected RTOQTYQTY quantity;
@XmlElementRef(name = "ingredient", namespace = "urn:hl7-org:v3", type = JAXBElement.class, required = false)
protected JAXBElement<COCTMT230100UVSubstance> ingredient;
@XmlAttribute(name = "nullFlavor")
protected List<String> nullFlavor;
@XmlAttribute(name = "classCode", required = true)
protected String classCode;
@XmlAttribute(name = "negationInd")
protected Boolean negationInd;
/**
* Gets the value of the realmCode property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the realmCode property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRealmCode().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CS }
*
*
*/
public List<CS> getRealmCode() {
if (realmCode == null) {
realmCode = new ArrayList<CS>();
}
return this.realmCode;
}
/**
* Gets the value of the typeId property.
*
* @return
* possible object is
* {@link II }
*
*/
public II getTypeId() {
return typeId;
}
/**
* Sets the value of the typeId property.
*
* @param value
* allowed object is
* {@link II }
*
*/
public void setTypeId(II value) {
this.typeId = value;
}
/**
* Gets the value of the templateId property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the templateId property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTemplateId().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link II }
*
*
*/
public List<II> getTemplateId() {
if (templateId == null) {
templateId = new ArrayList<II>();
}
return this.templateId;
}
/**
* Gets the value of the quantity property.
*
* @return
* possible object is
* {@link RTOQTYQTY }
*
*/
public RTOQTYQTY getQuantity() {
return quantity;
}
/**
* Sets the value of the quantity property.
*
* @param value
* allowed object is
* {@link RTOQTYQTY }
*
*/
public void setQuantity(RTOQTYQTY value) {
this.quantity = value;
}
/**
* Gets the value of the ingredient property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link COCTMT230100UVSubstance }{@code >}
*
*/
public JAXBElement<COCTMT230100UVSubstance> getIngredient() {
return ingredient;
}
/**
* Sets the value of the ingredient property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link COCTMT230100UVSubstance }{@code >}
*
*/
public void setIngredient(JAXBElement<COCTMT230100UVSubstance> value) {
this.ingredient = value;
}
/**
* Gets the value of the nullFlavor property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the nullFlavor property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getNullFlavor().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getNullFlavor() {
if (nullFlavor == null) {
nullFlavor = new ArrayList<String>();
}
return this.nullFlavor;
}
/**
* Gets the value of the classCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getClassCode() {
return classCode;
}
/**
* Sets the value of the classCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setClassCode(String value) {
this.classCode = value;
}
/**
* Gets the value of the negationInd property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public boolean isNegationInd() {
if (negationInd == null) {
return false;
} else {
return negationInd;
}
}
/**
* Sets the value of the negationInd property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setNegationInd(Boolean value) {
this.negationInd = value;
}
}
| KRMAssociatesInc/eHMP | lib/mvi/org/hl7/v3/COCTMT230100UVIngredient.java | Java | apache-2.0 | 7,481 |
/**
* 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.blueprint;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.camel.LoadPropertiesException;
import org.apache.camel.TypeConverter;
import org.apache.camel.blueprint.handler.CamelNamespaceHandler;
import org.apache.camel.core.osgi.OsgiBeanRepository;
import org.apache.camel.core.osgi.OsgiCamelContextHelper;
import org.apache.camel.core.osgi.OsgiCamelContextPublisher;
import org.apache.camel.core.osgi.OsgiFactoryFinderResolver;
import org.apache.camel.core.osgi.OsgiTypeConverter;
import org.apache.camel.core.osgi.utils.BundleContextUtils;
import org.apache.camel.core.osgi.utils.BundleDelegatingClassLoader;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.spi.BeanRepository;
import org.apache.camel.spi.EventNotifier;
import org.apache.camel.spi.FactoryFinder;
import org.apache.camel.spi.ModelJAXBContextFactory;
import org.apache.camel.support.DefaultRegistry;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.blueprint.container.BlueprintContainer;
import org.osgi.service.blueprint.container.BlueprintEvent;
import org.osgi.service.blueprint.container.BlueprintListener;
/**
* OSGi Blueprint based {@link org.apache.camel.CamelContext}.
*/
public class BlueprintCamelContext extends DefaultCamelContext implements ServiceListener, BlueprintListener {
protected final AtomicBoolean routeDefinitionValid = new AtomicBoolean(true);
private BundleContext bundleContext;
private BlueprintContainer blueprintContainer;
private ServiceRegistration<?> registration;
private BlueprintCamelStateService bundleStateService;
public BlueprintCamelContext(BundleContext bundleContext, BlueprintContainer blueprintContainer) {
super(false);
this.bundleContext = bundleContext;
this.blueprintContainer = blueprintContainer;
// inject common osgi
OsgiCamelContextHelper.osgiUpdate(this, bundleContext);
// and these are blueprint specific
BeanRepository repo1 = new BlueprintContainerBeanRepository(getBlueprintContainer());
OsgiBeanRepository repo2 = new OsgiBeanRepository(bundleContext);
setRegistry(new DefaultRegistry(repo1, repo2));
// Need to clean up the OSGi service when camel context is closed.
addLifecycleStrategy(repo2);
setComponentResolver(new BlueprintComponentResolver(bundleContext));
setLanguageResolver(new BlueprintLanguageResolver(bundleContext));
setDataFormatResolver(new BlueprintDataFormatResolver(bundleContext));
setApplicationContextClassLoader(new BundleDelegatingClassLoader(bundleContext.getBundle()));
init();
}
@Override
protected ModelJAXBContextFactory createModelJAXBContextFactory() {
// must use classloader of the namespace handler
return new BlueprintModelJAXBContextFactory(CamelNamespaceHandler.class.getClassLoader());
}
public BundleContext getBundleContext() {
return bundleContext;
}
public void setBundleContext(BundleContext bundleContext) {
this.bundleContext = bundleContext;
}
public BlueprintContainer getBlueprintContainer() {
return blueprintContainer;
}
public void setBlueprintContainer(BlueprintContainer blueprintContainer) {
this.blueprintContainer = blueprintContainer;
}
public BlueprintCamelStateService getBundleStateService() {
return bundleStateService;
}
public void setBundleStateService(BlueprintCamelStateService bundleStateService) {
this.bundleStateService = bundleStateService;
}
public void doInit() {
log.trace("init {}", this);
// add service listener so we can be notified when blueprint container is done
// and we would be ready to start CamelContext
bundleContext.addServiceListener(this);
// add blueprint listener as service, as we need this for the blueprint container
// to support change events when it changes states
registration = bundleContext.registerService(BlueprintListener.class, this, null);
// call super
super.doInit();
}
public void destroy() throws Exception {
log.trace("destroy {}", this);
// remove listener and stop this CamelContext
try {
bundleContext.removeServiceListener(this);
} catch (Exception e) {
log.warn("Error removing ServiceListener: " + this + ". This exception is ignored.", e);
}
if (registration != null) {
try {
registration.unregister();
} catch (Exception e) {
log.warn("Error unregistering service registration: " + registration + ". This exception is ignored.", e);
}
registration = null;
}
bundleStateService.setBundleState(bundleContext.getBundle(), this.getName(), null);
// must stop Camel
stop();
}
@Override
public Map<String, Properties> findComponents() throws LoadPropertiesException, IOException {
return BundleContextUtils.findComponents(bundleContext, this);
}
@Override
public void blueprintEvent(BlueprintEvent event) {
if (log.isDebugEnabled()) {
String eventTypeString;
switch (event.getType()) {
case BlueprintEvent.CREATING:
eventTypeString = "CREATING";
break;
case BlueprintEvent.CREATED:
eventTypeString = "CREATED";
break;
case BlueprintEvent.DESTROYING:
eventTypeString = "DESTROYING";
break;
case BlueprintEvent.DESTROYED:
eventTypeString = "DESTROYED";
break;
case BlueprintEvent.GRACE_PERIOD:
eventTypeString = "GRACE_PERIOD";
break;
case BlueprintEvent.WAITING:
eventTypeString = "WAITING";
break;
case BlueprintEvent.FAILURE:
eventTypeString = "FAILURE";
break;
default:
eventTypeString = "UNKNOWN";
break;
}
log.debug("Received BlueprintEvent[replay={} type={} bundle={}] %s", event.isReplay(), eventTypeString, event.getBundle().getSymbolicName(), event);
}
if (!event.isReplay() && this.getBundleContext().getBundle().getBundleId() == event.getBundle().getBundleId()) {
if (event.getType() == BlueprintEvent.CREATED) {
try {
log.info("Attempting to start CamelContext: {}", this.getName());
this.maybeStart();
} catch (Exception startEx) {
log.error("Error occurred during starting CamelContext: {}", this.getName(), startEx);
}
} else if (event.getType() == BlueprintEvent.DESTROYING) {
try {
log.info("Stopping CamelContext: {}", this.getName());
this.stop();
} catch (Exception stopEx) {
log.error("Error occurred during stopping CamelContext: {}", this.getName(), stopEx);
}
}
}
}
@Override
public void serviceChanged(ServiceEvent event) {
if (log.isTraceEnabled()) {
String eventTypeString;
switch (event.getType()) {
case ServiceEvent.REGISTERED:
eventTypeString = "REGISTERED";
break;
case ServiceEvent.MODIFIED:
eventTypeString = "MODIFIED";
break;
case ServiceEvent.UNREGISTERING:
eventTypeString = "UNREGISTERING";
break;
case ServiceEvent.MODIFIED_ENDMATCH:
eventTypeString = "MODIFIED_ENDMATCH";
break;
default:
eventTypeString = "UNKNOWN";
break;
}
// use trace logging as this is very noisy
log.trace("Service: {} changed to: {}", event, eventTypeString);
}
}
@Override
protected TypeConverter createTypeConverter() {
// CAMEL-3614: make sure we use a bundle context which imports org.apache.camel.impl.converter package
BundleContext ctx = BundleContextUtils.getBundleContext(getClass());
if (ctx == null) {
ctx = bundleContext;
}
FactoryFinder finder = new OsgiFactoryFinderResolver(bundleContext).resolveDefaultFactoryFinder(getClassResolver());
return new OsgiTypeConverter(ctx, this, getInjector(), finder);
}
@Override
public void start() throws Exception {
final ClassLoader original = Thread.currentThread().getContextClassLoader();
try {
// let's set a more suitable TCCL while starting the context
Thread.currentThread().setContextClassLoader(getApplicationContextClassLoader());
bundleStateService.setBundleState(bundleContext.getBundle(), this.getName(), BlueprintCamelStateService.State.Starting);
super.start();
bundleStateService.setBundleState(bundleContext.getBundle(), this.getName(), BlueprintCamelStateService.State.Active);
} catch (Exception e) {
bundleStateService.setBundleState(bundleContext.getBundle(), this.getName(), BlueprintCamelStateService.State.Failure, e);
routeDefinitionValid.set(false);
throw e;
} finally {
Thread.currentThread().setContextClassLoader(original);
}
}
private void maybeStart() throws Exception {
log.trace("maybeStart: {}", this);
if (!routeDefinitionValid.get()) {
log.trace("maybeStart: {} is skipping since CamelRoute definition is not correct.", this);
return;
}
// allow to register the BluerintCamelContext eager in the OSGi Service Registry, which ex is needed
// for unit testing with camel-test-blueprint
boolean eager = "true".equalsIgnoreCase(System.getProperty("registerBlueprintCamelContextEager"));
if (eager) {
for (EventNotifier notifier : getManagementStrategy().getEventNotifiers()) {
if (notifier instanceof OsgiCamelContextPublisher) {
OsgiCamelContextPublisher publisher = (OsgiCamelContextPublisher) notifier;
publisher.registerCamelContext(this);
break;
}
}
}
// for example from unit testing we want to start Camel later and not
// when blueprint loading the bundle
boolean skip = "true".equalsIgnoreCase(System.getProperty("skipStartingCamelContext"));
if (skip) {
log.trace("maybeStart: {} is skipping as System property skipStartingCamelContext is set", this);
return;
}
if (!isStarted() && !isStarting()) {
log.debug("Starting {}", this);
start();
} else {
// ignore as Camel is already started
log.trace("Ignoring maybeStart() as {} is already started", this);
}
}
}
| punkhorn/camel-upstream | components/camel-blueprint/src/main/java/org/apache/camel/blueprint/BlueprintCamelContext.java | Java | apache-2.0 | 12,310 |
/*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.apikeys.v2;
/**
* Available OAuth 2.0 scopes for use with the API Keys API.
*
* @since 1.4
*/
public class ApiKeysServiceScopes {
/** See, edit, configure, and delete your Google Cloud data and see the email address for your Google Account.. */
public static final String CLOUD_PLATFORM = "https://www.googleapis.com/auth/cloud-platform";
/** View your data across Google Cloud services and see the email address of your Google Account. */
public static final String CLOUD_PLATFORM_READ_ONLY = "https://www.googleapis.com/auth/cloud-platform.read-only";
/**
* Returns an unmodifiable set that contains all scopes declared by this class.
*
* @since 1.16
*/
public static java.util.Set<String> all() {
java.util.Set<String> set = new java.util.HashSet<String>();
set.add(CLOUD_PLATFORM);
set.add(CLOUD_PLATFORM_READ_ONLY);
return java.util.Collections.unmodifiableSet(set);
}
private ApiKeysServiceScopes() {
}
}
| googleapis/google-api-java-client-services | clients/google-api-services-apikeys/v2/1.31.0/com/google/api/services/apikeys/v2/ApiKeysServiceScopes.java | Java | apache-2.0 | 1,679 |
/*
* Copyright 2017-2022 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.config.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.config.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* GetAggregateResourceConfigResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetAggregateResourceConfigResultJsonUnmarshaller implements Unmarshaller<GetAggregateResourceConfigResult, JsonUnmarshallerContext> {
public GetAggregateResourceConfigResult unmarshall(JsonUnmarshallerContext context) throws Exception {
GetAggregateResourceConfigResult getAggregateResourceConfigResult = new GetAggregateResourceConfigResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return getAggregateResourceConfigResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("ConfigurationItem", targetDepth)) {
context.nextToken();
getAggregateResourceConfigResult.setConfigurationItem(ConfigurationItemJsonUnmarshaller.getInstance().unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return getAggregateResourceConfigResult;
}
private static GetAggregateResourceConfigResultJsonUnmarshaller instance;
public static GetAggregateResourceConfigResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new GetAggregateResourceConfigResultJsonUnmarshaller();
return instance;
}
}
| aws/aws-sdk-java | aws-java-sdk-config/src/main/java/com/amazonaws/services/config/model/transform/GetAggregateResourceConfigResultJsonUnmarshaller.java | Java | apache-2.0 | 2,994 |
package com.action.view.design.principle.liskovsubstitution.methodout;
/**
* @Description TODO
* @Author wuyunfeng
* @Date 2020-05-22 20:32
* @Version 1.0
*/
public class Test {
public static void main(String[] args) {
Child child = new Child();
System.out.println(child.method());
}
}
| pearpai/java_action | src/main/java/com/action/view/design/principle/liskovsubstitution/methodout/Test.java | Java | apache-2.0 | 319 |
/*
* Copyright 2019 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.bremersee.exception;
import org.springframework.lang.Nullable;
/**
* Marker interface to get an error code.
*
* @author Christian Bremer
*/
public interface ErrorCodeAware {
/**
* The default value of the 'code' attribute.
*/
String NO_ERROR_CODE_VALUE = "UNSPECIFIED";
/**
* Gets the error code.
*
* @return the error code
*/
@Nullable
String getErrorCode();
}
| bremersee/common | common-base/src/main/java/org/bremersee/exception/ErrorCodeAware.java | Java | apache-2.0 | 1,028 |
/*
* Copyright 2014-2019 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.simplesystemsmanagement.model.transform;
import java.util.Map;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.simplesystemsmanagement.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* StartSessionRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class StartSessionRequestMarshaller {
private static final MarshallingInfo<String> TARGET_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Target").build();
private static final MarshallingInfo<String> DOCUMENTNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("DocumentName").build();
private static final MarshallingInfo<Map> PARAMETERS_BINDING = MarshallingInfo.builder(MarshallingType.MAP).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Parameters").build();
private static final StartSessionRequestMarshaller instance = new StartSessionRequestMarshaller();
public static StartSessionRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(StartSessionRequest startSessionRequest, ProtocolMarshaller protocolMarshaller) {
if (startSessionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(startSessionRequest.getTarget(), TARGET_BINDING);
protocolMarshaller.marshall(startSessionRequest.getDocumentName(), DOCUMENTNAME_BINDING);
protocolMarshaller.marshall(startSessionRequest.getParameters(), PARAMETERS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| jentfoo/aws-sdk-java | aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/transform/StartSessionRequestMarshaller.java | Java | apache-2.0 | 2,669 |
/**
* Copyright 2018 Mike Hummel
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 de.mhus.lib.core.config;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import de.mhus.lib.core.MFile;
import de.mhus.lib.core.MString;
import de.mhus.lib.errors.MException;
public class JsonConfigFile extends JsonConfig {
private static final long serialVersionUID = 1L;
private File file;
public JsonConfigFile(File file) throws Exception {
super(MFile.readFile(file));
this.file = file;
}
public JsonConfigFile(InputStream is) throws Exception {
super(MFile.readFile(new InputStreamReader(is, MString.CHARSET_UTF_8))); // read utf
this.file = null;
}
public boolean canSave() {
return file != null && file.canWrite();
}
public void save() throws MException {
try {
if (!canSave()) return;
log().t("save config", this);
FileOutputStream os = new FileOutputStream(file);
write(os);
os.close();
} catch (Exception e) {
throw new MException(e);
}
}
@Override
public String toString() {
return getClass() + ": " + (file == null ? "?" : file.getAbsolutePath());
}
public void setName(String name) {
this.name = name;
}
public File getFile() {
return file;
}
}
| mhus/mhus-inka | cao/config/JsonConfigFile.java | Java | apache-2.0 | 1,968 |
package example.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Customer1472 {
@Id @GeneratedValue(strategy = GenerationType.AUTO) private long id;
private String firstName;
private String lastName;
protected Customer1472() {}
public Customer1472(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return String.format("Customer1472[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName);
}
}
| spring-projects/spring-data-examples | jpa/deferred/src/main/java/example/model/Customer1472.java | Java | apache-2.0 | 628 |
/*
* Copyright 2015-2019 Jeeva Kandasamy ([email protected])
* 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.mycontroller.standalone.api.jaxrs;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.mycontroller.standalone.AppProperties;
import org.mycontroller.standalone.api.BackupApi;
import org.mycontroller.standalone.api.jaxrs.model.ApiError;
import org.mycontroller.standalone.api.jaxrs.model.ApiMessage;
import org.mycontroller.standalone.api.jaxrs.model.Query;
import org.mycontroller.standalone.api.jaxrs.utils.RestUtils;
import org.mycontroller.standalone.backup.McFileUtils;
import org.mycontroller.standalone.settings.BackupSettings;
import lombok.extern.slf4j.Slf4j;
/**
* @author Jeeva Kandasamy (jkandasa)
* @since 0.0.3
*/
@Path("/rest/backup")
@Produces(APPLICATION_JSON)
@Consumes(APPLICATION_JSON)
@RolesAllowed({ "admin" })
@Slf4j
public class BackupHandler {
private BackupApi backupApi = new BackupApi();
@GET
@Path("/backupFiles")
public Response getBackupList(@QueryParam(McFileUtils.KEY_NAME) List<String> name,
@QueryParam(Query.PAGE_LIMIT) Long pageLimit,
@QueryParam(Query.PAGE) Long page,
@QueryParam(Query.ORDER_BY) String orderBy,
@QueryParam(Query.ORDER) String order) {
HashMap<String, Object> filters = new HashMap<String, Object>();
filters.put(McFileUtils.KEY_NAME, name);
if (orderBy == null) {
orderBy = McFileUtils.KEY_NAME;
}
//Query primary filters
filters.put(Query.ORDER, order);
filters.put(Query.ORDER_BY, orderBy);
filters.put(Query.PAGE_LIMIT, pageLimit);
filters.put(Query.PAGE, page);
try {
return RestUtils.getResponse(Status.OK, backupApi.getBackupFiles(filters));
} catch (Exception ex) {
_logger.error("Error,", ex);
return RestUtils.getResponse(Status.INTERNAL_SERVER_ERROR, new ApiError(ex.getMessage()));
}
}
@GET
@Path("/backupSettings")
public Response getBackupSettings() {
return RestUtils.getResponse(Status.OK, AppProperties.getInstance().getBackupSettings());
}
@PUT
@Path("/backupSettings")
public Response updateBackupSettings(BackupSettings backupSettings) {
backupSettings.save();
BackupSettings.reloadJob();//Reload backup job
AppProperties.getInstance().setBackupSettings(BackupSettings.get());
return RestUtils.getResponse(Status.OK);
}
@PUT
@Path("/backupNow")
public Response backupNow() {
try {
return RestUtils.getResponse(Status.OK, new ApiMessage(backupApi.backupNow()));
} catch (Exception ex) {
_logger.error("Error,", ex);
return RestUtils.getResponse(Status.BAD_REQUEST, new ApiError(ex.getMessage()));
}
}
@POST
@Path("/delete")
public Response deleteIds(List<String> backupFiles) {
try {
backupApi.deleteBackupFiles(backupFiles);
} catch (IOException ex) {
RestUtils.getResponse(Status.BAD_REQUEST, new ApiError(ex.getMessage()));
}
return RestUtils.getResponse(Status.NO_CONTENT);
}
@POST
@Path("/restore")
public Response restore(String backupFile) {
try {
backupApi.restore(backupFile);
return RestUtils.getResponse(Status.OK, new ApiMessage(
"Server is going to down now! Monitor log file of the server."));
} catch (Exception ex) {
_logger.error("Error in restore,", ex);
return RestUtils.getResponse(Status.BAD_REQUEST, new ApiError(ex.getMessage()));
}
}
}
| mycontroller-org/mycontroller | modules/core/src/main/java/org/mycontroller/standalone/api/jaxrs/BackupHandler.java | Java | apache-2.0 | 4,695 |
/*
* 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.executiongraph;
import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.IllegalConfigurationException;
import org.apache.flink.configuration.JobManagerOptions;
import org.apache.flink.metrics.MetricGroup;
import org.apache.flink.runtime.JobException;
import org.apache.flink.runtime.blob.BlobWriter;
import org.apache.flink.runtime.checkpoint.CheckpointIDCounter;
import org.apache.flink.runtime.checkpoint.CheckpointStatsTracker;
import org.apache.flink.runtime.checkpoint.CheckpointsCleaner;
import org.apache.flink.runtime.checkpoint.CompletedCheckpointStore;
import org.apache.flink.runtime.checkpoint.MasterTriggerRestoreHook;
import org.apache.flink.runtime.checkpoint.hooks.MasterHooks;
import org.apache.flink.runtime.client.JobExecutionException;
import org.apache.flink.runtime.client.JobSubmissionException;
import org.apache.flink.runtime.deployment.TaskDeploymentDescriptorFactory;
import org.apache.flink.runtime.executiongraph.failover.flip1.partitionrelease.PartitionGroupReleaseStrategy;
import org.apache.flink.runtime.executiongraph.failover.flip1.partitionrelease.PartitionGroupReleaseStrategyFactoryLoader;
import org.apache.flink.runtime.executiongraph.metrics.DownTimeGauge;
import org.apache.flink.runtime.executiongraph.metrics.RestartTimeGauge;
import org.apache.flink.runtime.executiongraph.metrics.UpTimeGauge;
import org.apache.flink.runtime.io.network.partition.JobMasterPartitionTracker;
import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.runtime.jobgraph.JobVertex;
import org.apache.flink.runtime.jobgraph.jsonplan.JsonPlanGenerator;
import org.apache.flink.runtime.jobgraph.tasks.CheckpointCoordinatorConfiguration;
import org.apache.flink.runtime.jobgraph.tasks.JobCheckpointingSettings;
import org.apache.flink.runtime.scheduler.VertexParallelismStore;
import org.apache.flink.runtime.shuffle.ShuffleMaster;
import org.apache.flink.runtime.state.CheckpointStorage;
import org.apache.flink.runtime.state.CheckpointStorageLoader;
import org.apache.flink.runtime.state.StateBackend;
import org.apache.flink.runtime.state.StateBackendLoader;
import org.apache.flink.util.DynamicCodeLoadingException;
import org.apache.flink.util.SerializedValue;
import org.slf4j.Logger;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Supplier;
import static org.apache.flink.util.Preconditions.checkNotNull;
/**
* Utility class to encapsulate the logic of building an {@link DefaultExecutionGraph} from a {@link
* JobGraph}.
*/
public class DefaultExecutionGraphBuilder {
public static DefaultExecutionGraph buildGraph(
JobGraph jobGraph,
Configuration jobManagerConfig,
ScheduledExecutorService futureExecutor,
Executor ioExecutor,
ClassLoader classLoader,
CompletedCheckpointStore completedCheckpointStore,
CheckpointsCleaner checkpointsCleaner,
CheckpointIDCounter checkpointIdCounter,
Time rpcTimeout,
MetricGroup metrics,
BlobWriter blobWriter,
Logger log,
ShuffleMaster<?> shuffleMaster,
JobMasterPartitionTracker partitionTracker,
TaskDeploymentDescriptorFactory.PartitionLocationConstraint partitionLocationConstraint,
ExecutionDeploymentListener executionDeploymentListener,
ExecutionStateUpdateListener executionStateUpdateListener,
long initializationTimestamp,
VertexAttemptNumberStore vertexAttemptNumberStore,
VertexParallelismStore vertexParallelismStore,
Supplier<CheckpointStatsTracker> checkpointStatsTrackerFactory)
throws JobExecutionException, JobException {
checkNotNull(jobGraph, "job graph cannot be null");
final String jobName = jobGraph.getName();
final JobID jobId = jobGraph.getJobID();
final JobInformation jobInformation =
new JobInformation(
jobId,
jobName,
jobGraph.getSerializedExecutionConfig(),
jobGraph.getJobConfiguration(),
jobGraph.getUserJarBlobKeys(),
jobGraph.getClasspaths());
final int maxPriorAttemptsHistoryLength =
jobManagerConfig.getInteger(JobManagerOptions.MAX_ATTEMPTS_HISTORY_SIZE);
final PartitionGroupReleaseStrategy.Factory partitionGroupReleaseStrategyFactory =
PartitionGroupReleaseStrategyFactoryLoader.loadPartitionGroupReleaseStrategyFactory(
jobManagerConfig);
// create a new execution graph, if none exists so far
final DefaultExecutionGraph executionGraph;
try {
executionGraph =
new DefaultExecutionGraph(
jobInformation,
futureExecutor,
ioExecutor,
rpcTimeout,
maxPriorAttemptsHistoryLength,
classLoader,
blobWriter,
partitionGroupReleaseStrategyFactory,
shuffleMaster,
partitionTracker,
partitionLocationConstraint,
executionDeploymentListener,
executionStateUpdateListener,
initializationTimestamp,
vertexAttemptNumberStore,
vertexParallelismStore);
} catch (IOException e) {
throw new JobException("Could not create the ExecutionGraph.", e);
}
// set the basic properties
try {
executionGraph.setJsonPlan(JsonPlanGenerator.generatePlan(jobGraph));
} catch (Throwable t) {
log.warn("Cannot create JSON plan for job", t);
// give the graph an empty plan
executionGraph.setJsonPlan("{}");
}
// initialize the vertices that have a master initialization hook
// file output formats create directories here, input formats create splits
final long initMasterStart = System.nanoTime();
log.info("Running initialization on master for job {} ({}).", jobName, jobId);
for (JobVertex vertex : jobGraph.getVertices()) {
String executableClass = vertex.getInvokableClassName();
if (executableClass == null || executableClass.isEmpty()) {
throw new JobSubmissionException(
jobId,
"The vertex "
+ vertex.getID()
+ " ("
+ vertex.getName()
+ ") has no invokable class.");
}
try {
vertex.initializeOnMaster(classLoader);
} catch (Throwable t) {
throw new JobExecutionException(
jobId,
"Cannot initialize task '" + vertex.getName() + "': " + t.getMessage(),
t);
}
}
log.info(
"Successfully ran initialization on master in {} ms.",
(System.nanoTime() - initMasterStart) / 1_000_000);
// topologically sort the job vertices and attach the graph to the existing one
List<JobVertex> sortedTopology = jobGraph.getVerticesSortedTopologicallyFromSources();
if (log.isDebugEnabled()) {
log.debug(
"Adding {} vertices from job graph {} ({}).",
sortedTopology.size(),
jobName,
jobId);
}
executionGraph.attachJobGraph(sortedTopology);
if (log.isDebugEnabled()) {
log.debug(
"Successfully created execution graph from job graph {} ({}).", jobName, jobId);
}
// configure the state checkpointing
if (isCheckpointingEnabled(jobGraph)) {
JobCheckpointingSettings snapshotSettings = jobGraph.getCheckpointingSettings();
// load the state backend from the application settings
final StateBackend applicationConfiguredBackend;
final SerializedValue<StateBackend> serializedAppConfigured =
snapshotSettings.getDefaultStateBackend();
if (serializedAppConfigured == null) {
applicationConfiguredBackend = null;
} else {
try {
applicationConfiguredBackend =
serializedAppConfigured.deserializeValue(classLoader);
} catch (IOException | ClassNotFoundException e) {
throw new JobExecutionException(
jobId, "Could not deserialize application-defined state backend.", e);
}
}
final StateBackend rootBackend;
try {
rootBackend =
StateBackendLoader.fromApplicationOrConfigOrDefault(
applicationConfiguredBackend,
snapshotSettings.isChangelogStateBackendEnabled(),
jobManagerConfig,
classLoader,
log);
} catch (IllegalConfigurationException | IOException | DynamicCodeLoadingException e) {
throw new JobExecutionException(
jobId, "Could not instantiate configured state backend", e);
}
// load the checkpoint storage from the application settings
final CheckpointStorage applicationConfiguredStorage;
final SerializedValue<CheckpointStorage> serializedAppConfiguredStorage =
snapshotSettings.getDefaultCheckpointStorage();
if (serializedAppConfiguredStorage == null) {
applicationConfiguredStorage = null;
} else {
try {
applicationConfiguredStorage =
serializedAppConfiguredStorage.deserializeValue(classLoader);
} catch (IOException | ClassNotFoundException e) {
throw new JobExecutionException(
jobId,
"Could not deserialize application-defined checkpoint storage.",
e);
}
}
final CheckpointStorage rootStorage;
try {
rootStorage =
CheckpointStorageLoader.load(
applicationConfiguredStorage,
null,
rootBackend,
jobManagerConfig,
classLoader,
log);
} catch (IllegalConfigurationException | DynamicCodeLoadingException e) {
throw new JobExecutionException(
jobId, "Could not instantiate configured checkpoint storage", e);
}
// instantiate the user-defined checkpoint hooks
final SerializedValue<MasterTriggerRestoreHook.Factory[]> serializedHooks =
snapshotSettings.getMasterHooks();
final List<MasterTriggerRestoreHook<?>> hooks;
if (serializedHooks == null) {
hooks = Collections.emptyList();
} else {
final MasterTriggerRestoreHook.Factory[] hookFactories;
try {
hookFactories = serializedHooks.deserializeValue(classLoader);
} catch (IOException | ClassNotFoundException e) {
throw new JobExecutionException(
jobId, "Could not instantiate user-defined checkpoint hooks", e);
}
final Thread thread = Thread.currentThread();
final ClassLoader originalClassLoader = thread.getContextClassLoader();
thread.setContextClassLoader(classLoader);
try {
hooks = new ArrayList<>(hookFactories.length);
for (MasterTriggerRestoreHook.Factory factory : hookFactories) {
hooks.add(MasterHooks.wrapHook(factory.create(), classLoader));
}
} finally {
thread.setContextClassLoader(originalClassLoader);
}
}
final CheckpointCoordinatorConfiguration chkConfig =
snapshotSettings.getCheckpointCoordinatorConfiguration();
executionGraph.enableCheckpointing(
chkConfig,
hooks,
checkpointIdCounter,
completedCheckpointStore,
rootBackend,
rootStorage,
checkpointStatsTrackerFactory.get(),
checkpointsCleaner);
}
// create all the metrics for the Execution Graph
metrics.gauge(RestartTimeGauge.METRIC_NAME, new RestartTimeGauge(executionGraph));
metrics.gauge(DownTimeGauge.METRIC_NAME, new DownTimeGauge(executionGraph));
metrics.gauge(UpTimeGauge.METRIC_NAME, new UpTimeGauge(executionGraph));
return executionGraph;
}
public static boolean isCheckpointingEnabled(JobGraph jobGraph) {
return jobGraph.getCheckpointingSettings() != null;
}
// ------------------------------------------------------------------------
/** This class is not supposed to be instantiated. */
private DefaultExecutionGraphBuilder() {}
}
| StephanEwen/incubator-flink | flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/DefaultExecutionGraphBuilder.java | Java | apache-2.0 | 15,044 |
package io.electrum.billpay.model;
import io.electrum.vas.JsonUtil;
import io.electrum.vas.Utils;
import io.electrum.vas.model.Amounts;
import io.electrum.vas.model.PaymentMethod;
import io.electrum.vas.model.Tender;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import io.electrum.vas.interfaces.HasPaymentMethods;
import io.electrum.vas.interfaces.HasTenders;
import org.hibernate.validator.constraints.Length;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Represents a request to perform a payment of a traffic fine.
**/
@ApiModel(description = "Represents a request to perform a payment of a traffic fine.")
public class PolicyPaymentRequest extends BillpayRequest implements HasPaymentMethods, HasTenders {
@ApiModelProperty(required = true, value = "A reference number identifying the policy to the service provider.")
@JsonProperty("policyNumber")
@NotNull
@Length(min = 6, max = 40)
private String policyNumber = null;
@ApiModelProperty(required = true, value = "Contains the payment amount.", dataType = "io.electrum.billpay.model.BillpayAmounts")
@JsonProperty("amounts")
@NotNull
@Valid
private BillpayAmounts amounts = null;
@ApiModelProperty(required = false, value = "Contains the tenders for the payment request if available")
@JsonProperty("tenders")
private List<Tender> tenders = new ArrayList<>();
@ApiModelProperty(required = false, value = "Contains the payment method for the payment request if available")
@JsonProperty("paymentMethods")
private List<PaymentMethod> paymentMethods = new ArrayList<>();
@ApiModelProperty(value = "Customer detail")
@JsonProperty("customer")
@Valid
private Customer customer = null;
/**
* A reference number identifying the policy to the service provider.
**/
public PolicyPaymentRequest policyNumber(String policyNumber) {
this.policyNumber = policyNumber;
return this;
}
public String getPolicyNumber() {
return policyNumber;
}
public void setPolicyNumber(String policyNumber) {
this.policyNumber = policyNumber;
}
/**
* Contains the payment amount.
*
* @since v4.8.0
**/
public PolicyPaymentRequest amounts(BillpayAmounts amounts) {
this.amounts = amounts;
return this;
}
/**
* Contains the payment amount.
*
* @deprecated - Use {@link #amounts(BillpayAmounts)} instead.
**/
@Deprecated
@JsonIgnore
@ApiModelProperty(access = "overloaded-method")
public PolicyPaymentRequest amounts(Amounts amounts) {
try {
this.amounts = JsonUtil.deserialize(JsonUtil.serialize(amounts, Amounts.class), BillpayAmounts.class);
return this;
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
public <T extends Amounts> T getAmounts() {
return (T) amounts;
}
/**
* @since v4.8.0
* @param amounts
*/
public void setAmounts(BillpayAmounts amounts) {
this.amounts = amounts;
}
/**
*
* @param amounts
* @deprecated - Use {@link #setAmounts(BillpayAmounts)} instead.
*/
@Deprecated
@JsonIgnore
@ApiModelProperty(access = "overloaded-method")
public void setAmounts(Amounts amounts) {
try {
this.amounts = JsonUtil.deserialize(JsonUtil.serialize(amounts, Amounts.class), BillpayAmounts.class);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
public PolicyPaymentRequest tender(List<Tender> tenders) {
this.tenders = tenders;
return this;
}
public List<Tender> getTenders() {
return tenders;
}
public void setTenders(List<Tender> tenders) {
this.tenders = tenders;
}
public PolicyPaymentRequest paymentMethods(List<PaymentMethod> paymentMethods) {
this.paymentMethods = paymentMethods;
return this;
}
public List<PaymentMethod> getPaymentMethods() {
return paymentMethods;
}
public void setPaymentMethods(List<PaymentMethod> paymentMethods) {
this.paymentMethods = paymentMethods;
}
/**
* Customer detail
**/
public PolicyPaymentRequest customer(Customer customer) {
this.customer = customer;
return this;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PolicyPaymentRequest tender = (PolicyPaymentRequest) o;
return Objects.equals(policyNumber, tender.policyNumber) && Objects.equals(amounts, tender.amounts);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), policyNumber, amounts);
}
@Override
public String toString() {
return new StringBuilder().append("class PolicyPaymentRequest {")
.append(System.lineSeparator())
.append(" policyNumber: ")
.append(Utils.toIndentedString(policyNumber))
.append(System.lineSeparator())
.append(" amounts: ")
.append(Utils.toIndentedString(amounts))
.append(System.lineSeparator())
.append(" tenders: ")
.append(Utils.toIndentedString(tenders))
.append(System.lineSeparator())
.append(" paymentMethods: ")
.append(Utils.toIndentedString(paymentMethods))
.append(System.lineSeparator())
.append(" customer: ")
.append(Utils.toIndentedString(customer))
.append(System.lineSeparator())
.append("}")
.append(System.lineSeparator())
.append(super.toString())
.toString();
}
}
| electrumpayments/billpay-service-interface | src/main/java/io/electrum/billpay/model/PolicyPaymentRequest.java | Java | apache-2.0 | 6,163 |
package com.orasi.core.interfaces.impl;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.naming.directory.NoSuchAttributeException;
import com.orasi.core.interfaces.Webtable;
import com.orasi.utils.WebDriverSetup;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
/**
* Wrapper class like Select that wraps basic checkbox functionality.
*/
public class WebtableImpl extends ElementImpl implements Webtable {
/**
* @summary - Wraps a WebElement with checkbox functionality.
* @param element to wrap up
*/
public WebtableImpl(WebElement element) {
super(element);
}
/**
* @summary - Attempts to locate the number of child elements with the HTML
* tag "tr" using xpath. If none are found, the xpath "tbody/tr" is used.
* @param driver - Current active WebDriver object
* @return int - number of rows found for a given table
*/
@Override
public int getRowCount(WebDriver driver){
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
List<WebElement> rowCollection = this.element.findElements(By.xpath("tr"));
if (rowCollection.size() == 0) {
rowCollection = this.element.findElements(By.xpath("tbody/tr"));
}
driver.manage().timeouts().implicitlyWait(WebDriverSetup.getDefaultTestTimeout(), TimeUnit.SECONDS);
return rowCollection.size();
}
/**
* @summary - Attempts to locate the number of child elements with the HTML
* tag "tr" using xpath. If none are found, the xpath "tbody/tr" is used.
* All rows are then iterated through until the desired row, determined
* by the parameter, is found.
* @param driver - Current active WebDriver object
* @param row - Desired row for which to return a column count
* @return int - number of columns found for a given row
* @throws NoSuchAttributeException
*/
@Override
public int getColumnCount( WebDriver driver, int row) throws NoSuchAttributeException {
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
List<WebElement> rowCollection = this.element.findElements(By.xpath("tr"));
boolean rowFound = false;
if (rowCollection.size() == 0) {
rowCollection = this.element.findElements(By.xpath("tbody/tr"));
}
driver.manage().timeouts().implicitlyWait(WebDriverSetup.getDefaultTestTimeout(), TimeUnit.SECONDS);
int currentRow = 1;
int columnCount = 0;
String xpath = null;
for(WebElement rowElement : rowCollection){
if(row == currentRow){
rowFound = true;
driver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS);
if(rowElement.findElements(By.xpath("th")).size() != 0){
xpath = "th";
}else if(rowElement.findElements(By.xpath("td")).size() != 0){
xpath = "td";
}else{
throw new NoSuchAttributeException("No child element with the HTML tag \"th\" or \"td\" were found for the parent webtable [ <b>@FindBy: " + getElementLocatorInfo() + " </b>]");
}
driver.manage().timeouts().implicitlyWait(WebDriverSetup.getDefaultTestTimeout(), TimeUnit.SECONDS);
List<WebElement> columnCollection = rowElement.findElements(By.xpath(xpath));
columnCount =columnCollection.size();
break;
}else{
currentRow++;
}
}
Assert.assertEquals(rowFound, true, "The expected row ["+String.valueOf(row)+"] was not found. The number of rows found for webtable [ <b>@FindBy: " + getElementLocatorInfo() + " </b>] is ["+String.valueOf(rowCollection.size())+"].");
return columnCount;
}
/**
* @summary - Attempts to locate the number of child elements with the HTML
* tag "tr" using xpath. If none are found, the xpath "tbody/tr" is used.
* All rows are then iterated through until the desired row, determined
* by the parameter 'row', is found. For this row, all columns are then
* iterated through until the desired column, determined by the parameter
* 'column', is found.
* @param driver - Current active WebDriver object
* @param row - Desired row in which to search for a particular cell
* @param column - Desired column in which to find the cell
* @return WebElement - the desired cell
* @throws NoSuchAttributeException
*/
@Override
public WebElement getCell( WebDriver driver, int row, int column) throws NoSuchAttributeException{
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
List<WebElement> rowCollection = this.element.findElements(By.xpath("tr"));
if (rowCollection.size() == 0) {
rowCollection = this.element.findElements(By.xpath("tbody/tr"));
}
driver.manage().timeouts().implicitlyWait(WebDriverSetup.getDefaultTestTimeout(), TimeUnit.SECONDS);
WebElement elementCell = null;
int currentRow = 1,currentColumn = 1;
String xpath = null;
Boolean found = false;
List<WebElement> columnCollection = null;
for(WebElement rowElement : rowCollection)
{
if(row != currentRow){currentRow++;}
else{
driver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS);
if(rowElement.findElements(By.xpath("th")).size() != 0)
{
xpath = "th";
}else if(rowElement.findElements(By.xpath("td")).size() != 0)
{
xpath = "td";
}else{
throw new NoSuchAttributeException("No child element with the HTML tag \"th\" or \"td\" were found for the parent webtable [ <b>@FindBy: " + getElementLocatorInfo() + " </b>]");
}
driver.manage().timeouts().implicitlyWait(WebDriverSetup.getDefaultTestTimeout(), TimeUnit.SECONDS);
columnCollection = rowElement.findElements(By.xpath(xpath));
for(WebElement cell : columnCollection)
{
if (column != currentColumn){currentColumn++;}
else
{
elementCell = cell;
found = true;
break;
}
}
if (found){break;}
}
}
Assert.assertEquals(Boolean.valueOf(found), Boolean.TRUE, "No cell was found for row ["+String.valueOf(row)+"] and column ["+String.valueOf(column)+"]. The column count for row ["+String.valueOf(row)+"] is ["+String.valueOf(columnCollection.size())+"]");
return elementCell;
}
/**
* @summary - Attempts to locate the number of child elements with the HTML
* tag "tr" using xpath. If none are found, the xpath "tbody/tr" is used.
* All rows are then iterated through until the desired row, determined
* by the parameter 'row', is found. For this row, all columns are then
* iterated through until the desired column, determined by the parameter
* 'column', is found. The cell found by the row/column indices is then
* clicked
* @param driver - Current active WebDriver object
* @param row - Desired row in which to search for a particular cell
* @param column - Desired column in which to find the cell
* @throws NoSuchAttributeException
*/
@Override
public void clickCell( WebDriver driver, int row, int column) throws NoSuchAttributeException{
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
List<WebElement> rowCollection = this.element.findElements(By.xpath("tr"));
if (rowCollection.size() == 0) {
rowCollection = this.element.findElements(By.xpath("tbody/tr"));
}
driver.manage().timeouts().implicitlyWait(WebDriverSetup.getDefaultTestTimeout(), TimeUnit.SECONDS);
int currentRow = 1,currentColumn = 1;
String xpath = null;
Boolean found = false;
List<WebElement> columnCollection = null;
for(WebElement rowElement : rowCollection)
{
if(row != currentRow){currentRow++;}
else{
driver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS);
if(rowElement.findElements(By.xpath("th")).size() != 0)
{
xpath = "th";
}else if(rowElement.findElements(By.xpath("td")).size() != 0)
{
xpath = "td";
}else{
throw new NoSuchAttributeException("No child element with the HTML tag \"th\" or \"td\" were found for the parent webtable [ <b>@FindBy: " + getElementLocatorInfo() + " </b>]");
}
driver.manage().timeouts().implicitlyWait(WebDriverSetup.getDefaultTestTimeout(), TimeUnit.SECONDS);
columnCollection = rowElement.findElements(By.xpath(xpath));
for(WebElement cell : columnCollection)
{
if (column != currentColumn){currentColumn++;}
else
{
cell.click();
found = true;
break;
}
}
if (found){break;}
}
}
Assert.assertEquals(Boolean.valueOf(found), Boolean.TRUE, "No cell was found for row ["+String.valueOf(row)+"] and column ["+String.valueOf(column)+"]. The column count for row ["+String.valueOf(row)+"] is ["+String.valueOf(columnCollection.size())+"]");
}
/**
* @summary - Attempts to locate the number of child elements with the HTML
* tag "tr" using xpath. If none are found, the xpath "tbody/tr" is used.
* All rows are then iterated through until the desired row, determined
* by the parameter 'row', is found. For this row, all columns are then
* iterated through until the desired column, determined by the parameter
* 'column', is found.
* @param driver - Current active WebDriver object
* @param row - Desired row in which to search for a particular cell
* @param column - Desired column in which to find the cell
* @return String - text of cell contents
* @throws NoSuchAttributeException
*/
@Override
public String getCellData( WebDriver driver, int row, int column) throws NoSuchAttributeException{
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
List<WebElement> rowCollection = this.element.findElements(By.xpath("tr"));
if (rowCollection.size() == 0) {
rowCollection = this.element.findElements(By.xpath("tbody/tr"));
}
driver.manage().timeouts().implicitlyWait(WebDriverSetup.getDefaultTestTimeout(), TimeUnit.SECONDS);
int currentRow = 1,currentColumn = 1;
String xpath = null, cellData = "";
Boolean found = false;
List<WebElement> columnCollection = null;
for(WebElement rowElement : rowCollection)
{
if(row != currentRow){currentRow++;}
else{
driver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS);
if(rowElement.findElements(By.xpath("th")).size() != 0)
{
xpath = "th";
}else if(rowElement.findElements(By.xpath("td")).size() != 0)
{
xpath = "td";
}else{
throw new NoSuchAttributeException("No child element with the HTML tag \"th\" or \"td\" were found for the parent webtable [ <b>@FindBy: " + getElementLocatorInfo() + " </b>]");
}
driver.manage().timeouts().implicitlyWait(WebDriverSetup.getDefaultTestTimeout(), TimeUnit.SECONDS);
columnCollection = rowElement.findElements(By.xpath(xpath));
for(WebElement cell : columnCollection)
{
if (column != currentColumn){currentColumn++;}
else
{
cellData = cell.getText();
found = true;
break;
}
}
if (found){break;}
}
}
Assert.assertEquals(Boolean.valueOf(found), Boolean.TRUE, "No cell was found for row ["+String.valueOf(row)+"] and column ["+String.valueOf(column)+"]. The column count for row ["+String.valueOf(row)+"] is ["+String.valueOf(columnCollection.size())+"]");
return cellData;
}
/**
* @summary - Attempts to locate the number of child elements with the HTML
* tag "tr" using xpath. If none are found, the xpath "tbody/tr" is used.
* All rows are then iterated through as well as each column for each row
* until the cell with the desired text, determined by the parameter, is
* found.
* @param driver - Current active WebDriver object
* @param text - text for which to search
* @return int - row number containing the desired text
*/
@Override
public int getRowWithCellText( WebDriver driver, String text){
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
List<WebElement> rowCollection = this.element.findElements(By.xpath("tr"));
if (rowCollection.size() == 0) {
rowCollection = this.element.findElements(By.xpath("tbody/tr"));
}
driver.manage().timeouts().implicitlyWait(WebDriverSetup.getDefaultTestTimeout(), TimeUnit.SECONDS);
int currentRow = 1,currentColumn = 1, rowFound = 0;
String xpath = null;
Boolean found = false;
for(WebElement rowElement : rowCollection)
{
if(currentRow <= rowCollection.size()){
driver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS);
if(rowElement.findElements(By.xpath("th")).size() != 0)
{
xpath = "th";
}else if(rowElement.findElements(By.xpath("td")).size() != 0)
{
xpath = "td";
}
driver.manage().timeouts().implicitlyWait(WebDriverSetup.getDefaultTestTimeout(), TimeUnit.SECONDS);
List<WebElement> columnCollection = rowElement.findElements(By.xpath(xpath));
for(WebElement cell : columnCollection)
{
if (currentColumn <= columnCollection.size()){
if(cell.getText().trim().equals(text)){
rowFound = currentRow;
found = true;
break;
}
currentColumn++;
}
}
if (found){break;}
currentRow++;
currentColumn=1;
}
}
Assert.assertEquals(Boolean.valueOf(found), Boolean.TRUE, "No cell was found containing the text ["+text+"].");
return rowFound;
}
/**
* @summary - Attempts to locate the number of child elements with the HTML
* tag "tr" using xpath. If none are found, the xpath "tbody/tr" is used.
* All rows are then iterated through as well as each column for each row
* until the desired cell is located. The cell text is then validated
* against the parameter 'text'
* @param driver - Current active WebDriver object
* @param text - text for which to search
* @param columnPosition - column number where the desired text is expected
* @return int - row number containing the desired text
*/
@Override
public int getRowWithCellText( WebDriver driver, String text, int columnPosition){
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
List<WebElement> rowCollection = this.element.findElements(By.xpath("tr"));
if (rowCollection.size() == 0) {
rowCollection = this.element.findElements(By.xpath("tbody/tr"));
}
driver.manage().timeouts().implicitlyWait(WebDriverSetup.getDefaultTestTimeout(), TimeUnit.SECONDS);
int currentRow = 1,currentColumn = 1, rowFound = 0;
String xpath = null;
Boolean found = false;
for(WebElement rowElement : rowCollection)
{
if(currentRow <= rowCollection.size()){
driver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS);
if(rowElement.findElements(By.xpath("th")).size() != 0)
{
xpath = "th";
}else if(rowElement.findElements(By.xpath("td")).size() != 0)
{
xpath = "td";
}
driver.manage().timeouts().implicitlyWait(WebDriverSetup.getDefaultTestTimeout(), TimeUnit.SECONDS);
List<WebElement> columnCollection = rowElement.findElements(By.xpath(xpath));
for(WebElement cell : columnCollection)
{
if (currentColumn == columnPosition) {
if (cell.getText().trim().equals(text)) {
rowFound = currentRow;
found = true;
break;
}
} else {
currentColumn++;
}
}
if (found){break;}
currentRow++;
currentColumn=1;
}
}
Assert.assertEquals(Boolean.valueOf(found), Boolean.TRUE, "No cell in column ["+String.valueOf(columnPosition)+"] was found to contain the text ["+text+"].");
return rowFound;
}
/**
* @summary - Attempts to locate the number of child elements with the HTML
* tag "tr" using xpath. If none are found, the xpath "tbody/tr" is used.
* All rows are then iterated through as well as each column for each row
* until the desired cell is located. The cell text is then validated
* against the parameter 'text'
* @param driver - Current active WebDriver object
* @param text - text for which to search
* @param columnPosition - column number where the desired text is expected
* @param startRow - row with which to start
* @return int - row number containing the desired text
*/
@Override
public int getRowWithCellText( WebDriver driver, String text, int columnPosition, int startRow){
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
List<WebElement> rowCollection = this.element.findElements(By.xpath("tr"));
if (rowCollection.size() == 0) {
rowCollection = this.element.findElements(By.xpath("tbody/tr"));
}
driver.manage().timeouts().implicitlyWait(WebDriverSetup.getDefaultTestTimeout(), TimeUnit.SECONDS);
int currentRow = 1,currentColumn = 1, rowFound = 0;
String xpath = null;
Boolean found = false;
for(WebElement rowElement : rowCollection)
{
if(startRow > currentRow) {
currentRow++;
}else{
if(currentRow <= rowCollection.size()){
driver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS);
if(rowElement.findElements(By.xpath("th")).size() != 0)
{
xpath = "th";
}else if(rowElement.findElements(By.xpath("td")).size() != 0)
{
xpath = "td";
}
driver.manage().timeouts().implicitlyWait(WebDriverSetup.getDefaultTestTimeout(), TimeUnit.SECONDS);
List<WebElement> columnCollection = rowElement.findElements(By.xpath(xpath));
for(WebElement cell : columnCollection)
{
if (currentColumn == columnPosition){
if(cell.getText().trim().equals(text)){
rowFound = currentRow;
found = true;
break;
}
}else{
currentColumn++;
}
}
if (found){break;}
currentRow++;
currentColumn=1;
}
}
}
Assert.assertEquals(Boolean.valueOf(found), Boolean.TRUE, "No cell in column ["+String.valueOf(columnPosition)+"] was found to contain the text ["+text+"].");
return rowFound;
}
/**
* @summary - Attempts to locate the number of child elements with the HTML
* tag "tr" using xpath. If none are found, the xpath "tbody/tr" is used.
* All rows are then iterated through as well as each column for each row
* until the desired cell is located. The cell text is then validated
* against the parameter 'text'
* @param driver - Current active WebDriver object
* @param text - text for which to search
* @return int - column number containing the desired text
*/
@Override
public int getColumnWithCellText(WebDriver driver, String text){
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
List<WebElement> rowCollection = this.element.findElements(By.xpath("tr"));
if (rowCollection.size() == 0) {
rowCollection = this.element.findElements(By.xpath("tbody/tr"));
}
driver.manage().timeouts().implicitlyWait(WebDriverSetup.getDefaultTestTimeout(), TimeUnit.SECONDS);
int currentRow = 1,currentColumn = 1, columnFound = 0;
String xpath = null;
Boolean found = false;
for(WebElement rowElement : rowCollection)
{
if(currentRow <= rowCollection.size()){
driver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS);
if(rowElement.findElements(By.xpath("th")).size() != 0)
{
xpath = "th";
}else if(rowElement.findElements(By.xpath("td")).size() != 0)
{
xpath = "td";
}
driver.manage().timeouts().implicitlyWait(WebDriverSetup.getDefaultTestTimeout(), TimeUnit.SECONDS);
List<WebElement> columnCollection = rowElement.findElements(By.xpath(xpath));
for(WebElement cell : columnCollection)
{
if (currentColumn <= columnCollection.size()){
if(cell.getText().trim().equals(text)){
columnFound = currentColumn;
found = true;
break;
}
currentColumn++;
}
}
if (found){break;}
currentRow++;
currentColumn=1;
}
}
Assert.assertEquals(Boolean.valueOf(found), Boolean.TRUE, "No cell in any column was found to have the text ["+text+"].");
return columnFound;
}
/**
* @summary - Attempts to locate the number of child elements with the HTML
* tag "tr" using xpath. If none are found, the xpath "tbody/tr" is used.
* All rows are then iterated through until the desired row is found,
* then all columns are iterated through until the desired text is found.
* @param driver - Current active WebDriver object
* @param text - text for which to search
* @param rowPosition - row where the expected text is anticipated
* @return int - column number containing the desired text
*/
@Override
public int getColumnWithCellText(WebDriver driver, String text, int rowPosition){
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
List<WebElement> rowCollection = this.element.findElements(By.xpath("tr"));
if (rowCollection.size() == 0) {
rowCollection = this.element.findElements(By.xpath("tbody/tr"));
}
driver.manage().timeouts().implicitlyWait(WebDriverSetup.getDefaultTestTimeout(), TimeUnit.SECONDS);
int currentRow = 1,currentColumn = 1, columnFound = 0;
String xpath = null;
Boolean found = false;
for(WebElement rowElement : rowCollection)
{
if(rowPosition > currentRow) {
currentRow++;
}else{
if(currentRow <= rowCollection.size()){
driver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS);
if(rowElement.findElements(By.xpath("th")).size() != 0)
{
xpath = "th";
}else if(rowElement.findElements(By.xpath("td")).size() != 0)
{
xpath = "td";
}
driver.manage().timeouts().implicitlyWait(WebDriverSetup.getDefaultTestTimeout(), TimeUnit.SECONDS);
List<WebElement> columnCollection = rowElement.findElements(By.xpath(xpath));
for(WebElement cell : columnCollection)
{
if (currentColumn <= columnCollection.size()){
if(cell.getText().trim().equals(text)){
columnFound = currentColumn;
found = true;
break;
}
currentColumn++;
}
}
if (found){break;}
currentRow++;
currentColumn=1;
}
}
}
Assert.assertEquals(Boolean.valueOf(found), Boolean.TRUE, "No cell in row ["+String.valueOf(rowPosition)+"] was found to have the text ["+text+"].");
return columnFound;
}
/**
* @summary - Attempts to locate the number of child elements with the HTML
* tag "tr" using xpath. If none are found, the xpath "tbody/tr" is used.
* All rows are then iterated through and a particular column, determined
* by the 'columnPosition' parameter, is grabbed and the text is validate
* against the expected text defined by the parameter 'text'.
* @param driver - Current active WebDriver object
* @param text - text for which to search
* @param columnPosition - column where the expected text is anticipated
* @return int - column number containing the desired text
*/
@Override
public int getRowThatContainsCellText( WebDriver driver, String text, int columnPosition){
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
List<WebElement> rowCollection = this.element.findElements(By.xpath("tr"));
if (rowCollection.size() == 0) {
rowCollection = this.element.findElements(By.xpath("tbody/tr"));
}
driver.manage().timeouts().implicitlyWait(WebDriverSetup.getDefaultTestTimeout(), TimeUnit.SECONDS);
int currentRow = 1,currentColumn = 1, rowFound = 0;
String xpath = null;
Boolean found = false;
for(WebElement rowElement : rowCollection)
{
if(currentRow <= rowCollection.size()){
driver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS);
if(rowElement.findElements(By.xpath("th")).size() != 0)
{
xpath = "th";
}else if(rowElement.findElements(By.xpath("td")).size() != 0)
{
xpath = "td";
}
driver.manage().timeouts().implicitlyWait(WebDriverSetup.getDefaultTestTimeout(), TimeUnit.SECONDS);
List<WebElement> columnCollection = rowElement.findElements(By.xpath(xpath));
for(WebElement cell : columnCollection)
{
if (currentColumn == columnPosition){
if(cell.getText().trim().contains(text)){
rowFound = currentRow;
found = true;
break;
}
}else{
currentColumn++;
}
}
if (found){break;}
currentRow++;
currentColumn=1;
}
}
return rowFound;
}
} | JohnDoll/Toyota | src/main/java/com/orasi/core/interfaces/impl/WebtableImpl.java | Java | apache-2.0 | 28,168 |
/*
* Copyright (C) 2015 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.example.android.support.design.widget;
import com.example.android.support.design.R;
public class AppBarLayoutToolbarCollapseThenPinNested extends AppBarLayoutUsageBase {
@Override
protected int getLayoutId() {
return R.layout.design_appbar_toolbar_collapse_pin_nested;
}
}
| aosp-mirror/platform_frameworks_support | samples/SupportDesignDemos/src/main/java/com/example/android/support/design/widget/AppBarLayoutToolbarCollapseThenPinNested.java | Java | apache-2.0 | 929 |
package com.xem.mzbphoneapp.view;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.xem.mzbphoneapp.R;
/**
* Created by xuebing on 15/6/16.
*/
public class MzbDialog {
private Dialog mDialog;
private TextView dialog_title;
private TextView dialog_message;
public TextView positive;
public TextView negative;
public MzbDialog(Context context, String title, String message) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.dialog_layout, null);
mDialog = new Dialog(context, R.style.dialog);
mDialog.setContentView(view);
mDialog.setCanceledOnTouchOutside(false);
mDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
return false;
}
});
dialog_title = (TextView) view.findViewById(R.id.dialog_title);
dialog_message = (TextView) view.findViewById(R.id.dialog_message);
dialog_title.setText(title);
dialog_message.setText(message);
positive = (TextView) view.findViewById(R.id.yes);
negative = (TextView) view.findViewById(R.id.no);
}
public void show() {
mDialog.show();
}
public void dismiss() {
mDialog.dismiss();
}
}
| wxb2939/rwxlicai | mzb-phone-app-android/app/src/main/java/com/xem/mzbphoneapp/view/MzbDialog.java | Java | apache-2.0 | 1,682 |
/*
* Copyright (C) 2014 Indeed 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.indeed.lsmtree.recordcache;
/**
* @author jplaisance
*/
public class CacheStats {
int memcacheHits = 0;
long memcacheTime = 0;
int persistentStoreHits = 0;
long indexTime = 0;
long recordLogTime = 0;
int misses = 0;
int recordLogReadErrors = 0;
int indexReadErrors = 0;
public int getMemcacheHits() {
return memcacheHits;
}
public void setMemcacheHits(int memcacheHits) {
this.memcacheHits = memcacheHits;
}
public long getMemcacheTime() {
return memcacheTime;
}
public void setMemcacheTime(long memcacheTime) {
this.memcacheTime = memcacheTime;
}
public int getPersistentStoreHits() {
return persistentStoreHits;
}
public void setPersistentStoreHits(int persistentStoreHits) {
this.persistentStoreHits = persistentStoreHits;
}
public long getIndexTime() {
return indexTime;
}
public void setIndexTime(long indexTime) {
this.indexTime = indexTime;
}
public long getRecordLogTime() {
return recordLogTime;
}
public void setRecordLogTime(long recordLogTime) {
this.recordLogTime = recordLogTime;
}
public int getMisses() {
return misses;
}
public void setMisses(int misses) {
this.misses = misses;
}
public int getRecordLogReadErrors() {
return recordLogReadErrors;
}
public void setRecordLogReadErrors(final int recordLogReadErrors) {
this.recordLogReadErrors = recordLogReadErrors;
}
public int getIndexReadErrors() {
return indexReadErrors;
}
public void setIndexReadErrors(final int indexReadErrors) {
this.indexReadErrors = indexReadErrors;
}
public void clear() {
memcacheHits = 0;
memcacheTime = 0;
persistentStoreHits = 0;
indexTime = 0;
recordLogTime = 0;
misses = 0;
recordLogReadErrors = 0;
indexReadErrors = 0;
}
@Override
public String toString() {
return "CacheStats{" +
"memcacheHits=" +
memcacheHits +
", memcacheTime=" +
memcacheTime +
", persistentStoreHits=" + persistentStoreHits +
", indexTime=" +
indexTime +
", recordLogTime=" +
recordLogTime +
", misses=" +
misses +
", recordLogReadErrors=" +
recordLogReadErrors +
", indexReadErrors=" +
indexReadErrors +
'}';
}
}
| indeedeng/lsmtree | recordcache/src/main/java/com/indeed/lsmtree/recordcache/CacheStats.java | Java | apache-2.0 | 3,245 |
package org.apereo.cas.services;
import org.apereo.cas.ticket.AuthenticationAwareTicket;
import org.apereo.cas.util.model.TriStateBoolean;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;
/**
* This is {@link DefaultRegisteredServiceSingleSignOnParticipationPolicy}.
*
* @author Misagh Moayyed
* @since 6.1.0
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@ToString
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@EqualsAndHashCode
public class DefaultRegisteredServiceSingleSignOnParticipationPolicy implements RegisteredServiceSingleSignOnParticipationPolicy {
private static final long serialVersionUID = -1223944598337761319L;
private TriStateBoolean createCookieOnRenewedAuthentication;
@Override
public boolean shouldParticipateInSso(final RegisteredService registeredService, final AuthenticationAwareTicket ticketState) {
return true;
}
}
| apereo/cas | core/cas-server-core-services-api/src/main/java/org/apereo/cas/services/DefaultRegisteredServiceSingleSignOnParticipationPolicy.java | Java | apache-2.0 | 1,129 |
/*
* Copyright 2014-2019 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.waf.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/ListResourcesForWebACL"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListResourcesForWebACLResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* An array of ARNs (Amazon Resource Names) of the resources associated with the specified web ACL. An array with
* zero elements is returned if there are no resources associated with the web ACL.
* </p>
*/
private java.util.List<String> resourceArns;
/**
* <p>
* An array of ARNs (Amazon Resource Names) of the resources associated with the specified web ACL. An array with
* zero elements is returned if there are no resources associated with the web ACL.
* </p>
*
* @return An array of ARNs (Amazon Resource Names) of the resources associated with the specified web ACL. An array
* with zero elements is returned if there are no resources associated with the web ACL.
*/
public java.util.List<String> getResourceArns() {
return resourceArns;
}
/**
* <p>
* An array of ARNs (Amazon Resource Names) of the resources associated with the specified web ACL. An array with
* zero elements is returned if there are no resources associated with the web ACL.
* </p>
*
* @param resourceArns
* An array of ARNs (Amazon Resource Names) of the resources associated with the specified web ACL. An array
* with zero elements is returned if there are no resources associated with the web ACL.
*/
public void setResourceArns(java.util.Collection<String> resourceArns) {
if (resourceArns == null) {
this.resourceArns = null;
return;
}
this.resourceArns = new java.util.ArrayList<String>(resourceArns);
}
/**
* <p>
* An array of ARNs (Amazon Resource Names) of the resources associated with the specified web ACL. An array with
* zero elements is returned if there are no resources associated with the web ACL.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setResourceArns(java.util.Collection)} or {@link #withResourceArns(java.util.Collection)} if you want to
* override the existing values.
* </p>
*
* @param resourceArns
* An array of ARNs (Amazon Resource Names) of the resources associated with the specified web ACL. An array
* with zero elements is returned if there are no resources associated with the web ACL.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListResourcesForWebACLResult withResourceArns(String... resourceArns) {
if (this.resourceArns == null) {
setResourceArns(new java.util.ArrayList<String>(resourceArns.length));
}
for (String ele : resourceArns) {
this.resourceArns.add(ele);
}
return this;
}
/**
* <p>
* An array of ARNs (Amazon Resource Names) of the resources associated with the specified web ACL. An array with
* zero elements is returned if there are no resources associated with the web ACL.
* </p>
*
* @param resourceArns
* An array of ARNs (Amazon Resource Names) of the resources associated with the specified web ACL. An array
* with zero elements is returned if there are no resources associated with the web ACL.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListResourcesForWebACLResult withResourceArns(java.util.Collection<String> resourceArns) {
setResourceArns(resourceArns);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getResourceArns() != null)
sb.append("ResourceArns: ").append(getResourceArns());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ListResourcesForWebACLResult == false)
return false;
ListResourcesForWebACLResult other = (ListResourcesForWebACLResult) obj;
if (other.getResourceArns() == null ^ this.getResourceArns() == null)
return false;
if (other.getResourceArns() != null && other.getResourceArns().equals(this.getResourceArns()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getResourceArns() == null) ? 0 : getResourceArns().hashCode());
return hashCode;
}
@Override
public ListResourcesForWebACLResult clone() {
try {
return (ListResourcesForWebACLResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| jentfoo/aws-sdk-java | aws-java-sdk-waf/src/main/java/com/amazonaws/services/waf/model/ListResourcesForWebACLResult.java | Java | apache-2.0 | 6,430 |
/*
* Copyright 2017-2022 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.simplesystemsmanagement.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.simplesystemsmanagement.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* ResourceDataSyncOrganizationalUnitMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ResourceDataSyncOrganizationalUnitMarshaller {
private static final MarshallingInfo<String> ORGANIZATIONALUNITID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("OrganizationalUnitId").build();
private static final ResourceDataSyncOrganizationalUnitMarshaller instance = new ResourceDataSyncOrganizationalUnitMarshaller();
public static ResourceDataSyncOrganizationalUnitMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(ResourceDataSyncOrganizationalUnit resourceDataSyncOrganizationalUnit, ProtocolMarshaller protocolMarshaller) {
if (resourceDataSyncOrganizationalUnit == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(resourceDataSyncOrganizationalUnit.getOrganizationalUnitId(), ORGANIZATIONALUNITID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| aws/aws-sdk-java | aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/transform/ResourceDataSyncOrganizationalUnitMarshaller.java | Java | apache-2.0 | 2,203 |
package com.chillingvan.canvasglsample;
import android.app.Application;
import com.chillingvan.canvasgl.util.FileLogger;
/**
* Created by Chilling on 2018/11/17.
*/
public class MainApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// Loggers.DEBUG = true;
FileLogger.init(getExternalFilesDir(null).getAbsolutePath());
FileLogger.d("MainActivity", "init -----------------");
}
}
| ChillingVan/android-openGL-canvas | canvasglsample/src/main/java/com/chillingvan/canvasglsample/MainApplication.java | Java | apache-2.0 | 464 |
package com.indarsoft.cryptocard.customerverify;
public class CustomerVerifyException extends Exception {
/**
*
*/
private static final long serialVersionUID = -7559475613700140437L;
public CustomerVerifyException (String msg ) {
super(msg);
}
public CustomerVerifyException() {
super("Unhandled Exception !!") ;
}
}
| jporras66/cryptocard | cryptocard/src/main/java/com/indarsoft/cryptocard/customerverify/CustomerVerifyException.java | Java | apache-2.0 | 351 |
package net.jackofalltrades.workflow.model.xml;
import com.intellij.util.xml.DomElement;
import java.util.List;
/**
* Defines the structure of the "actions" element.
*
* @author bhandy
*/
public interface StepActionHolder extends DomElement, ActionHolder {
List<ActionReference> getCommonActions();
ActionReference addCommonAction(int index);
ActionReference addCommonAction();
}
| bradhandy/osworkflow-intellij-plugin | src/main/java/net/jackofalltrades/workflow/model/xml/StepActionHolder.java | Java | apache-2.0 | 403 |
package com.study.luence.day1;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
/**
* 查询title 包含 "美国" && content 不包含"日本"
*/
public class BooleanQueryTest {
public static void main(String[] args) throws IOException {
String field = "title";
Path indexPath = Paths.get("/Users/liuzhaoyuan/gitwork/study-hello/study-lucene/indexdir");
Directory dir = FSDirectory.open(indexPath);
IndexReader reader = DirectoryReader.open(dir);
IndexSearcher searcher = new IndexSearcher(reader);
Query query1 = new TermQuery(new Term("title", "美国"));
Query query2 = new TermQuery(new Term("content", "日本"));
BooleanClause bc1 = new BooleanClause(query1, Occur.MUST);
BooleanClause bc2 = new BooleanClause(query2, Occur.MUST_NOT);
BooleanQuery boolQuery = new BooleanQuery.Builder().add(bc1).add(bc2).build();
System.out.println("Query:" + boolQuery);
// 返回前10条
TopDocs tds = searcher.search(boolQuery, 10);
for (ScoreDoc sd : tds.scoreDocs) {
Document doc = searcher.doc(sd.doc);
System.out.println("DocID:" + sd.doc);
System.out.println("id:" + doc.get("id"));
System.out.println("title:" + doc.get("title"));
System.out.println("content:" + doc.get("content"));
System.out.println("文档评分:" + sd.score);
}
dir.close();
reader.close();
}
}
| liuzyw/study-hello | study-lucene/src/main/java/com/study/luence/day1/BooleanQueryTest.java | Java | apache-2.0 | 2,145 |
package uk.ac.kent.dover.fastGraph;
import java.nio.ByteBuffer;
import java.text.*;
import java.util.*;
import java.util.stream.*;
/**
* A class to hold a number of useful methods
*
* @author Rob Baker
*
*/
public class Util {
/**
* Rounds and sorts a double[][] to an int[][]
* @param arr a double[][] to be rounded
* @return The rounded int[][]
*/
public static int[][] roundArray(double[][] arr) {
int[][] newArr = new int[arr.length][arr[0].length];
for(int i = 0; i < arr.length; i++) {
for(int j = 0; j < arr[i].length; j++) {
newArr[i][j] = (int) Math.round(arr[i][j]);
}
}
Arrays.sort(newArr);
return newArr;
}
/**
* Rounds and sorts a double[] to an int[]
* @param arr a double[] to be rounded
* @return The rounded int[]
*/
public static int[] roundArray(double[] arr) {
int[] newArr = new int[arr.length];
for(int i = 0; i < arr.length; i++) {
newArr[i] = (int) Math.round(arr[i]);
}
Arrays.sort(newArr);
return newArr;
}
/**
* Rounds and a double[] to a less precise double[]
* @param arr a double[] to be rounded
* @param decimalPlaces the amount of decimal places to round each double in arr
* @return The rounded double[]
*/
public static double[] roundArray(double[] arr, int decimalPlaces) {
double[] newArr = new double[arr.length];
for(int i = 0; i < arr.length; i++) {
newArr[i] = round(arr[i],decimalPlaces);
if(newArr[i] == -0.0) {
newArr[i] = 0.0;
}
}
Arrays.sort(newArr);
return newArr;
}
/**
* Round to the given number of decimal places.
* @param d a double to be rounded
* @param decimalPlaces the number of decimal places
* @return The rounded double
*/
public static double round(double d,int decimalPlaces) {
long divider = 1;
for(int i = 1; i<= decimalPlaces; i++) {
divider *= 10;
}
double largeAmount = Math.rint(d*divider);
return(largeAmount/divider);
}
/**
* Rounds and Converts a double[].
* Multiplies each value by places and converts to an integer
*
* @param toConvert The array to convert
* @param places The number of decimal places to be retained
* @return The converted array
*/
public static int[] roundAndConvert(double[] toConvert, int places) {
int[] res = new int[toConvert.length];
for(int i = 0; i < toConvert.length; i++) {
res[i] = roundAndConvert(toConvert[i], places);
}
return res;
}
/**
* Rounds and Converts a double[].
* Multiplies each value by places and converts to an integer
*
* @param res The array to be populated
* @param toConvert The array to convert
* @param places The number of decimal places to be retained
* @return The converted array
*/
public static int[] roundAndConvert(int[] res, double[] toConvert, int places) {
for(int i = 0; i < toConvert.length; i++) {
res[i] = roundAndConvert(toConvert[i],places);
}
return res;
}
/**
* Rounds and Converts a double.
* Multiplies each value by places and converts to an integer
*
* @param toConvert The double to convert
* @param places The number of decimal places to be retained
* @return The converted and rounded int
*/
public static int roundAndConvert(double toConvert, int places) {
return (int) Math.round(toConvert*places);
}
/**
* Checks if a String is a positive integer.
*
* @param input The String to be converted
* @throws NumberFormatException If the input is not an integer, or $lt; 0.
* @return The positive integer
*/
public static int checkForPositiveInteger(String input) throws NumberFormatException {
int number = Integer.parseInt(input);
if (number < 0) {
throw new NumberFormatException();
} else {
return number;
}
}
/**
* Converts a LinkedList of any given object into an array of that object
*
* @param <T> The type of objects in the list
* @param list The list to be converted
* @param array The array to be populated with the new objects
*/
public static <T> void convertLinkedListObject(LinkedList<T> list, T[] array) {
list.toArray(array);
}
/**
* Converts a LinkedList of Integer to an int[] using streams
*
* @param list The linked list to convert
* @return The newly created array
*/
public static int[] convertLinkedList(LinkedList<Integer> list) {
return list.stream().mapToInt(i->i).toArray();
}
/**
* Converts a ArrayList of Integer to an int[] using streams
*
* @param list The ArrayList to convert
* @return The newly created array
*/
public static int[] convertArrayList(ArrayList<Integer> list) {
return list.stream().mapToInt(i->i).toArray();
}
/**
* Converts a LinkedList of Integer to a given int[] using streams
*
* @param list The linked list to convert
* @param array The array to be populated
*/
public static void convertLinkedList(LinkedList<Integer> list, int[] array) {
array = list.stream().mapToInt(i->i).toArray();
}
/**
* Converts an int[] to a LinkedList of Integer using streams
*
* @param array The array to convert
* @return The newly created LinkedList
*/
public static LinkedList<Integer> convertArray(int[] array) {
return new LinkedList<Integer>(IntStream.of(array).boxed().collect(Collectors.toList()));
}
/**
* Converts an int[] to a LinkedList of Integer using streams
*
* @param array The array to convert
* @param list The newly populated LinkedList
*/
public static void convertArray(int[] array, LinkedList<Integer> list) {
list.addAll(IntStream.of(array).boxed().collect(Collectors.toList()));
}
/**
* Adds all items in a primitive array to the given linked list
* @param list The list to be added to
* @param array The array of items to add
*/
public static void addAll(LinkedList<Integer> list, int[] array) {
for(int i : array) {
list.add(i);
}
}
/**
* Adds all items in a primitive array to the given linked hash set
* @param set The set to be added to
* @param array The array of items to add
*/
public static void addAll(LinkedHashSet<Integer> set, int[] array) {
for(int i : array) {
set.add(i);
}
}
/**
* Adds all items in a primitive array to the given hash set
* @param set The set to be added to
* @param array The array of items to add
*/
public static void addAll(HashSet<Integer> set, int[] array) {
for(int i : array) {
set.add(i);
}
}
/**
* Converts a HashSet of Integer to int[]
*
* @param set The set to be converted
* @return The newly converted array
*/
public static int[] convertHashSet(HashSet<Integer> set) {
return set.stream().mapToInt(i->i).toArray();
}
/**
* Converts a HashSet of Integer to a given int[]
*
* @param set The set to be converted
* @param array The newly converted array
*/
public static void convertHashSet(int[] array, HashSet<Integer> set) {
array = set.stream().mapToInt(i->i).toArray();
}
/**
* Converts an int[] to a HashSet of Integer using streams
*
* @param array The array to convert
* @param set The set to store the results in
*/
public static void convertArray(int[] array, HashSet<Integer> set) {
set.addAll(IntStream.of(array).boxed().collect(Collectors.toList()));
}
/**
* Deep copy of ByteBuffer.
* @param original the ByteBuffer to copy
* @return new ByteBuffer with a copy of the content of original.
*/
public static ByteBuffer cloneByteBuffer(ByteBuffer original) {
ByteBuffer clone = ByteBuffer.allocate(original.capacity());
original.rewind();//copy from the beginning
clone.put(original);
original.rewind();
clone.flip();
return clone;
}
/**
* Gets a specific numbered item from the HashSet given.<br>
* There is no guarantee this may pick the same entry if run multiple times.
*
* @param <T> The type of object in the set
* @param set The Set to look through
* @param number The item nmber to return
* @return The item
*/
public static <T> T getFromHashSet(HashSet<T> set, int number) {
int i = 0;
for (T item : set) {
if (i == number) {
return item;
}
i++;
}
return null;
}
/**
* Returns a sublist.<br>
* A copy of List.sublist() except the end is checked and shortened if too long
*
* @param <T> The type of object in the list
* @param list The list to have a sublist of
* @param start The start index
* @param end The end index
* @return The sublist
*/
public static <T> List<T> subList(ArrayList<T> list, int start, int end) {
if(end > list.size()) {
end = list.size();
}
return list.subList(start, end);
}
/**
* Returns the arithmetic mean of an array of doubles
* @param array The array
* @return The mean
*/
public static double mean(double[] array) {
if(array.length == 0) { //incase the array is empty
return Double.NaN;
}
int total = 0;
for(int i = 0; i < array.length; i++) {
total += array[i];
}
return total/array.length;
}
/**
* Returns the standard deviation of an array
*
* @param array The array itself
* @param mean The mean of the array
* @return The standard deviation
*/
public static double standardDeviation(double[] array, double mean) {
if (array.length == 0) {
return Double.NaN;
}
double result = 0;
for(int i = 0; i < array.length; i++) {
result += Math.pow(array[i] - mean, 2);
}
result = result / (array.length-1); //variance
return Math.sqrt(result);
}
/**
* Returns the standard deviation of an array
*
* @param <T> The type of object in the array. Must be a Number.
* @param array The array itself
* @param mean The mean of the array
* @return The standard deviation
*/
public static <T extends Number> double standardDeviation(ArrayList<T> array, double mean) {
if (array.size() == 0) {
return Double.NaN;
}
double result = 0;
for(int i = 0; i < array.size(); i++) {
result += Math.pow(((Double) array.get(i)) - mean, 2);
}
result = result / (array.size()-1); //variance
return Math.sqrt(result);
}
/**
* Picks a random sublist of a list. Will not pick duplicates
*
* @param <T> The type of object in the list
* @param r The Random generator
* @param number The number of items to choose
* @param target The items to choose from
* @return The random sublist
* @throws FastGraphException If the list is too small
*/
public static <T> ArrayList<T> randomSelection(Random r, int number, ArrayList<T> target) throws FastGraphException {
// not enough choices
if(number > target.size()) {
throw new FastGraphException("Number of options is larger than target size");
} else if (number == target.size()) {
//equal choices, so just shuffle list
ArrayList<T> result = new ArrayList<T>(number); //for storing the result
Collections.shuffle(result);
return result;
}
ArrayList<T> result = new ArrayList<T>(number); //for storing the result
ArrayList<T> toChooseFrom = new ArrayList<T>(target); //copy of the list
for(int i = 0; i < number; i++) {
int index = r.nextInt(toChooseFrom.size());
result.add(toChooseFrom.get(index));
toChooseFrom.remove(index);
}
toChooseFrom = null; //GC
return result;
}
/**
* Returns the current date as yyyyMMdd_HHmm
* @return the current date
*/
public static String dateAsString() {
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyyMMdd'_'HHmm"); // Quoted "Z" to indicate UTC, no timezone offset
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());
return nowAsISO;
}
/**
* Picks a random int in the range of 0(inc) to size(exc) where the int is not in deleteList
* @param r Random number generator
* @param size The range of items to pick
* @param deleteList But not in this list
* @return The random result
*/
public static int pickValidItem(Random r, int size, Collection<Integer> deleteList) {
if(size == 0 || (deleteList.size() >= size)) { //no results possible
return -1;
}
while(true) {
int pick = r.nextInt(size);
if(!deleteList.contains(pick)) {
return pick;
}
}
}
/**
* Picks a random item from a list
*
* @param <T> The type of object in the list
* @param r Random number generator
* @param list The list to pick from
* @return The random item
*/
public static <T> T pickRandom(Random r, ArrayList<T> list) {
int i = r.nextInt(list.size());
return list.get(i);
}
/**
* Checks if any of the objects are null
* @param objects The objects to check
* @return If any are null
*/
public static boolean areAnyObjectsNull(Object... objects) {
if (Stream.of(objects).anyMatch(x -> x == null)) {
return true;
}
return false;
}
/**
* output matrix in readable format for debugging.
*
* @param matrix the matrix to format
* @return a string with a formatted matrix
*/
public static String formatMatrix(double[][] matrix) {
String ret = "";
for(int y = 0; y < matrix.length; y++) {
for(int x = 0; x < matrix[y].length; x++) {
ret += matrix[y][x]+"\t";
}
ret += "\n";
}
return ret;
}
/**
* output matrix in readable format for debugging. Must be a square matrix
*
* @param matrix the matrix to format
* @return a string with a formatted matrix
*/
public static String formatMatrix(int[][] matrix) {
String ret = "";
for(int y = 0; y < matrix.length; y++) {
for(int x = 0; x < matrix[y].length; x++) {
ret += matrix[y][x]+"\t";
}
ret += "\n";
}
return ret;
}
}
| peterrodgers/dover | src/uk/ac/kent/dover/fastGraph/Util.java | Java | apache-2.0 | 14,030 |
/*
* Copyright 2014-2019 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.personalize.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.personalize.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* ListCampaignsResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListCampaignsResultJsonUnmarshaller implements Unmarshaller<ListCampaignsResult, JsonUnmarshallerContext> {
public ListCampaignsResult unmarshall(JsonUnmarshallerContext context) throws Exception {
ListCampaignsResult listCampaignsResult = new ListCampaignsResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return listCampaignsResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("campaigns", targetDepth)) {
context.nextToken();
listCampaignsResult.setCampaigns(new ListUnmarshaller<CampaignSummary>(CampaignSummaryJsonUnmarshaller.getInstance()).unmarshall(context));
}
if (context.testExpression("nextToken", targetDepth)) {
context.nextToken();
listCampaignsResult.setNextToken(context.getUnmarshaller(String.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return listCampaignsResult;
}
private static ListCampaignsResultJsonUnmarshaller instance;
public static ListCampaignsResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new ListCampaignsResultJsonUnmarshaller();
return instance;
}
}
| jentfoo/aws-sdk-java | aws-java-sdk-personalize/src/main/java/com/amazonaws/services/personalize/model/transform/ListCampaignsResultJsonUnmarshaller.java | Java | apache-2.0 | 3,100 |
/*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.retail.v2.model;
/**
* Response message for SearchService.Search method.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Retail API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GoogleCloudRetailV2SearchResponse extends com.google.api.client.json.GenericJson {
/**
* The fully qualified resource name of applied [controls](https://cloud.google.com/retail/docs
* /serving-control-rules).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> appliedControls;
/**
* A unique search token. This should be included in the UserEvent logs resulting from this
* search, which enables accurate attribution of search model performance.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String attributionToken;
/**
* If spell correction applies, the corrected query. Otherwise, empty.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String correctedQuery;
/**
* Results of facets requested by user.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GoogleCloudRetailV2SearchResponseFacet> facets;
/**
* The invalid SearchRequest.BoostSpec.condition_boost_specs that are not applied during serving.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GoogleCloudRetailV2SearchRequestBoostSpecConditionBoostSpec> invalidConditionBoostSpecs;
static {
// hack to force ProGuard to consider GoogleCloudRetailV2SearchRequestBoostSpecConditionBoostSpec used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(GoogleCloudRetailV2SearchRequestBoostSpecConditionBoostSpec.class);
}
/**
* A token that can be sent as SearchRequest.page_token to retrieve the next page. If this field
* is omitted, there are no subsequent pages.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String nextPageToken;
/**
* Query expansion information for the returned results.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleCloudRetailV2SearchResponseQueryExpansionInfo queryExpansionInfo;
/**
* The URI of a customer-defined redirect page. If redirect action is triggered, no search will be
* performed, and only redirect_uri and attribution_token will be set in the response.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String redirectUri;
/**
* A list of matched items. The order represents the ranking.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GoogleCloudRetailV2SearchResponseSearchResult> results;
/**
* The estimated total count of matched items irrespective of pagination. The count of results
* returned by pagination may be less than the total_size that matches.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer totalSize;
/**
* The fully qualified resource name of applied [controls](https://cloud.google.com/retail/docs
* /serving-control-rules).
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getAppliedControls() {
return appliedControls;
}
/**
* The fully qualified resource name of applied [controls](https://cloud.google.com/retail/docs
* /serving-control-rules).
* @param appliedControls appliedControls or {@code null} for none
*/
public GoogleCloudRetailV2SearchResponse setAppliedControls(java.util.List<java.lang.String> appliedControls) {
this.appliedControls = appliedControls;
return this;
}
/**
* A unique search token. This should be included in the UserEvent logs resulting from this
* search, which enables accurate attribution of search model performance.
* @return value or {@code null} for none
*/
public java.lang.String getAttributionToken() {
return attributionToken;
}
/**
* A unique search token. This should be included in the UserEvent logs resulting from this
* search, which enables accurate attribution of search model performance.
* @param attributionToken attributionToken or {@code null} for none
*/
public GoogleCloudRetailV2SearchResponse setAttributionToken(java.lang.String attributionToken) {
this.attributionToken = attributionToken;
return this;
}
/**
* If spell correction applies, the corrected query. Otherwise, empty.
* @return value or {@code null} for none
*/
public java.lang.String getCorrectedQuery() {
return correctedQuery;
}
/**
* If spell correction applies, the corrected query. Otherwise, empty.
* @param correctedQuery correctedQuery or {@code null} for none
*/
public GoogleCloudRetailV2SearchResponse setCorrectedQuery(java.lang.String correctedQuery) {
this.correctedQuery = correctedQuery;
return this;
}
/**
* Results of facets requested by user.
* @return value or {@code null} for none
*/
public java.util.List<GoogleCloudRetailV2SearchResponseFacet> getFacets() {
return facets;
}
/**
* Results of facets requested by user.
* @param facets facets or {@code null} for none
*/
public GoogleCloudRetailV2SearchResponse setFacets(java.util.List<GoogleCloudRetailV2SearchResponseFacet> facets) {
this.facets = facets;
return this;
}
/**
* The invalid SearchRequest.BoostSpec.condition_boost_specs that are not applied during serving.
* @return value or {@code null} for none
*/
public java.util.List<GoogleCloudRetailV2SearchRequestBoostSpecConditionBoostSpec> getInvalidConditionBoostSpecs() {
return invalidConditionBoostSpecs;
}
/**
* The invalid SearchRequest.BoostSpec.condition_boost_specs that are not applied during serving.
* @param invalidConditionBoostSpecs invalidConditionBoostSpecs or {@code null} for none
*/
public GoogleCloudRetailV2SearchResponse setInvalidConditionBoostSpecs(java.util.List<GoogleCloudRetailV2SearchRequestBoostSpecConditionBoostSpec> invalidConditionBoostSpecs) {
this.invalidConditionBoostSpecs = invalidConditionBoostSpecs;
return this;
}
/**
* A token that can be sent as SearchRequest.page_token to retrieve the next page. If this field
* is omitted, there are no subsequent pages.
* @return value or {@code null} for none
*/
public java.lang.String getNextPageToken() {
return nextPageToken;
}
/**
* A token that can be sent as SearchRequest.page_token to retrieve the next page. If this field
* is omitted, there are no subsequent pages.
* @param nextPageToken nextPageToken or {@code null} for none
*/
public GoogleCloudRetailV2SearchResponse setNextPageToken(java.lang.String nextPageToken) {
this.nextPageToken = nextPageToken;
return this;
}
/**
* Query expansion information for the returned results.
* @return value or {@code null} for none
*/
public GoogleCloudRetailV2SearchResponseQueryExpansionInfo getQueryExpansionInfo() {
return queryExpansionInfo;
}
/**
* Query expansion information for the returned results.
* @param queryExpansionInfo queryExpansionInfo or {@code null} for none
*/
public GoogleCloudRetailV2SearchResponse setQueryExpansionInfo(GoogleCloudRetailV2SearchResponseQueryExpansionInfo queryExpansionInfo) {
this.queryExpansionInfo = queryExpansionInfo;
return this;
}
/**
* The URI of a customer-defined redirect page. If redirect action is triggered, no search will be
* performed, and only redirect_uri and attribution_token will be set in the response.
* @return value or {@code null} for none
*/
public java.lang.String getRedirectUri() {
return redirectUri;
}
/**
* The URI of a customer-defined redirect page. If redirect action is triggered, no search will be
* performed, and only redirect_uri and attribution_token will be set in the response.
* @param redirectUri redirectUri or {@code null} for none
*/
public GoogleCloudRetailV2SearchResponse setRedirectUri(java.lang.String redirectUri) {
this.redirectUri = redirectUri;
return this;
}
/**
* A list of matched items. The order represents the ranking.
* @return value or {@code null} for none
*/
public java.util.List<GoogleCloudRetailV2SearchResponseSearchResult> getResults() {
return results;
}
/**
* A list of matched items. The order represents the ranking.
* @param results results or {@code null} for none
*/
public GoogleCloudRetailV2SearchResponse setResults(java.util.List<GoogleCloudRetailV2SearchResponseSearchResult> results) {
this.results = results;
return this;
}
/**
* The estimated total count of matched items irrespective of pagination. The count of results
* returned by pagination may be less than the total_size that matches.
* @return value or {@code null} for none
*/
public java.lang.Integer getTotalSize() {
return totalSize;
}
/**
* The estimated total count of matched items irrespective of pagination. The count of results
* returned by pagination may be less than the total_size that matches.
* @param totalSize totalSize or {@code null} for none
*/
public GoogleCloudRetailV2SearchResponse setTotalSize(java.lang.Integer totalSize) {
this.totalSize = totalSize;
return this;
}
@Override
public GoogleCloudRetailV2SearchResponse set(String fieldName, Object value) {
return (GoogleCloudRetailV2SearchResponse) super.set(fieldName, value);
}
@Override
public GoogleCloudRetailV2SearchResponse clone() {
return (GoogleCloudRetailV2SearchResponse) super.clone();
}
}
| googleapis/google-api-java-client-services | clients/google-api-services-retail/v2/1.31.0/com/google/api/services/retail/v2/model/GoogleCloudRetailV2SearchResponse.java | Java | apache-2.0 | 10,974 |
/****************************************************************
* Licensed to the AOS Community (AOS) under one or more *
* contributor license agreements. See the NOTICE file *
* distributed with this work for additional information *
* regarding copyright ownership. The AOS 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. *
****************************************************************/
/*
* 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 io.datalayer.conf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationAssert;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.FileConfiguration;
import org.apache.commons.configuration.HierarchicalConfiguration;
import org.apache.commons.configuration.SubnodeConfiguration;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.configuration.reloading.FileAlwaysReloadingStrategy;
import org.apache.commons.configuration.reloading.InvariantReloadingStrategy;
import org.apache.commons.configuration.resolver.CatalogResolver;
import org.apache.commons.configuration.tree.ConfigurationNode;
import org.apache.commons.configuration.tree.xpath.XPathExpressionEngine;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
/**
* test for loading and saving xml properties files
*
* @version $Id: TestXMLConfiguration.java 1301996 2012-03-17 20:30:39Z sebb $
*/
public class XmlConfigurationTest {
/** XML Catalog */
private static final String CATALOG_FILES = ConfigurationAssert.getTestFile("catalog.xml").getAbsolutePath();
/** Constant for the used encoding. */
static final String ENCODING = "ISO-8859-1";
/** Constant for the test system ID. */
static final String SYSTEM_ID = "properties.dtd";
/** Constant for the test public ID. */
static final String PUBLIC_ID = "-//Commons Configuration//DTD Test Configuration 1.3//EN";
/** Constant for the DOCTYPE declaration. */
static final String DOCTYPE_DECL = " PUBLIC \"" + PUBLIC_ID + "\" \"" + SYSTEM_ID + "\">";
/** Constant for the DOCTYPE prefix. */
static final String DOCTYPE = "<!DOCTYPE ";
/** Constant for the transformer factory property. */
static final String PROP_FACTORY = "javax.xml.transform.TransformerFactory";
/** The File that we test with */
private String testProperties = ConfigurationAssert.getTestFile("test.xml").getAbsolutePath();
private String testProperties2 = ConfigurationAssert.getTestFile("testDigesterConfigurationInclude1.xml")
.getAbsolutePath();
private String testBasePath = ConfigurationAssert.TEST_DIR.getAbsolutePath();
private File testSaveConf = ConfigurationAssert.getOutFile("testsave.xml");
private File testSaveFile = ConfigurationAssert.getOutFile("testsample2.xml");
private String testFile2 = ConfigurationAssert.getTestFile("sample.xml").getAbsolutePath();
/** Constant for the number of test threads. */
private static final int THREAD_COUNT = 5;
/** Constant for the number of loops in tests with multiple threads. */
private static final int LOOP_COUNT = 100;
private XMLConfiguration conf;
@Before
public void setUp() throws Exception {
conf = new XMLConfiguration();
conf.setFile(new File(testProperties));
conf.load();
removeTestFile();
}
@Test
public void testGetProperty() {
assertEquals("value", conf.getProperty("element"));
}
@Test
public void testGetCommentedProperty() {
assertEquals("", conf.getProperty("test.comment"));
}
@Test
public void testGetPropertyWithXMLEntity() {
assertEquals("1<2", conf.getProperty("test.entity"));
}
@Test
public void testClearProperty() throws Exception {
// test non-existent element
String key = "clearly";
conf.clearProperty(key);
assertNull(key, conf.getProperty(key));
assertNull(key, conf.getProperty(key));
// test single element
conf.load();
key = "clear.element";
conf.clearProperty(key);
assertNull(key, conf.getProperty(key));
assertNull(key, conf.getProperty(key));
// test single element with attribute
conf.load();
key = "clear.element2";
conf.clearProperty(key);
assertNull(key, conf.getProperty(key));
assertNull(key, conf.getProperty(key));
key = "clear.element2[@id]";
assertNotNull(key, conf.getProperty(key));
assertNotNull(key, conf.getProperty(key));
// test non-text/cdata element
conf.load();
key = "clear.comment";
conf.clearProperty(key);
assertNull(key, conf.getProperty(key));
assertNull(key, conf.getProperty(key));
// test cdata element
conf.load();
key = "clear.cdata";
conf.clearProperty(key);
assertNull(key, conf.getProperty(key));
assertNull(key, conf.getProperty(key));
// test multiple sibling elements
conf.load();
key = "clear.list.item";
conf.clearProperty(key);
assertNull(key, conf.getProperty(key));
assertNull(key, conf.getProperty(key));
key = "clear.list.item[@id]";
assertNotNull(key, conf.getProperty(key));
assertNotNull(key, conf.getProperty(key));
// test multiple, disjoined elements
conf.load();
key = "list.item";
conf.clearProperty(key);
assertNull(key, conf.getProperty(key));
assertNull(key, conf.getProperty(key));
}
@Test
public void testgetProperty() {
// test non-leaf element
Object property = conf.getProperty("clear");
assertNull(property);
// test non-existent element
property = conf.getProperty("e");
assertNull(property);
// test non-existent element
property = conf.getProperty("element3[@n]");
assertNull(property);
// test single element
property = conf.getProperty("element");
assertNotNull(property);
assertTrue(property instanceof String);
assertEquals("value", property);
// test single attribute
property = conf.getProperty("element3[@name]");
assertNotNull(property);
assertTrue(property instanceof String);
assertEquals("foo", property);
// test non-text/cdata element
property = conf.getProperty("test.comment");
assertEquals("", property);
// test cdata element
property = conf.getProperty("test.cdata");
assertNotNull(property);
assertTrue(property instanceof String);
assertEquals("<cdata value>", property);
// test multiple sibling elements
property = conf.getProperty("list.sublist.item");
assertNotNull(property);
assertTrue(property instanceof List);
List<?> list = (List<?>) property;
assertEquals(2, list.size());
assertEquals("five", list.get(0));
assertEquals("six", list.get(1));
// test multiple, disjoined elements
property = conf.getProperty("list.item");
assertNotNull(property);
assertTrue(property instanceof List);
list = (List<?>) property;
assertEquals(4, list.size());
assertEquals("one", list.get(0));
assertEquals("two", list.get(1));
assertEquals("three", list.get(2));
assertEquals("four", list.get(3));
// test multiple, disjoined attributes
property = conf.getProperty("list.item[@name]");
assertNotNull(property);
assertTrue(property instanceof List);
list = (List<?>) property;
assertEquals(2, list.size());
assertEquals("one", list.get(0));
assertEquals("three", list.get(1));
}
@Test
public void testGetAttribute() {
assertEquals("element3[@name]", "foo", conf.getProperty("element3[@name]"));
}
@Test
public void testClearAttribute() throws Exception {
// test non-existent attribute
String key = "clear[@id]";
conf.clearProperty(key);
assertNull(key, conf.getProperty(key));
assertNull(key, conf.getProperty(key));
// test single attribute
conf.load();
key = "clear.element2[@id]";
conf.clearProperty(key);
assertNull(key, conf.getProperty(key));
assertNull(key, conf.getProperty(key));
key = "clear.element2";
assertNotNull(key, conf.getProperty(key));
assertNotNull(key, conf.getProperty(key));
// test multiple, disjoined attributes
conf.load();
key = "clear.list.item[@id]";
conf.clearProperty(key);
assertNull(key, conf.getProperty(key));
assertNull(key, conf.getProperty(key));
key = "clear.list.item";
assertNotNull(key, conf.getProperty(key));
assertNotNull(key, conf.getProperty(key));
}
@Test
public void testSetAttribute() {
// replace an existing attribute
conf.setProperty("element3[@name]", "bar");
assertEquals("element3[@name]", "bar", conf.getProperty("element3[@name]"));
// set a new attribute
conf.setProperty("foo[@bar]", "value");
assertEquals("foo[@bar]", "value", conf.getProperty("foo[@bar]"));
conf.setProperty("name1", "value1");
assertEquals("value1", conf.getProperty("name1"));
}
@Test
public void testAddAttribute() {
conf.addProperty("element3[@name]", "bar");
List<Object> list = conf.getList("element3[@name]");
assertNotNull("null list", list);
assertTrue("'foo' element missing", list.contains("foo"));
assertTrue("'bar' element missing", list.contains("bar"));
assertEquals("list size", 2, list.size());
}
@Test
public void testAddObjectAttribute() {
conf.addProperty("test.boolean[@value]", Boolean.TRUE);
assertTrue("test.boolean[@value]", conf.getBoolean("test.boolean[@value]"));
}
/**
* Tests setting an attribute on the root element.
*/
@Test
public void testSetRootAttribute() throws ConfigurationException {
conf.setProperty("[@test]", "true");
assertEquals("Root attribute not set", "true", conf.getString("[@test]"));
conf.save(testSaveConf);
XMLConfiguration checkConf = new XMLConfiguration();
checkConf.setFile(testSaveConf);
checkSavedConfig(checkConf);
assertTrue("Attribute not found after save", checkConf.containsKey("[@test]"));
checkConf.setProperty("[@test]", "newValue");
checkConf.save();
conf = checkConf;
checkConf = new XMLConfiguration();
checkConf.setFile(testSaveConf);
checkSavedConfig(checkConf);
assertEquals("Attribute not modified after save", "newValue", checkConf.getString("[@test]"));
}
/**
* Tests whether the configuration's root node is initialized with a
* reference to the corresponding XML element.
*/
@Test
public void testGetRootReference() {
assertNotNull("Root node has no reference", conf.getRootNode().getReference());
}
@Test
public void testAddList() {
conf.addProperty("test.array", "value1");
conf.addProperty("test.array", "value2");
List<Object> list = conf.getList("test.array");
assertNotNull("null list", list);
assertTrue("'value1' element missing", list.contains("value1"));
assertTrue("'value2' element missing", list.contains("value2"));
assertEquals("list size", 2, list.size());
}
@Test
public void testGetComplexProperty() {
assertEquals("I'm complex!", conf.getProperty("element2.subelement.subsubelement"));
}
@Test
public void testSettingFileNames() {
conf = new XMLConfiguration();
conf.setFileName(testProperties);
assertEquals(testProperties.toString(), conf.getFileName());
conf.setBasePath(testBasePath);
conf.setFileName("hello.xml");
assertEquals("hello.xml", conf.getFileName());
assertEquals(testBasePath.toString(), conf.getBasePath());
assertEquals(new File(testBasePath, "hello.xml"), conf.getFile());
conf.setBasePath(testBasePath);
conf.setFileName("subdir/hello.xml");
assertEquals("subdir/hello.xml", conf.getFileName());
assertEquals(testBasePath.toString(), conf.getBasePath());
assertEquals(new File(testBasePath, "subdir/hello.xml"), conf.getFile());
}
@Test
public void testLoad() throws Exception {
conf = new XMLConfiguration();
conf.setFileName(testProperties);
conf.load();
assertEquals("I'm complex!", conf.getProperty("element2.subelement.subsubelement"));
}
@Test
public void testLoadWithBasePath() throws Exception {
conf = new XMLConfiguration();
conf.setFileName("test.xml");
conf.setBasePath(testBasePath);
conf.load();
assertEquals("I'm complex!", conf.getProperty("element2.subelement.subsubelement"));
}
/**
* Tests constructing an XMLConfiguration from a non existing file and later
* saving to this file.
*/
@Test
public void testLoadAndSaveFromFile() throws Exception {
// If the file does not exist, an empty config is created
conf = new XMLConfiguration(testSaveConf);
assertTrue(conf.isEmpty());
conf.addProperty("test", "yes");
conf.save();
conf = new XMLConfiguration(testSaveConf);
assertEquals("yes", conf.getString("test"));
}
/**
* Tests loading a configuration from a URL.
*/
@Test
public void testLoadFromURL() throws Exception {
URL url = new File(testProperties).toURI().toURL();
conf = new XMLConfiguration(url);
assertEquals("value", conf.getProperty("element"));
assertEquals(url, conf.getURL());
}
/**
* Tests loading from a stream.
*/
@Test
public void testLoadFromStream() throws Exception {
String xml = "<?xml version=\"1.0\"?><config><test>1</test></config>";
conf = new XMLConfiguration();
conf.load(new ByteArrayInputStream(xml.getBytes()));
assertEquals(1, conf.getInt("test"));
conf = new XMLConfiguration();
conf.load(new ByteArrayInputStream(xml.getBytes()), "UTF8");
assertEquals(1, conf.getInt("test"));
}
/**
* Tests loading a non well formed XML from a string.
*/
@Test(expected = ConfigurationException.class)
public void testLoadInvalidXML() throws Exception {
String xml = "<?xml version=\"1.0\"?><config><test>1</rest></config>";
conf = new XMLConfiguration();
conf.load(new StringReader(xml));
}
@Test
public void testSetProperty() throws Exception {
conf.setProperty("element.string", "hello");
assertEquals("'element.string'", "hello", conf.getString("element.string"));
assertEquals("XML value of element.string", "hello", conf.getProperty("element.string"));
}
@Test
public void testAddProperty() {
// add a property to a non initialized xml configuration
XMLConfiguration config = new XMLConfiguration();
config.addProperty("test.string", "hello");
assertEquals("'test.string'", "hello", config.getString("test.string"));
}
@Test
public void testAddObjectProperty() {
// add a non string property
conf.addProperty("test.boolean", Boolean.TRUE);
assertTrue("'test.boolean'", conf.getBoolean("test.boolean"));
}
@Test
public void testSave() throws Exception {
// add an array of strings to the configuration
conf.addProperty("string", "value1");
for (int i = 1; i < 5; i++) {
conf.addProperty("test.array", "value" + i);
}
// add an array of strings in an attribute
for (int i = 1; i < 5; i++) {
conf.addProperty("test.attribute[@array]", "value" + i);
}
// add comma delimited lists with escaped delimiters
conf.addProperty("split.list5", "a\\,b\\,c");
conf.setProperty("element3", "value\\,value1\\,value2");
conf.setProperty("element3[@name]", "foo\\,bar");
// save the configuration
conf.save(testSaveConf.getAbsolutePath());
// read the configuration and compare the properties
XMLConfiguration checkConfig = new XMLConfiguration();
checkConfig.setFileName(testSaveConf.getAbsolutePath());
checkSavedConfig(checkConfig);
}
/**
* Tests saving to a URL.
*/
@Test
public void testSaveToURL() throws Exception {
conf.save(testSaveConf.toURI().toURL());
XMLConfiguration checkConfig = new XMLConfiguration();
checkConfig.setFile(testSaveConf);
checkSavedConfig(checkConfig);
}
/**
* Tests saving to a stream.
*/
@Test
public void testSaveToStream() throws Exception {
assertNull(conf.getEncoding());
conf.setEncoding("UTF8");
FileOutputStream out = null;
try {
out = new FileOutputStream(testSaveConf);
conf.save(out);
} finally {
if (out != null) {
out.close();
}
}
XMLConfiguration checkConfig = new XMLConfiguration();
checkConfig.setFile(testSaveConf);
checkSavedConfig(checkConfig);
try {
out = new FileOutputStream(testSaveConf);
conf.save(out, "UTF8");
} finally {
if (out != null) {
out.close();
}
}
checkConfig.clear();
checkSavedConfig(checkConfig);
}
@Test
public void testAutoSave() throws Exception {
conf.setFile(testSaveConf);
assertFalse(conf.isAutoSave());
conf.setAutoSave(true);
assertTrue(conf.isAutoSave());
conf.setProperty("autosave", "ok");
// reload the configuration
XMLConfiguration conf2 = new XMLConfiguration(conf.getFile());
assertEquals("'autosave' property", "ok", conf2.getString("autosave"));
conf.clearTree("clear");
conf2 = new XMLConfiguration(conf.getFile());
Configuration sub = conf2.subset("clear");
assertTrue(sub.isEmpty());
}
/**
* Tests if a second file can be appended to a first.
*/
@Test
public void testAppend() throws Exception {
conf = new XMLConfiguration();
conf.setFileName(testProperties);
conf.load();
conf.load(testProperties2);
assertEquals("value", conf.getString("element"));
assertEquals("tasks", conf.getString("table.name"));
conf.save(testSaveConf);
conf = new XMLConfiguration(testSaveConf);
assertEquals("value", conf.getString("element"));
assertEquals("tasks", conf.getString("table.name"));
assertEquals("application", conf.getString("table[@tableType]"));
}
/**
* Tests saving attributes (related to issue 34442).
*/
@Test
public void testSaveAttributes() throws Exception {
conf.clear();
conf.load();
conf.save(testSaveConf);
conf = new XMLConfiguration();
conf.load(testSaveConf);
assertEquals("foo", conf.getString("element3[@name]"));
}
/**
* Tests collaboration between XMLConfiguration and a reloading strategy.
*/
@Test
public void testReloading() throws Exception {
assertNotNull(conf.getReloadingStrategy());
assertTrue(conf.getReloadingStrategy() instanceof InvariantReloadingStrategy);
PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter(testSaveConf));
out.println("<?xml version=\"1.0\"?><config><test>1</test></config>");
out.close();
out = null;
conf.setFile(testSaveConf);
FileAlwaysReloadingStrategy strategy = new FileAlwaysReloadingStrategy();
strategy.setRefreshDelay(100);
conf.setReloadingStrategy(strategy);
assertEquals(strategy, conf.getReloadingStrategy());
assertEquals("Wrong file monitored", testSaveConf.getAbsolutePath(), strategy.getMonitoredFile()
.getAbsolutePath());
conf.load();
assertEquals(1, conf.getInt("test"));
out = new PrintWriter(new FileWriter(testSaveConf));
out.println("<?xml version=\"1.0\"?><config><test>2</test></config>");
out.close();
out = null;
int value = conf.getInt("test");
assertEquals("No reloading performed", 2, value);
} finally {
if (out != null) {
out.close();
}
}
}
@Test
public void testReloadingOOM() throws Exception {
assertNotNull(conf.getReloadingStrategy());
assertTrue(conf.getReloadingStrategy() instanceof InvariantReloadingStrategy);
PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter(testSaveConf));
out.println("<?xml version=\"1.0\"?><config><test>1</test></config>");
out.close();
out = null;
conf.setFile(testSaveConf);
FileAlwaysReloadingStrategy strategy = new FileAlwaysReloadingStrategy();
strategy.setRefreshDelay(100);
conf.setReloadingStrategy(strategy);
conf.load();
assertEquals(1, conf.getInt("test"));
for (int i = 1; i < LOOP_COUNT; ++i) {
assertEquals(1, conf.getInt("test"));
}
} finally {
if (out != null) {
out.close();
}
}
}
/**
* Tests the refresh() method.
*/
@Test
public void testRefresh() throws ConfigurationException {
conf.setProperty("element", "anotherValue");
conf.refresh();
assertEquals("Wrong property after refresh", "value", conf.getString("element"));
}
/**
* Tries to call refresh() when the configuration is not associated with a
* file.
*/
@Test(expected = ConfigurationException.class)
public void testRefreshNoFile() throws ConfigurationException {
conf = new XMLConfiguration();
conf.refresh();
}
/**
* Tests access to tag names with delimiter characters.
*/
@Test
public void testComplexNames() {
assertEquals("Name with dot", conf.getString("complexNames.my..elem"));
assertEquals("Another dot", conf.getString("complexNames.my..elem.sub..elem"));
}
/**
* Creates a validating document builder.
*
* @return the document builder
* @throws ParserConfigurationException
* if an error occurs
*/
private DocumentBuilder createValidatingDocBuilder() throws ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new DefaultHandler() {
@Override
public void error(SAXParseException ex) throws SAXException {
throw ex;
}
});
return builder;
}
/**
* Tests setting a custom document builder.
*/
@Test
public void testCustomDocBuilder() throws Exception {
// Load an invalid XML file with the default (non validating)
// doc builder. This should work...
conf = new XMLConfiguration();
conf.load(ConfigurationAssert.getTestFile("testValidateInvalid.xml"));
assertEquals("customers", conf.getString("table.name"));
assertFalse(conf.containsKey("table.fields.field(1).type"));
}
/**
* Tests whether a validating document builder detects a validation error.
*/
@Test(expected = ConfigurationException.class)
public void testCustomDocBuilderValidationError() throws Exception {
DocumentBuilder builder = createValidatingDocBuilder();
conf = new XMLConfiguration();
conf.setDocumentBuilder(builder);
conf.load(new File("conf/testValidateInvalid.xml"));
}
/**
* Tests whether a valid document can be loaded with a validating document
* builder.
*/
@Test
public void testCustomDocBuilderValidationSuccess() throws Exception {
DocumentBuilder builder = createValidatingDocBuilder();
conf = new XMLConfiguration();
conf.setDocumentBuilder(builder);
conf.load(ConfigurationAssert.getTestFile("testValidateValid.xml"));
assertTrue(conf.containsKey("table.fields.field(1).type"));
}
/**
* Tests the clone() method.
*/
@Test
public void testClone() {
Configuration c = (Configuration) conf.clone();
assertTrue(c instanceof XMLConfiguration);
XMLConfiguration copy = (XMLConfiguration) c;
assertNotNull(conf.getDocument());
assertNull(copy.getDocument());
assertNotNull(conf.getFileName());
assertNull(copy.getFileName());
copy.setProperty("element3", "clonedValue");
assertEquals("value", conf.getString("element3"));
conf.setProperty("element3[@name]", "originalFoo");
assertEquals("foo", copy.getString("element3[@name]"));
}
/**
* Tests saving a configuration after cloning to ensure that the clone and
* the original are completely detached.
*/
@Test
public void testCloneWithSave() throws ConfigurationException {
XMLConfiguration c = (XMLConfiguration) conf.clone();
c.addProperty("test.newProperty", Boolean.TRUE);
conf.addProperty("test.orgProperty", Boolean.TRUE);
c.save(testSaveConf);
XMLConfiguration c2 = new XMLConfiguration(testSaveConf);
assertTrue("New property after clone() was not saved", c2.getBoolean("test.newProperty"));
assertFalse("Property of original config was saved", c2.containsKey("test.orgProperty"));
}
/**
* Tests the subset() method. There was a bug that calling subset() had
* undesired side effects.
*/
@Test
public void testSubset() throws ConfigurationException {
conf = new XMLConfiguration();
conf.load(ConfigurationAssert.getTestFile("testHierarchicalXMLConfiguration.xml"));
conf.subset("tables.table(0)");
conf.save(testSaveConf);
conf = new XMLConfiguration(testSaveConf);
assertEquals("users", conf.getString("tables.table(0).name"));
}
/**
* Tests string properties with list delimiters and escaped delimiters.
*/
@Test
public void testSplitLists() {
assertEquals("a", conf.getString("split.list3[@values]"));
assertEquals(2, conf.getMaxIndex("split.list3[@values]"));
assertEquals("a,b,c", conf.getString("split.list4[@values]"));
assertEquals("a", conf.getString("split.list1"));
assertEquals(2, conf.getMaxIndex("split.list1"));
assertEquals("a,b,c", conf.getString("split.list2"));
}
/**
* Tests string properties with list delimiters when delimiter parsing is
* disabled
*/
@Test
public void testDelimiterParsingDisabled() throws ConfigurationException {
XMLConfiguration conf2 = new XMLConfiguration();
conf2.setDelimiterParsingDisabled(true);
conf2.setFile(new File(testProperties));
conf2.load();
assertEquals("a,b,c", conf2.getString("split.list3[@values]"));
assertEquals(0, conf2.getMaxIndex("split.list3[@values]"));
assertEquals("a\\,b\\,c", conf2.getString("split.list4[@values]"));
assertEquals("a,b,c", conf2.getString("split.list1"));
assertEquals(0, conf2.getMaxIndex("split.list1"));
assertEquals("a\\,b\\,c", conf2.getString("split.list2"));
conf2 = new XMLConfiguration();
conf2.setExpressionEngine(new XPathExpressionEngine());
conf2.setDelimiterParsingDisabled(true);
conf2.setFile(new File(testProperties));
conf2.load();
assertEquals("a,b,c", conf2.getString("split/list3/@values"));
assertEquals(0, conf2.getMaxIndex("split/list3/@values"));
assertEquals("a\\,b\\,c", conf2.getString("split/list4/@values"));
assertEquals("a,b,c", conf2.getString("split/list1"));
assertEquals(0, conf2.getMaxIndex("split/list1"));
assertEquals("a\\,b\\,c", conf2.getString("split/list2"));
}
/**
* Tests string properties with list delimiters when delimiter parsing is
* disabled
*/
@Test
public void testSaveWithDelimiterParsingDisabled() throws ConfigurationException {
XMLConfiguration conf = new XMLConfiguration();
conf.setExpressionEngine(new XPathExpressionEngine());
conf.setDelimiterParsingDisabled(true);
conf.setAttributeSplittingDisabled(true);
conf.setFile(new File(testProperties));
conf.load();
assertEquals("a,b,c", conf.getString("split/list3/@values"));
assertEquals(0, conf.getMaxIndex("split/list3/@values"));
assertEquals("a\\,b\\,c", conf.getString("split/list4/@values"));
assertEquals("a,b,c", conf.getString("split/list1"));
assertEquals(0, conf.getMaxIndex("split/list1"));
assertEquals("a\\,b\\,c", conf.getString("split/list2"));
// save the configuration
conf.save(testSaveConf.getAbsolutePath());
// read the configuration and compare the properties
XMLConfiguration checkConfig = new XMLConfiguration();
checkConfig.setFileName(testSaveConf.getAbsolutePath());
checkSavedConfig(checkConfig);
XMLConfiguration config = new XMLConfiguration();
config.setFileName(testFile2);
// config.setExpressionEngine(new XPathExpressionEngine());
config.setDelimiterParsingDisabled(true);
config.setAttributeSplittingDisabled(true);
config.load();
config.setProperty("Employee[@attr1]", "3,2,1");
assertEquals("3,2,1", config.getString("Employee[@attr1]"));
config.save(testSaveFile.getAbsolutePath());
config = new XMLConfiguration();
config.setFileName(testSaveFile.getAbsolutePath());
// config.setExpressionEngine(new XPathExpressionEngine());
config.setDelimiterParsingDisabled(true);
config.setAttributeSplittingDisabled(true);
config.load();
config.setProperty("Employee[@attr1]", "1,2,3");
assertEquals("1,2,3", config.getString("Employee[@attr1]"));
config.setProperty("Employee[@attr2]", "one, two, three");
assertEquals("one, two, three", config.getString("Employee[@attr2]"));
config.setProperty("Employee.text", "a,b,d");
assertEquals("a,b,d", config.getString("Employee.text"));
config.setProperty("Employee.Salary", "100,000");
assertEquals("100,000", config.getString("Employee.Salary"));
config.save(testSaveFile.getAbsolutePath());
checkConfig = new XMLConfiguration();
checkConfig.setFileName(testSaveFile.getAbsolutePath());
checkConfig.setExpressionEngine(new XPathExpressionEngine());
checkConfig.setDelimiterParsingDisabled(true);
checkConfig.setAttributeSplittingDisabled(true);
checkConfig.load();
assertEquals("1,2,3", checkConfig.getString("Employee/@attr1"));
assertEquals("one, two, three", checkConfig.getString("Employee/@attr2"));
assertEquals("a,b,d", checkConfig.getString("Employee/text"));
assertEquals("100,000", checkConfig.getString("Employee/Salary"));
}
/**
* Tests whether a DTD can be accessed.
*/
@Test
public void testDtd() throws ConfigurationException {
conf = new XMLConfiguration("testDtd.xml");
assertEquals("value1", conf.getString("entry(0)"));
assertEquals("test2", conf.getString("entry(1)[@key]"));
}
/**
* Tests DTD validation using the setValidating() method.
*/
@Test
public void testValidating() throws ConfigurationException {
File nonValidFile = ConfigurationAssert.getTestFile("testValidateInvalid.xml");
conf = new XMLConfiguration();
assertFalse(conf.isValidating());
// Load a non valid XML document. Should work for isValidating() ==
// false
conf.load(nonValidFile);
assertEquals("customers", conf.getString("table.name"));
assertFalse(conf.containsKey("table.fields.field(1).type"));
// Now set the validating flag to true
conf.setValidating(true);
try {
conf.load(nonValidFile);
fail("Validation was not performed!");
} catch (ConfigurationException cex) {
// ok
}
}
/**
* Tests handling of empty elements.
*/
@Test
public void testEmptyElements() throws ConfigurationException {
assertTrue(conf.containsKey("empty"));
assertEquals("", conf.getString("empty"));
conf.addProperty("empty2", "");
conf.setProperty("empty", "no more empty");
conf.save(testSaveConf);
conf = new XMLConfiguration(testSaveConf);
assertEquals("no more empty", conf.getString("empty"));
assertEquals("", conf.getProperty("empty2"));
}
/**
* Tests the isEmpty() method for an empty configuration that was reloaded.
*/
@Test
public void testEmptyReload() throws ConfigurationException {
XMLConfiguration config = new XMLConfiguration();
assertTrue("Newly created configuration not empty", config.isEmpty());
config.save(testSaveConf);
config.load(testSaveConf);
assertTrue("Reloaded configuration not empty", config.isEmpty());
}
/**
* Tests whether the encoding is correctly detected by the XML parser. This
* is done by loading an XML file with the encoding "UTF-16". If this
* encoding is not detected correctly, an exception will be thrown that
* "Content is not allowed in prolog". This test case is related to issue
* 34204.
*/
@Test
@Ignore
public void testLoadWithEncoding() throws ConfigurationException {
File file = ConfigurationAssert.getTestFile("testEncoding.xml");
conf = new XMLConfiguration();
conf.load(file);
assertEquals("test3_yoge", conf.getString("yoge"));
}
/**
* Tests whether the encoding is written to the generated XML file.
*/
@Test
public void testSaveWithEncoding() throws ConfigurationException {
conf = new XMLConfiguration();
conf.setProperty("test", "a value");
conf.setEncoding(ENCODING);
StringWriter out = new StringWriter();
conf.save(out);
assertTrue("Encoding was not written to file", out.toString().indexOf("encoding=\"" + ENCODING + "\"") >= 0);
}
/**
* Tests whether a default encoding is used if no specific encoding is set.
* According to the XSLT specification (http://www.w3.org/TR/xslt#output)
* this should be either UTF-8 or UTF-16.
*/
@Test
public void testSaveWithNullEncoding() throws ConfigurationException {
conf = new XMLConfiguration();
conf.setProperty("testNoEncoding", "yes");
conf.setEncoding(null);
StringWriter out = new StringWriter();
conf.save(out);
assertTrue("Encoding was written to file", out.toString().indexOf("encoding=\"UTF-") >= 0);
}
/**
* Tests whether the DOCTYPE survives a save operation.
*/
@Test
public void testSaveWithDoctype() throws ConfigurationException {
String content = "<?xml version=\"1.0\"?>" + DOCTYPE + "properties" + DOCTYPE_DECL
+ "<properties version=\"1.0\"><entry key=\"test\">value</entry></properties>";
StringReader in = new StringReader(content);
conf = new XMLConfiguration();
conf.setFileName("testDtd.xml");
conf.load();
conf.clear();
conf.load(in);
assertEquals("Wrong public ID", PUBLIC_ID, conf.getPublicID());
assertEquals("Wrong system ID", SYSTEM_ID, conf.getSystemID());
StringWriter out = new StringWriter();
conf.save(out);
assertTrue("Did not find DOCTYPE", out.toString().indexOf(DOCTYPE) >= 0);
}
/**
* Tests setting public and system IDs for the D'OCTYPE and then saving the
* configuration. This should generate a DOCTYPE declaration.
*/
@Test
public void testSaveWithDoctypeIDs() throws ConfigurationException {
assertNull("A public ID was found", conf.getPublicID());
assertNull("A system ID was found", conf.getSystemID());
conf.setPublicID(PUBLIC_ID);
conf.setSystemID(SYSTEM_ID);
StringWriter out = new StringWriter();
conf.save(out);
assertTrue("Did not find DOCTYPE", out.toString().indexOf(DOCTYPE + "testconfig" + DOCTYPE_DECL) >= 0);
}
/**
* Tests saving a configuration when an invalid transformer factory is
* specified. In this case the error thrown by the TransformerFactory class
* should be caught and re-thrown as a ConfigurationException.
*/
@Test
public void testSaveWithInvalidTransformerFactory() {
System.setProperty(PROP_FACTORY, "an.invalid.Class");
try {
conf.save(testSaveConf);
fail("Could save with invalid TransformerFactory!");
} catch (ConfigurationException cex) {
// ok
} finally {
System.getProperties().remove(PROP_FACTORY);
}
}
/**
* Tests if reloads are recognized by subset().
*/
@Test
public void testSubsetWithReload() throws ConfigurationException {
XMLConfiguration c = setUpReloadTest();
Configuration sub = c.subset("test");
assertEquals("New value not read", "newValue", sub.getString("entity"));
}
/**
* Tests if reloads are recognized by configurationAt().
*/
@Test
public void testConfigurationAtWithReload() throws ConfigurationException {
XMLConfiguration c = setUpReloadTest();
HierarchicalConfiguration sub = c.configurationAt("test(0)");
assertEquals("New value not read", "newValue", sub.getString("entity"));
}
/**
* Tests if reloads are recognized by configurationsAt().
*/
@Test
public void testConfigurationsAtWithReload() throws ConfigurationException {
XMLConfiguration c = setUpReloadTest();
List<HierarchicalConfiguration> configs = c.configurationsAt("test");
assertEquals("New value not read", "newValue", configs.get(0).getString("entity"));
}
/**
* Tests whether reloads are recognized when querying the configuration's
* keys.
*/
@Test
public void testGetKeysWithReload() throws ConfigurationException {
XMLConfiguration c = setUpReloadTest();
conf.addProperty("aNewKey", "aNewValue");
conf.save(testSaveConf);
boolean found = false;
for (Iterator<String> it = c.getKeys(); it.hasNext();) {
if ("aNewKey".equals(it.next())) {
found = true;
}
}
assertTrue("Reload not performed", found);
}
/**
* Tests accessing properties when the XPATH expression engine is set.
*/
@Test
public void testXPathExpressionEngine() {
conf.setExpressionEngine(new XPathExpressionEngine());
assertEquals("Wrong attribute value", "foo\"bar", conf.getString("test[1]/entity/@name"));
conf.clear();
assertNull(conf.getString("test[1]/entity/@name"));
}
/**
* Tests the copy constructor.
*/
@Test
public void testInitCopy() throws ConfigurationException {
XMLConfiguration copy = new XMLConfiguration(conf);
assertEquals("value", copy.getProperty("element"));
assertNull("Document was copied, too", copy.getDocument());
ConfigurationNode root = copy.getRootNode();
for (ConfigurationNode node : root.getChildren()) {
assertNull("Reference was not cleared", node.getReference());
}
removeTestFile();
copy.setFile(testSaveConf);
copy.save();
copy.clear();
checkSavedConfig(copy);
}
/**
* Tests setting text of the root element.
*/
@Test
public void testSetTextRootElement() throws ConfigurationException {
conf.setProperty("", "Root text");
conf.save(testSaveConf);
XMLConfiguration copy = new XMLConfiguration();
copy.setFile(testSaveConf);
checkSavedConfig(copy);
}
/**
* Tests removing the text of the root element.
*/
@Test
public void testClearTextRootElement() throws ConfigurationException {
final String xml = "<e a=\"v\">text</e>";
conf.clear();
StringReader in = new StringReader(xml);
conf.load(in);
assertEquals("Wrong text of root", "text", conf.getString(""));
conf.clearProperty("");
conf.save(testSaveConf);
XMLConfiguration copy = new XMLConfiguration();
copy.setFile(testSaveConf);
checkSavedConfig(copy);
}
/**
* Tests list nodes with multiple values and attributes.
*/
@Test
public void testListWithAttributes() {
assertEquals("Wrong number of <a> elements", 6, conf.getList("attrList.a").size());
assertEquals("Wrong value of first element", "ABC", conf.getString("attrList.a(0)"));
assertEquals("Wrong value of first name attribute", "x", conf.getString("attrList.a(0)[@name]"));
assertEquals("Wrong number of name attributes", 5, conf.getList("attrList.a[@name]").size());
}
/**
* Tests a list node with attributes that has multiple values separated by
* the list delimiter. In this scenario the attribute should be added to the
* node with the first value.
*/
@Test
public void testListWithAttributesMultiValue() {
assertEquals("Wrong value of 2nd element", "1", conf.getString("attrList.a(1)"));
assertEquals("Wrong value of 2nd name attribute", "y", conf.getString("attrList.a(1)[@name]"));
for (int i = 2; i <= 3; i++) {
assertEquals("Wrong value of element " + (i + 1), i, conf.getInt("attrList.a(" + i + ")"));
assertFalse("element " + (i + 1) + " has attribute", conf.containsKey("attrList.a(2)[@name]"));
}
}
/**
* Tests a list node with a multi-value attribute and multiple values. All
* attribute values should be assigned to the node with the first value.
*/
@Test
public void testListWithMultiAttributesMultiValue() {
for (int i = 1; i <= 2; i++) {
assertEquals("Wrong value of multi-valued node", "value" + i, conf.getString("attrList.a(" + (i + 3) + ")"));
}
List<Object> attrs = conf.getList("attrList.a(4)[@name]");
final String attrVal = "uvw";
assertEquals("Wrong number of name attributes", attrVal.length(), attrs.size());
for (int i = 0; i < attrVal.length(); i++) {
assertEquals("Wrong value for attribute " + i, String.valueOf(attrVal.charAt(i)), attrs.get(i));
}
assertEquals("Wrong value of test attribute", "yes", conf.getString("attrList.a(4)[@test]"));
assertFalse("Name attribute for 2nd value", conf.containsKey("attrList.a(5)[@name]"));
assertFalse("Test attribute for 2nd value", conf.containsKey("attrList.a(5)[@test]"));
}
/**
* Tests whether the auto save mechanism is triggered by changes at a
* subnode configuration.
*/
@Test
public void testAutoSaveWithSubnodeConfig() throws ConfigurationException {
final String newValue = "I am autosaved";
conf.setFile(testSaveConf);
conf.setAutoSave(true);
Configuration sub = conf.configurationAt("element2.subelement");
sub.setProperty("subsubelement", newValue);
assertEquals("Change not visible to parent", newValue, conf.getString("element2.subelement.subsubelement"));
XMLConfiguration conf2 = new XMLConfiguration(testSaveConf);
assertEquals("Change was not saved", newValue, conf2.getString("element2.subelement.subsubelement"));
}
/**
* Tests whether a subnode configuration created from another subnode
* configuration of a XMLConfiguration can trigger the auto save mechanism.
*/
@Test
public void testAutoSaveWithSubSubnodeConfig() throws ConfigurationException {
final String newValue = "I am autosaved";
conf.setFile(testSaveConf);
conf.setAutoSave(true);
SubnodeConfiguration sub1 = conf.configurationAt("element2");
SubnodeConfiguration sub2 = sub1.configurationAt("subelement");
sub2.setProperty("subsubelement", newValue);
assertEquals("Change not visible to parent", newValue, conf.getString("element2.subelement.subsubelement"));
XMLConfiguration conf2 = new XMLConfiguration(testSaveConf);
assertEquals("Change was not saved", newValue, conf2.getString("element2.subelement.subsubelement"));
}
/**
* Tests saving and loading a configuration when delimiter parsing is
* disabled.
*/
@Test
public void testSaveDelimiterParsingDisabled() throws ConfigurationException {
checkSaveDelimiterParsingDisabled("list.delimiter.test");
}
/**
* Tests saving and loading a configuration when delimiter parsing is
* disabled and attributes are involved.
*/
@Test
public void testSaveDelimiterParsingDisabledAttrs() throws ConfigurationException {
checkSaveDelimiterParsingDisabled("list.delimiter.test[@attr]");
}
/**
* Helper method for testing saving and loading a configuration when
* delimiter parsing is disabled.
*
* @param key
* the key to be checked
* @throws ConfigurationException
* if an error occurs
*/
private void checkSaveDelimiterParsingDisabled(String key) throws ConfigurationException {
conf.clear();
conf.setDelimiterParsingDisabled(true);
conf.load();
conf.setProperty(key, "C:\\Temp\\,C:\\Data\\");
conf.addProperty(key, "a,b,c");
conf.save(testSaveConf);
XMLConfiguration checkConf = new XMLConfiguration();
checkConf.setDelimiterParsingDisabled(true);
checkConf.setFile(testSaveConf);
checkSavedConfig(checkConf);
}
/**
* Tests multiple attribute values in delimiter parsing disabled mode.
*/
@Test
public void testDelimiterParsingDisabledMultiAttrValues() throws ConfigurationException {
conf.clear();
conf.setDelimiterParsingDisabled(true);
conf.load();
List<Object> expr = conf.getList("expressions[@value]");
assertEquals("Wrong list size", 2, expr.size());
assertEquals("Wrong element 1", "a || (b && c)", expr.get(0));
assertEquals("Wrong element 2", "!d", expr.get(1));
}
/**
* Tests using multiple attribute values, which are partly escaped when
* delimiter parsing is not disabled.
*/
@Test
public void testMultipleAttrValuesEscaped() throws ConfigurationException {
conf.addProperty("test.dir[@name]", "C:\\Temp\\");
conf.addProperty("test.dir[@name]", "C:\\Data\\");
conf.save(testSaveConf);
XMLConfiguration checkConf = new XMLConfiguration();
checkConf.setFile(testSaveConf);
checkSavedConfig(checkConf);
}
/**
* Tests a combination of auto save = true and an associated reloading
* strategy.
*/
@Test
public void testAutoSaveWithReloadingStrategy() throws ConfigurationException {
conf.setFile(testSaveConf);
conf.save();
conf.setReloadingStrategy(new FileAlwaysReloadingStrategy());
conf.setAutoSave(true);
assertEquals("Value not found", "value", conf.getProperty("element"));
}
/**
* Tests adding nodes from another configuration.
*/
@Test
public void testAddNodesCopy() throws ConfigurationException {
XMLConfiguration c2 = new XMLConfiguration(testProperties2);
conf.addNodes("copiedProperties", c2.getRootNode().getChildren());
conf.save(testSaveConf);
XMLConfiguration checkConf = new XMLConfiguration();
checkConf.setFile(testSaveConf);
checkSavedConfig(checkConf);
}
/**
* Tests whether the addNodes() method triggers an auto save.
*/
@Test
public void testAutoSaveAddNodes() throws ConfigurationException {
conf.setFile(testSaveConf);
conf.setAutoSave(true);
HierarchicalConfiguration.Node node = new HierarchicalConfiguration.Node("addNodesTest", Boolean.TRUE);
Collection<ConfigurationNode> nodes = new ArrayList<ConfigurationNode>(1);
nodes.add(node);
conf.addNodes("test.autosave", nodes);
XMLConfiguration c2 = new XMLConfiguration(testSaveConf);
assertTrue("Added nodes are not saved", c2.getBoolean("test.autosave.addNodesTest"));
}
/**
* Tests saving a configuration after a node was added. Test for
* CONFIGURATION-294.
*
* @Test public void testAddNodesAndSave() throws ConfigurationException {
* ConfigurationNode node = new
* HierarchicalConfiguration.Node("test"); ConfigurationNode child =
* new HierarchicalConfiguration.Node("child"); node.addChild(child);
* ConfigurationNode attr = new
* HierarchicalConfiguration.Node("attr"); node.addAttribute(attr);
* ConfigurationNode node2 = conf.createNode("test2");
* Collection<ConfigurationNode> nodes = new
* ArrayList<ConfigurationNode>(2); nodes.add(node); nodes.add(node2);
* conf.addNodes("add.nodes", nodes); conf.setFile(testSaveConf);
* conf.save(); conf.setProperty("add.nodes.test", "true");
* conf.setProperty("add.nodes.test.child", "yes");
* conf.setProperty("add.nodes.test[@attr]", "existing");
* conf.setProperty("add.nodes.test2", "anotherValue"); conf.save();
* XMLConfiguration c2 = new XMLConfiguration(testSaveConf);
* assertEquals("Value was not saved", "true", c2
* .getString("add.nodes.test"));
* assertEquals("Child value was not saved", "yes", c2
* .getString("add.nodes.test.child"));
* assertEquals("Attr value was not saved", "existing", c2
* .getString("add.nodes.test[@attr]"));
* assertEquals("Node2 not saved", "anotherValue", c2
* .getString("add.nodes.test2")); }
*/
/**
* Tests registering the publicId of a DTD.
*/
@Test
public void testRegisterEntityId() throws Exception {
URL dtdURL = getClass().getResource("/properties.dtd");
final String publicId = "http://commons.apache.org/test/properties.dtd";
conf = new XMLConfiguration("testDtd.xml");
conf.setPublicID(publicId);
conf.save(testSaveConf);
XMLConfiguration checkConfig = new XMLConfiguration();
checkConfig.setFile(testSaveConf);
checkConfig.registerEntityId(publicId, dtdURL);
checkConfig.setValidating(true);
checkSavedConfig(checkConfig);
}
/**
* Tries to register a null public ID. This should cause an exception.
*/
@Test(expected = IllegalArgumentException.class)
public void testRegisterEntityIdNull() throws IOException {
conf.registerEntityId(null, new URL("http://commons.apache.org"));
}
/**
* Tests saving a configuration that was created from a hierarchical
* configuration. This test exposes bug CONFIGURATION-301.
*/
@Test
public void testSaveAfterCreateWithCopyConstructor() throws ConfigurationException {
HierarchicalConfiguration hc = conf.configurationAt("element2");
conf = new XMLConfiguration(hc);
conf.save(testSaveConf);
XMLConfiguration checkConfig = new XMLConfiguration();
checkConfig.setFile(testSaveConf);
checkSavedConfig(checkConfig);
assertEquals("Wrong name of root element", "element2", checkConfig.getRootElementName());
}
/**
* Tests whether the name of the root element is copied when a configuration
* is created using the copy constructor.
*/
@Test
public void testCopyRootName() throws ConfigurationException {
final String rootName = "rootElement";
final String xml = "<" + rootName + "><test>true</test></" + rootName + ">";
conf.clear();
conf.load(new StringReader(xml));
XMLConfiguration copy = new XMLConfiguration(conf);
assertEquals("Wrong name of root element", rootName, copy.getRootElementName());
copy.save(testSaveConf);
copy = new XMLConfiguration(testSaveConf);
assertEquals("Wrong name of root element after save", rootName, copy.getRootElementName());
}
/**
* Tests whether the name of the root element is copied for a configuration
* for which not yet a document exists.
*/
@Test
public void testCopyRootNameNoDocument() throws ConfigurationException {
final String rootName = "rootElement";
conf = new XMLConfiguration();
conf.setRootElementName(rootName);
conf.setProperty("test", Boolean.TRUE);
XMLConfiguration copy = new XMLConfiguration(conf);
assertEquals("Wrong name of root element", rootName, copy.getRootElementName());
copy.save(testSaveConf);
copy = new XMLConfiguration(testSaveConf);
assertEquals("Wrong name of root element after save", rootName, copy.getRootElementName());
}
/**
* Tests adding an attribute node using the addNodes() method.
*/
@Test
public void testAddNodesAttributeNode() {
conf.addProperty("testAddNodes.property[@name]", "prop1");
conf.addProperty("testAddNodes.property(0).value", "value1");
conf.addProperty("testAddNodes.property(-1)[@name]", "prop2");
conf.addProperty("testAddNodes.property(1).value", "value2");
Collection<ConfigurationNode> nodes = new ArrayList<ConfigurationNode>();
nodes.add(new HierarchicalConfiguration.Node("property"));
conf.addNodes("testAddNodes", nodes);
nodes.clear();
ConfigurationNode nd = new HierarchicalConfiguration.Node("name", "prop3");
nd.setAttribute(true);
nodes.add(nd);
conf.addNodes("testAddNodes.property(2)", nodes);
assertEquals("Attribute not added", "prop3", conf.getString("testAddNodes.property(2)[@name]"));
}
/**
* Tests whether spaces are preserved when the xml:space attribute is set.
*/
@Test
public void testPreserveSpace() {
assertEquals("Wrong value of blanc", " ", conf.getString("space.blanc"));
assertEquals("Wrong value of stars", " * * ", conf.getString("space.stars"));
}
/**
* Tests whether the xml:space attribute can be overridden in nested
* elements.
*/
@Test
public void testPreserveSpaceOverride() {
assertEquals("Not trimmed", "Some text", conf.getString("space.description"));
}
/**
* Tests an xml:space attribute with an invalid value. This will be
* interpreted as default.
*/
@Test
public void testPreserveSpaceInvalid() {
assertEquals("Invalid not trimmed", "Some other text", conf.getString("space.testInvalid"));
}
/**
* Tests whether attribute splitting can be disabled.
*/
@Test
public void testAttributeSplittingDisabled() throws ConfigurationException {
List<Object> values = conf.getList("expressions[@value2]");
assertEquals("Wrong number of attribute values", 2, values.size());
assertEquals("Wrong value 1", "a", values.get(0));
assertEquals("Wrong value 2", "b|c", values.get(1));
XMLConfiguration conf2 = new XMLConfiguration();
conf2.setAttributeSplittingDisabled(true);
conf2.setFile(conf.getFile());
conf2.load();
assertEquals("Attribute was split", "a,b|c", conf2.getString("expressions[@value2]"));
}
/**
* Tests disabling both delimiter parsing and attribute splitting.
*/
@Test
public void testAttributeSplittingAndDelimiterParsingDisabled() throws ConfigurationException {
conf.clear();
conf.setDelimiterParsingDisabled(true);
conf.load();
List<Object> values = conf.getList("expressions[@value2]");
assertEquals("Wrong number of attribute values", 2, values.size());
assertEquals("Wrong value 1", "a,b", values.get(0));
assertEquals("Wrong value 2", "c", values.get(1));
XMLConfiguration conf2 = new XMLConfiguration();
conf2.setAttributeSplittingDisabled(true);
conf2.setDelimiterParsingDisabled(true);
conf2.setFile(conf.getFile());
conf2.load();
assertEquals("Attribute was split", "a,b|c", conf2.getString("expressions[@value2]"));
}
/**
* Tests modifying an XML document and saving it with schema validation
* enabled.
*/
@Test
@Ignore
public void testSaveWithValidation() throws Exception {
CatalogResolver resolver = new CatalogResolver();
resolver.setCatalogFiles(CATALOG_FILES);
conf = new XMLConfiguration();
conf.setEntityResolver(resolver);
conf.setFileName(testFile2);
conf.setSchemaValidation(true);
conf.load();
conf.setProperty("Employee.SSN", "123456789");
conf.validate();
conf.save(testSaveConf);
conf = new XMLConfiguration(testSaveConf);
assertEquals("123456789", conf.getString("Employee.SSN"));
}
/**
* Tests modifying an XML document and validating it against the schema.
*/
@Test
@Ignore
public void testSaveWithValidationFailure() throws Exception {
CatalogResolver resolver = new CatalogResolver();
resolver.setCatalogFiles(CATALOG_FILES);
conf = new XMLConfiguration();
conf.setEntityResolver(resolver);
conf.setFileName(testFile2);
conf.setSchemaValidation(true);
conf.load();
conf.setProperty("Employee.Email", "[email protected]");
try {
conf.validate();
fail("No validation failure on save");
} catch (Exception e) {
Throwable cause = e.getCause();
assertNotNull("No cause for exception on save", cause);
assertTrue("Incorrect exception on save", cause instanceof SAXParseException);
}
}
@Test
public void testConcurrentGetAndReload() throws Exception {
// final FileConfiguration config = new
// PropertiesConfiguration("test.properties");
final FileConfiguration config = new XMLConfiguration("test.xml");
config.setReloadingStrategy(new FileAlwaysReloadingStrategy());
assertTrue("Property not found", config.getProperty("test.short") != null);
Thread testThreads[] = new Thread[THREAD_COUNT];
for (int i = 0; i < testThreads.length; ++i) {
testThreads[i] = new ReloadThread(config);
testThreads[i].start();
}
for (int i = 0; i < LOOP_COUNT; i++) {
assertTrue("Property not found", config.getProperty("test.short") != null);
}
for (int i = 0; i < testThreads.length; ++i) {
testThreads[i].join();
}
}
/**
* Tests whether a windows path can be saved correctly. This test is related
* to CONFIGURATION-428.
*/
@Test
public void testSaveWindowsPath() throws ConfigurationException {
conf.clear();
conf.addProperty("path", "C:\\Temp");
StringWriter writer = new StringWriter();
conf.save(writer);
String content = writer.toString();
assertTrue("Path not found: " + content, content.indexOf("<path>C:\\Temp</path>") >= 0);
conf.save(testSaveFile);
XMLConfiguration conf2 = new XMLConfiguration(testSaveFile);
assertEquals("Wrong windows path", "C:\\Temp", conf2.getString("path"));
}
/**
* Tests whether an attribute can be set to an empty string. This test is
* related to CONFIGURATION-446.
*/
@Test
public void testEmptyAttribute() throws ConfigurationException {
String key = "element3[@value]";
conf.setProperty(key, "");
assertTrue("Key not found", conf.containsKey(key));
assertEquals("Wrong value", "", conf.getString(key));
conf.save(testSaveConf);
conf = new XMLConfiguration();
conf.load(testSaveConf);
assertTrue("Key not found after save", conf.containsKey(key));
assertEquals("Wrong value after save", "", conf.getString(key));
}
/**
* Tests whether it is possible to add nodes to a XMLConfiguration through a
* SubnodeConfiguration and whether these nodes have the correct type. This
* test is related to CONFIGURATION-472.
*
* @Test public void testAddNodesToSubnodeConfiguration() throws Exception {
* SubnodeConfiguration sub = conf.configurationAt("element2");
* sub.addProperty("newKey", "newvalue"); ConfigurationNode root =
* conf.getRootNode(); ConfigurationNode elem =
* root.getChildren("element2").get(0); ConfigurationNode newNode =
* elem.getChildren("newKey").get(0); assertTrue("Wrong node type: " +
* newNode, newNode instanceof XMLConfiguration.XMLNode); }
*/
/**
* Prepares a configuration object for testing a reload operation.
*
* @return the initialized configuration
* @throws ConfigurationException
* if an error occurs
*/
private XMLConfiguration setUpReloadTest() throws ConfigurationException {
removeTestFile();
conf.save(testSaveConf);
XMLConfiguration c = new XMLConfiguration(testSaveConf);
c.setReloadingStrategy(new FileAlwaysReloadingStrategy());
conf.setProperty("test(0).entity", "newValue");
conf.save(testSaveConf);
return c;
}
/**
* Removes the test output file if it exists.
*/
private void removeTestFile() {
if (testSaveConf.exists()) {
assertTrue(testSaveConf.delete());
}
}
/**
* Helper method for checking if a save operation was successful. Loads a
* saved configuration and then tests against a reference configuration.
*
* @param checkConfig
* the configuration to check
* @throws ConfigurationException
* if an error occurs
*/
private void checkSavedConfig(FileConfiguration checkConfig) throws ConfigurationException {
checkConfig.load();
ConfigurationAssert.assertEquals(conf, checkConfig);
}
private class ReloadThread extends Thread {
FileConfiguration config;
ReloadThread(FileConfiguration config) {
this.config = config;
}
@Override
public void run() {
for (int i = 0; i < LOOP_COUNT; i++) {
config.reload();
}
}
}
}
| XClouded/t4f-core | devops/java/src/test/java/io/datalayer/conf/XmlConfigurationTest.java | Java | apache-2.0 | 66,459 |
/*
\\ * Copyright 2009-2010 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.batch.admin.web.util;
/**
* @author Suraj Muraleedharan
*
*/
public final class Constants {
/**
* job parameters regex
*/
public static final String JOB_PARAMETERS_REGEX = "([\\w\\.-_\\)\\(]+=[^,\\n]*[,\\n])*([\\w\\.-_\\)\\(]+=[^,]*$)";
/**
* job name
*/
public static final String JOB_NAME = "jobName";
/**
* job run date
*/
public static final String JOB_RUN_DATE = "jobRunDate";
/**
* Quartz group
*/
public static final String QUARTZ_GROUP = "quartzGroup";
/**
* Quartz trigger name suffix
*/
public static final String TRIGGER_SUFFIX = "QuartzTrigger";
/**
* Bean names
*/
public static final String JOB_SERVICE_BEAN = "jobService";
public static final String JOB_DATASTORE_BEAN = "batchDataStore";
}
| smshen/spring-batch-quartz-admin | src/main/java/org/springframework/batch/admin/web/util/Constants.java | Java | apache-2.0 | 1,554 |
package org.netcrusher.tcp.bulk;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.CopyOnWriteArrayList;
public class TcpBulkServer implements AutoCloseable {
private static final Logger LOGGER = LoggerFactory.getLogger(TcpBulkServer.class);
private final ServerSocketChannel serverSocketChannel;
private final Acceptor acceptor;
public TcpBulkServer(InetSocketAddress address, long limit) throws IOException {
this.serverSocketChannel = ServerSocketChannel.open();
this.serverSocketChannel.configureBlocking(true);
this.serverSocketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
this.serverSocketChannel.bind(address);
this.acceptor = new Acceptor(serverSocketChannel, limit);
}
public void open() {
this.acceptor.start();
}
@Override
public void close() throws Exception {
if (this.acceptor.isAlive()) {
this.acceptor.interrupt();
this.acceptor.join();
}
for (TcpBulkClient client : acceptor.clients) {
client.close();
}
if (this.serverSocketChannel.isOpen()) {
this.serverSocketChannel.close();
}
}
public Collection<TcpBulkClient> getClients() {
return new ArrayList<>(acceptor.clients);
}
private static class Acceptor extends Thread {
private final ServerSocketChannel serverSocketChannel;
private final Collection<TcpBulkClient> clients;
private final long limit;
public Acceptor(ServerSocketChannel serverSocketChannel, long limit) {
this.serverSocketChannel = serverSocketChannel;
this.clients = new CopyOnWriteArrayList<>();
this.limit = limit;
this.setName("Acceptor thread");
}
@Override
public void run() {
LOGGER.debug("Accepting thread has started");
try {
while (!Thread.currentThread().isInterrupted()) {
SocketChannel channel = serverSocketChannel.accept();
LOGGER.debug("Connection is accepted from <{}>", channel.getRemoteAddress());
TcpBulkClient client = TcpBulkClient.forSocket("INT-" + clients.size(), channel, limit);
clients.add(client);
}
} catch (ClosedChannelException e) {
LOGGER.debug("Socket is closed");
} catch (IOException e) {
LOGGER.error("Error while accepting", e);
}
LOGGER.debug("Accepting thread has finished");
}
}
}
| NetCrusherOrg/netcrusher-java | core/src/test/java/org/netcrusher/tcp/bulk/TcpBulkServer.java | Java | apache-2.0 | 2,964 |
package com.google.android.material.motion.sample;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Demo[] demos;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
demos = new Demo[]{
new Demo("Tossable Tap", new Intent(this, TossableTapActivity.class)),
new Demo("Tween", new Intent(this, TweenActivity.class)),
new Demo("Gesture", new Intent(this, GestureActivity.class)),
};
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(new DemoAdapter());
}
private static class Demo {
public String text;
public Intent intent;
public Demo(String text, Intent intent) {
this.text = text;
this.intent = intent;
}
}
private class DemoAdapter extends RecyclerView.Adapter<DemoViewHolder> {
@Override
public DemoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new DemoViewHolder(parent, getLayoutInflater());
}
@Override
public void onBindViewHolder(DemoViewHolder holder, int position) {
final Demo demo = demos[position];
holder.text.setText(demo.text);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(demo.intent);
}
});
}
@Override
public int getItemCount() {
return demos.length;
}
}
private class DemoViewHolder extends RecyclerView.ViewHolder {
private final TextView text;
public DemoViewHolder(ViewGroup parent, LayoutInflater inflater) {
super(inflater.inflate(R.layout.demo_view, parent, false));
text = (TextView) itemView.findViewById(R.id.text);
}
}
}
| material-motion/material-motion-android | sample/src/main/java/com/google/android/material/motion/sample/MainActivity.java | Java | apache-2.0 | 2,281 |
/*
* Copyright 2014-present Facebook, 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.facebook.buck.apple;
import com.dd.plist.NSArray;
import com.dd.plist.NSNumber;
import com.dd.plist.NSObject;
import com.dd.plist.NSString;
import com.facebook.buck.apple.platform_type.ApplePlatformType;
import com.facebook.buck.apple.toolchain.AppleCxxPlatform;
import com.facebook.buck.apple.toolchain.ApplePlatform;
import com.facebook.buck.apple.toolchain.AppleSdk;
import com.facebook.buck.apple.toolchain.CodeSignIdentity;
import com.facebook.buck.apple.toolchain.CodeSignIdentityStore;
import com.facebook.buck.apple.toolchain.ProvisioningProfileMetadata;
import com.facebook.buck.apple.toolchain.ProvisioningProfileStore;
import com.facebook.buck.core.build.buildable.context.BuildableContext;
import com.facebook.buck.core.build.context.BuildContext;
import com.facebook.buck.core.exceptions.HumanReadableException;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.impl.BuildTargetPaths;
import com.facebook.buck.core.rulekey.AddToRuleKey;
import com.facebook.buck.core.rules.ActionGraphBuilder;
import com.facebook.buck.core.rules.BuildRule;
import com.facebook.buck.core.rules.BuildRuleParams;
import com.facebook.buck.core.rules.SourcePathRuleFinder;
import com.facebook.buck.core.rules.attr.HasRuntimeDeps;
import com.facebook.buck.core.rules.impl.AbstractBuildRuleWithDeclaredAndExtraDeps;
import com.facebook.buck.core.rules.tool.BinaryBuildRule;
import com.facebook.buck.core.sourcepath.ExplicitBuildTargetSourcePath;
import com.facebook.buck.core.sourcepath.PathSourcePath;
import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.core.sourcepath.resolver.SourcePathResolver;
import com.facebook.buck.core.toolchain.tool.Tool;
import com.facebook.buck.core.toolchain.tool.impl.CommandTool;
import com.facebook.buck.core.util.log.Logger;
import com.facebook.buck.cxx.CxxPreprocessorInput;
import com.facebook.buck.cxx.HasAppleDebugSymbolDeps;
import com.facebook.buck.cxx.NativeTestable;
import com.facebook.buck.cxx.toolchain.CxxPlatform;
import com.facebook.buck.file.WriteFile;
import com.facebook.buck.io.BuildCellRelativePath;
import com.facebook.buck.io.file.MorePaths;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.rules.args.SourcePathArg;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.fs.CopyStep;
import com.facebook.buck.step.fs.FindAndReplaceStep;
import com.facebook.buck.step.fs.MakeCleanDirectoryStep;
import com.facebook.buck.step.fs.MkdirStep;
import com.facebook.buck.step.fs.MoveStep;
import com.facebook.buck.step.fs.RmStep;
import com.facebook.buck.step.fs.WriteFileStep;
import com.facebook.buck.util.types.Either;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import com.google.common.hash.HashCode;
import com.google.common.io.Files;
import com.google.common.util.concurrent.Futures;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Creates a bundle: a directory containing files and subdirectories, described by an Info.plist.
*/
public class AppleBundle extends AbstractBuildRuleWithDeclaredAndExtraDeps
implements NativeTestable, BuildRuleWithBinary, HasRuntimeDeps, BinaryBuildRule {
private static final Logger LOG = Logger.get(AppleBundle.class);
public static final String CODE_SIGN_ENTITLEMENTS = "CODE_SIGN_ENTITLEMENTS";
private static final String FRAMEWORK_EXTENSION =
AppleBundleExtension.FRAMEWORK.toFileExtension();
private static final String PP_DRY_RUN_RESULT_FILE = "BUCK_pp_dry_run.plist";
private static final String CODE_SIGN_DRY_RUN_ARGS_FILE = "BUCK_code_sign_args.plist";
private static final String CODE_SIGN_DRY_RUN_ENTITLEMENTS_FILE =
"BUCK_code_sign_entitlements.plist";
@AddToRuleKey private final String extension;
@AddToRuleKey private final Optional<String> productName;
@AddToRuleKey private final SourcePath infoPlist;
@AddToRuleKey private final ImmutableMap<String, String> infoPlistSubstitutions;
@AddToRuleKey private final Optional<SourcePath> entitlementsFile;
@AddToRuleKey private final Optional<BuildRule> binary;
@AddToRuleKey private final Optional<AppleDsym> appleDsym;
@AddToRuleKey private final ImmutableSet<BuildRule> extraBinaries;
@AddToRuleKey private final AppleBundleDestinations destinations;
@AddToRuleKey private final AppleBundleResources resources;
@AddToRuleKey private final Set<SourcePath> frameworks;
@AddToRuleKey private final Tool ibtool;
@AddToRuleKey private final ImmutableSortedSet<BuildTarget> tests;
@AddToRuleKey private final ApplePlatform platform;
@AddToRuleKey private final String sdkName;
@AddToRuleKey private final String sdkVersion;
@AddToRuleKey private final ProvisioningProfileStore provisioningProfileStore;
@AddToRuleKey private final Supplier<ImmutableList<CodeSignIdentity>> codeSignIdentitiesSupplier;
@AddToRuleKey private final Optional<Tool> codesignAllocatePath;
@AddToRuleKey private final Tool codesign;
@AddToRuleKey private final Optional<Tool> swiftStdlibTool;
@AddToRuleKey private final Tool lipo;
@AddToRuleKey private final boolean dryRunCodeSigning;
@AddToRuleKey private final ImmutableList<String> codesignFlags;
@AddToRuleKey private final Optional<String> codesignIdentitySubjectName;
// Need to use String here as RuleKeyBuilder requires that paths exist to compute hashes.
@AddToRuleKey private final ImmutableMap<SourcePath, String> extensionBundlePaths;
@AddToRuleKey private final boolean copySwiftStdlibToFrameworks;
private final Optional<AppleAssetCatalog> assetCatalog;
private final Optional<CoreDataModel> coreDataModel;
private final Optional<SceneKitAssets> sceneKitAssets;
private final Optional<String> platformBuildVersion;
private final Optional<String> xcodeVersion;
private final Optional<String> xcodeBuildVersion;
private final Path sdkPath;
private final String minOSVersion;
private final String binaryName;
private final Path bundleRoot;
private final Path binaryPath;
private final Path bundleBinaryPath;
private final boolean ibtoolModuleFlag;
private final ImmutableList<String> ibtoolFlags;
private final boolean hasBinary;
private final boolean cacheable;
private final boolean verifyResources;
private final Duration codesignTimeout;
private static final ImmutableList<String> BASE_IBTOOL_FLAGS =
ImmutableList.of(
"--output-format", "human-readable-text", "--notices", "--warnings", "--errors");
AppleBundle(
BuildTarget buildTarget,
ProjectFilesystem projectFilesystem,
BuildRuleParams params,
ActionGraphBuilder graphBuilder,
Either<AppleBundleExtension, String> extension,
Optional<String> productName,
SourcePath infoPlist,
Map<String, String> infoPlistSubstitutions,
Optional<BuildRule> binary,
Optional<AppleDsym> appleDsym,
ImmutableSet<BuildRule> extraBinaries,
AppleBundleDestinations destinations,
AppleBundleResources resources,
ImmutableMap<SourcePath, String> extensionBundlePaths,
Set<SourcePath> frameworks,
AppleCxxPlatform appleCxxPlatform,
Optional<AppleAssetCatalog> assetCatalog,
Optional<CoreDataModel> coreDataModel,
Optional<SceneKitAssets> sceneKitAssets,
Set<BuildTarget> tests,
CodeSignIdentityStore codeSignIdentityStore,
ProvisioningProfileStore provisioningProfileStore,
boolean dryRunCodeSigning,
boolean cacheable,
boolean verifyResources,
ImmutableList<String> codesignFlags,
Optional<String> codesignIdentity,
Optional<Boolean> ibtoolModuleFlag,
ImmutableList<String> ibtoolFlags,
Duration codesignTimeout,
boolean copySwiftStdlibToFrameworks) {
super(buildTarget, projectFilesystem, params);
this.extension =
extension.isLeft() ? extension.getLeft().toFileExtension() : extension.getRight();
this.productName = productName;
this.infoPlist = infoPlist;
this.infoPlistSubstitutions = ImmutableMap.copyOf(infoPlistSubstitutions);
this.binary = binary;
Optional<SourcePath> entitlementsFile = Optional.empty();
if (binary.isPresent()) {
Optional<HasEntitlementsFile> hasEntitlementsFile =
graphBuilder.requireMetadata(binary.get().getBuildTarget(), HasEntitlementsFile.class);
if (hasEntitlementsFile.isPresent()) {
entitlementsFile = hasEntitlementsFile.get().getEntitlementsFile();
}
}
this.entitlementsFile = entitlementsFile;
this.appleDsym = appleDsym;
this.extraBinaries = extraBinaries;
this.destinations = destinations;
this.resources = resources;
this.extensionBundlePaths = extensionBundlePaths;
this.frameworks = frameworks;
this.ibtool = appleCxxPlatform.getIbtool();
this.assetCatalog = assetCatalog;
this.coreDataModel = coreDataModel;
this.sceneKitAssets = sceneKitAssets;
this.binaryName = getBinaryName(getBuildTarget(), this.productName);
this.bundleRoot =
getBundleRoot(getProjectFilesystem(), getBuildTarget(), this.binaryName, this.extension);
this.binaryPath = this.destinations.getExecutablesPath().resolve(this.binaryName);
this.tests = ImmutableSortedSet.copyOf(tests);
AppleSdk sdk = appleCxxPlatform.getAppleSdk();
this.platform = sdk.getApplePlatform();
this.sdkName = sdk.getName();
this.sdkPath = appleCxxPlatform.getAppleSdkPaths().getSdkPath();
this.sdkVersion = sdk.getVersion();
this.minOSVersion = appleCxxPlatform.getMinVersion();
this.platformBuildVersion = appleCxxPlatform.getBuildVersion();
this.xcodeBuildVersion = appleCxxPlatform.getXcodeBuildVersion();
this.xcodeVersion = appleCxxPlatform.getXcodeVersion();
this.dryRunCodeSigning = dryRunCodeSigning;
this.cacheable = cacheable;
this.verifyResources = verifyResources;
this.codesignFlags = codesignFlags;
this.codesignIdentitySubjectName = codesignIdentity;
this.ibtoolModuleFlag = ibtoolModuleFlag.orElse(false);
this.ibtoolFlags = ibtoolFlags;
bundleBinaryPath = bundleRoot.resolve(binaryPath);
hasBinary = binary.isPresent() && binary.get().getSourcePathToOutput() != null;
if (needCodeSign() && !adHocCodeSignIsSufficient()) {
this.provisioningProfileStore = provisioningProfileStore;
this.codeSignIdentitiesSupplier = codeSignIdentityStore.getIdentitiesSupplier();
} else {
this.provisioningProfileStore = ProvisioningProfileStore.empty();
this.codeSignIdentitiesSupplier = Suppliers.ofInstance(ImmutableList.of());
}
this.codesignAllocatePath = appleCxxPlatform.getCodesignAllocate();
this.codesign =
appleCxxPlatform
.getCodesignProvider()
.resolve(graphBuilder, buildTarget.getTargetConfiguration());
this.swiftStdlibTool =
appleCxxPlatform.getSwiftPlatform().isPresent()
? appleCxxPlatform.getSwiftPlatform().get().getSwiftStdlibTool()
: Optional.empty();
this.lipo = appleCxxPlatform.getLipo();
this.codesignTimeout = codesignTimeout;
this.copySwiftStdlibToFrameworks = copySwiftStdlibToFrameworks;
}
public static String getBinaryName(BuildTarget buildTarget, Optional<String> productName) {
return productName.orElse(buildTarget.getShortName());
}
public static Path getBundleRoot(
ProjectFilesystem filesystem, BuildTarget buildTarget, String binaryName, String extension) {
return BuildTargetPaths.getGenPath(filesystem, buildTarget, "%s")
.resolve(binaryName + "." + extension);
}
public String getExtension() {
return extension;
}
@Override
public SourcePath getSourcePathToOutput() {
return ExplicitBuildTargetSourcePath.of(getBuildTarget(), bundleRoot);
}
public Path getInfoPlistPath() {
return getMetadataPath().resolve("Info.plist");
}
public Path getUnzippedOutputFilePathToBinary() {
return this.binaryPath;
}
private Path getMetadataPath() {
return bundleRoot.resolve(destinations.getMetadataPath());
}
public String getPlatformName() {
return platform.getName();
}
public Optional<BuildRule> getBinary() {
return binary;
}
public Optional<AppleDsym> getAppleDsym() {
return appleDsym;
}
public boolean isLegacyWatchApp() {
return extension.equals(AppleBundleExtension.APP.toFileExtension())
&& binary.isPresent()
&& binary
.get()
.getBuildTarget()
.getFlavors()
.contains(AppleBinaryDescription.LEGACY_WATCH_FLAVOR);
}
@Override
public ImmutableList<Step> getBuildSteps(
BuildContext context, BuildableContext buildableContext) {
ImmutableList.Builder<Step> stepsBuilder = ImmutableList.builder();
stepsBuilder.addAll(
MakeCleanDirectoryStep.of(
BuildCellRelativePath.fromCellRelativePath(
context.getBuildCellRootPath(), getProjectFilesystem(), bundleRoot)));
Path resourcesDestinationPath = bundleRoot.resolve(this.destinations.getResourcesPath());
if (assetCatalog.isPresent()) {
stepsBuilder.add(
MkdirStep.of(
BuildCellRelativePath.fromCellRelativePath(
context.getBuildCellRootPath(),
getProjectFilesystem(),
resourcesDestinationPath)));
Path bundleDir = assetCatalog.get().getOutputDir();
stepsBuilder.add(
CopyStep.forDirectory(
getProjectFilesystem(),
bundleDir,
resourcesDestinationPath,
CopyStep.DirectoryMode.CONTENTS_ONLY));
}
if (coreDataModel.isPresent()) {
stepsBuilder.add(
MkdirStep.of(
BuildCellRelativePath.fromCellRelativePath(
context.getBuildCellRootPath(),
getProjectFilesystem(),
resourcesDestinationPath)));
stepsBuilder.add(
CopyStep.forDirectory(
getProjectFilesystem(),
context
.getSourcePathResolver()
.getRelativePath(coreDataModel.get().getSourcePathToOutput()),
resourcesDestinationPath,
CopyStep.DirectoryMode.CONTENTS_ONLY));
}
if (sceneKitAssets.isPresent()) {
stepsBuilder.add(
MkdirStep.of(
BuildCellRelativePath.fromCellRelativePath(
context.getBuildCellRootPath(),
getProjectFilesystem(),
resourcesDestinationPath)));
stepsBuilder.add(
CopyStep.forDirectory(
getProjectFilesystem(),
context
.getSourcePathResolver()
.getRelativePath(sceneKitAssets.get().getSourcePathToOutput()),
resourcesDestinationPath,
CopyStep.DirectoryMode.CONTENTS_ONLY));
}
Path metadataPath = getMetadataPath();
Path infoPlistInputPath = context.getSourcePathResolver().getAbsolutePath(infoPlist);
Path infoPlistSubstitutionTempPath =
BuildTargetPaths.getScratchPath(getProjectFilesystem(), getBuildTarget(), "%s.plist");
Path infoPlistOutputPath = metadataPath.resolve("Info.plist");
stepsBuilder.add(
MkdirStep.of(
BuildCellRelativePath.fromCellRelativePath(
context.getBuildCellRootPath(), getProjectFilesystem(), metadataPath)));
if (needsPkgInfoFile()) {
// TODO(bhamiltoncx): This is only appropriate for .app bundles.
stepsBuilder.add(
new WriteFileStep(
getProjectFilesystem(),
"APPLWRUN",
metadataPath.resolve("PkgInfo"),
/* executable */ false));
}
stepsBuilder.add(
MkdirStep.of(
BuildCellRelativePath.fromCellRelativePath(
context.getBuildCellRootPath(),
getProjectFilesystem(),
infoPlistSubstitutionTempPath.getParent())),
new FindAndReplaceStep(
getProjectFilesystem(),
infoPlistInputPath,
infoPlistSubstitutionTempPath,
InfoPlistSubstitution.createVariableExpansionFunction(
withDefaults(
infoPlistSubstitutions,
ImmutableMap.of(
"EXECUTABLE_NAME", binaryName,
"PRODUCT_NAME", binaryName)))),
new PlistProcessStep(
getProjectFilesystem(),
infoPlistSubstitutionTempPath,
assetCatalog.map(AppleAssetCatalog::getOutputPlist),
infoPlistOutputPath,
getInfoPlistAdditionalKeys(),
getInfoPlistOverrideKeys(),
PlistProcessStep.OutputFormat.BINARY));
if (hasBinary) {
appendCopyBinarySteps(stepsBuilder, context);
appendCopyDsymStep(stepsBuilder, buildableContext, context);
}
if (!Iterables.isEmpty(
Iterables.concat(
resources.getResourceDirs(),
resources.getDirsContainingResourceDirs(),
resources.getResourceFiles()))) {
if (verifyResources) {
verifyResourceConflicts(resources, context.getSourcePathResolver());
}
stepsBuilder.add(
MkdirStep.of(
BuildCellRelativePath.fromCellRelativePath(
context.getBuildCellRootPath(),
getProjectFilesystem(),
resourcesDestinationPath)));
for (SourcePath dir : resources.getResourceDirs()) {
stepsBuilder.add(
CopyStep.forDirectory(
getProjectFilesystem(),
context.getSourcePathResolver().getAbsolutePath(dir),
resourcesDestinationPath,
CopyStep.DirectoryMode.DIRECTORY_AND_CONTENTS));
}
for (SourcePath dir : resources.getDirsContainingResourceDirs()) {
stepsBuilder.add(
CopyStep.forDirectory(
getProjectFilesystem(),
context.getSourcePathResolver().getAbsolutePath(dir),
resourcesDestinationPath,
CopyStep.DirectoryMode.CONTENTS_ONLY));
}
for (SourcePath file : resources.getResourceFiles()) {
Path resolvedFilePath = context.getSourcePathResolver().getAbsolutePath(file);
Path destinationPath = resourcesDestinationPath.resolve(resolvedFilePath.getFileName());
addResourceProcessingSteps(
context.getSourcePathResolver(), resolvedFilePath, destinationPath, stepsBuilder);
}
}
ImmutableList.Builder<Path> codeSignOnCopyPathsBuilder = ImmutableList.builder();
addStepsToCopyExtensionBundlesDependencies(context, stepsBuilder, codeSignOnCopyPathsBuilder);
for (SourcePath variantSourcePath : resources.getResourceVariantFiles()) {
Path variantFilePath = context.getSourcePathResolver().getAbsolutePath(variantSourcePath);
Path variantDirectory = variantFilePath.getParent();
if (variantDirectory == null || !variantDirectory.toString().endsWith(".lproj")) {
throw new HumanReadableException(
"Variant files have to be in a directory with name ending in '.lproj', "
+ "but '%s' is not.",
variantFilePath);
}
Path bundleVariantDestinationPath =
resourcesDestinationPath.resolve(variantDirectory.getFileName());
stepsBuilder.add(
MkdirStep.of(
BuildCellRelativePath.fromCellRelativePath(
context.getBuildCellRootPath(),
getProjectFilesystem(),
bundleVariantDestinationPath)));
Path destinationPath = bundleVariantDestinationPath.resolve(variantFilePath.getFileName());
addResourceProcessingSteps(
context.getSourcePathResolver(), variantFilePath, destinationPath, stepsBuilder);
}
if (!frameworks.isEmpty()) {
Path frameworksDestinationPath = bundleRoot.resolve(this.destinations.getFrameworksPath());
stepsBuilder.add(
MkdirStep.of(
BuildCellRelativePath.fromCellRelativePath(
context.getBuildCellRootPath(),
getProjectFilesystem(),
frameworksDestinationPath)));
for (SourcePath framework : frameworks) {
Path srcPath = context.getSourcePathResolver().getAbsolutePath(framework);
stepsBuilder.add(
CopyStep.forDirectory(
getProjectFilesystem(),
srcPath,
frameworksDestinationPath,
CopyStep.DirectoryMode.DIRECTORY_AND_CONTENTS));
codeSignOnCopyPathsBuilder.add(frameworksDestinationPath.resolve(srcPath.getFileName()));
}
}
if (needCodeSign()) {
Optional<Path> signingEntitlementsTempPath;
Supplier<CodeSignIdentity> codeSignIdentitySupplier;
if (adHocCodeSignIsSufficient()) {
signingEntitlementsTempPath = Optional.empty();
CodeSignIdentity identity =
codesignIdentitySubjectName
.map(id -> CodeSignIdentity.ofAdhocSignedWithSubjectCommonName(id))
.orElse(CodeSignIdentity.AD_HOC);
codeSignIdentitySupplier = () -> identity;
} else {
// Copy the .mobileprovision file if the platform requires it, and sign the executable.
Optional<Path> entitlementsPlist = Optional.empty();
// Try to use the entitlements file specified in the bundle's binary first.
entitlementsPlist =
entitlementsFile.map(p -> context.getSourcePathResolver().getAbsolutePath(p));
// Fall back to getting CODE_SIGN_ENTITLEMENTS from info_plist_substitutions.
if (!entitlementsPlist.isPresent()) {
Path srcRoot =
getProjectFilesystem().getRootPath().resolve(getBuildTarget().getBasePath());
Optional<String> entitlementsPlistString =
InfoPlistSubstitution.getVariableExpansionForPlatform(
CODE_SIGN_ENTITLEMENTS,
platform.getName(),
withDefaults(
infoPlistSubstitutions,
ImmutableMap.of(
"SOURCE_ROOT", srcRoot.toString(),
"SRCROOT", srcRoot.toString())));
entitlementsPlist =
entitlementsPlistString.map(
entitlementsPlistName -> {
ProjectFilesystem filesystem = getProjectFilesystem();
Path originalEntitlementsPlist =
srcRoot.resolve(Paths.get(entitlementsPlistName));
Path entitlementsPlistWithSubstitutions =
BuildTargetPaths.getScratchPath(
filesystem, getBuildTarget(), "%s-Entitlements.plist");
stepsBuilder.add(
new FindAndReplaceStep(
filesystem,
originalEntitlementsPlist,
entitlementsPlistWithSubstitutions,
InfoPlistSubstitution.createVariableExpansionFunction(
infoPlistSubstitutions)));
return filesystem.resolve(entitlementsPlistWithSubstitutions);
});
}
signingEntitlementsTempPath =
Optional.of(
BuildTargetPaths.getScratchPath(
getProjectFilesystem(), getBuildTarget(), "%s.xcent"));
Path dryRunResultPath = bundleRoot.resolve(PP_DRY_RUN_RESULT_FILE);
ProvisioningProfileCopyStep provisioningProfileCopyStep =
new ProvisioningProfileCopyStep(
getProjectFilesystem(),
infoPlistOutputPath,
platform,
Optional.empty(), // Provisioning profile UUID -- find automatically.
entitlementsPlist,
provisioningProfileStore,
resourcesDestinationPath.resolve("embedded.mobileprovision"),
dryRunCodeSigning
? bundleRoot.resolve(CODE_SIGN_DRY_RUN_ENTITLEMENTS_FILE)
: signingEntitlementsTempPath.get(),
codeSignIdentitiesSupplier,
dryRunCodeSigning ? Optional.of(dryRunResultPath) : Optional.empty());
stepsBuilder.add(provisioningProfileCopyStep);
codeSignIdentitySupplier =
() -> {
// Using getUnchecked here because the previous step should already throw if exception
// occurred, and this supplier would never be evaluated.
Optional<ProvisioningProfileMetadata> selectedProfile =
Futures.getUnchecked(
provisioningProfileCopyStep.getSelectedProvisioningProfileFuture());
if (!selectedProfile.isPresent()) {
// This should only happen in dry-run codesign mode (since otherwise an exception
// would have been thrown already.) Still, we need to return *something*.
Preconditions.checkState(dryRunCodeSigning);
return CodeSignIdentity.AD_HOC;
}
ImmutableSet<HashCode> fingerprints =
selectedProfile.get().getDeveloperCertificateFingerprints();
if (fingerprints.isEmpty()) {
// No constraints, pick an arbitrary identity.
// If no identities are available, use an ad-hoc identity.
return Iterables.getFirst(
codeSignIdentitiesSupplier.get(), CodeSignIdentity.AD_HOC);
}
for (CodeSignIdentity identity : codeSignIdentitiesSupplier.get()) {
if (identity.getFingerprint().isPresent()
&& fingerprints.contains(identity.getFingerprint().get())) {
return identity;
}
}
throw new HumanReadableException(
"No code sign identity available for provisioning profile: %s\n"
+ "Profile requires an identity with one of the following SHA1 fingerprints "
+ "available in your keychain: \n %s",
selectedProfile.get().getProfilePath(), Joiner.on("\n ").join(fingerprints));
};
}
addSwiftStdlibStepIfNeeded(
context.getSourcePathResolver(),
bundleRoot.resolve(destinations.getFrameworksPath()),
dryRunCodeSigning ? Optional.empty() : Optional.of(codeSignIdentitySupplier),
stepsBuilder,
false /* is for packaging? */);
for (BuildRule extraBinary : extraBinaries) {
Path outputPath = getBundleBinaryPathForBuildRule(extraBinary);
codeSignOnCopyPathsBuilder.add(outputPath);
}
for (Path codeSignOnCopyPath : codeSignOnCopyPathsBuilder.build()) {
stepsBuilder.add(
new CodeSignStep(
getProjectFilesystem(),
context.getSourcePathResolver(),
codeSignOnCopyPath,
Optional.empty(),
codeSignIdentitySupplier,
codesign,
codesignAllocatePath,
dryRunCodeSigning
? Optional.of(codeSignOnCopyPath.resolve(CODE_SIGN_DRY_RUN_ARGS_FILE))
: Optional.empty(),
codesignFlags,
codesignTimeout));
}
stepsBuilder.add(
new CodeSignStep(
getProjectFilesystem(),
context.getSourcePathResolver(),
bundleRoot,
signingEntitlementsTempPath,
codeSignIdentitySupplier,
codesign,
codesignAllocatePath,
dryRunCodeSigning
? Optional.of(bundleRoot.resolve(CODE_SIGN_DRY_RUN_ARGS_FILE))
: Optional.empty(),
codesignFlags,
codesignTimeout));
} else {
addSwiftStdlibStepIfNeeded(
context.getSourcePathResolver(),
bundleRoot.resolve(destinations.getFrameworksPath()),
Optional.empty(),
stepsBuilder,
false /* is for packaging? */);
}
// Ensure the bundle directory is archived so we can fetch it later.
buildableContext.recordArtifact(
context.getSourcePathResolver().getRelativePath(getSourcePathToOutput()));
return stepsBuilder.build();
}
private void verifyResourceConflicts(
AppleBundleResources resources, SourcePathResolver resolver) {
// Ensure there are no resources that will overwrite each other
// TODO: handle ResourceDirsContainingResourceDirs
Set<Path> resourcePaths = new HashSet<>();
for (SourcePath path :
Iterables.concat(resources.getResourceDirs(), resources.getResourceFiles())) {
Path pathInBundle = resolver.getRelativePath(path).getFileName();
if (resourcePaths.contains(pathInBundle)) {
throw new HumanReadableException(
"Bundle contains multiple resources with path %s", pathInBundle);
} else {
resourcePaths.add(pathInBundle);
}
}
}
private boolean needsPkgInfoFile() {
return !(extension.equals(AppleBundleExtension.XPC.toFileExtension())
|| extension.equals(AppleBundleExtension.QLGENERATOR.toFileExtension()));
}
private void appendCopyBinarySteps(
ImmutableList.Builder<Step> stepsBuilder, BuildContext context) {
Preconditions.checkArgument(hasBinary);
Path binaryOutputPath =
context
.getSourcePathResolver()
.getAbsolutePath(Objects.requireNonNull(binary.get().getSourcePathToOutput()));
ImmutableMap.Builder<Path, Path> binariesBuilder = ImmutableMap.builder();
binariesBuilder.put(bundleBinaryPath, binaryOutputPath);
for (BuildRule extraBinary : extraBinaries) {
Path outputPath =
context.getSourcePathResolver().getRelativePath(extraBinary.getSourcePathToOutput());
Path bundlePath = getBundleBinaryPathForBuildRule(extraBinary);
binariesBuilder.put(bundlePath, outputPath);
}
copyBinariesIntoBundle(stepsBuilder, context, binariesBuilder.build());
copyAnotherCopyOfWatchKitStub(stepsBuilder, context, binaryOutputPath);
}
private Path getBundleBinaryPathForBuildRule(BuildRule buildRule) {
BuildTarget unflavoredTarget = buildRule.getBuildTarget().withFlavors();
String binaryName = getBinaryName(unflavoredTarget, Optional.empty());
Path pathRelativeToBundleRoot = destinations.getExecutablesPath().resolve(binaryName);
return bundleRoot.resolve(pathRelativeToBundleRoot);
}
/**
* @param binariesMap A map from destination to source. Destination is deliberately used as a key
* prevent multiple sources overwriting the same destination.
*/
private void copyBinariesIntoBundle(
ImmutableList.Builder<Step> stepsBuilder,
BuildContext context,
ImmutableMap<Path, Path> binariesMap) {
stepsBuilder.add(
MkdirStep.of(
BuildCellRelativePath.fromCellRelativePath(
context.getBuildCellRootPath(),
getProjectFilesystem(),
bundleRoot.resolve(this.destinations.getExecutablesPath()))));
binariesMap.forEach(
(binaryBundlePath, binaryOutputPath) -> {
stepsBuilder.add(
CopyStep.forFile(getProjectFilesystem(), binaryOutputPath, binaryBundlePath));
});
}
private void copyAnotherCopyOfWatchKitStub(
ImmutableList.Builder<Step> stepsBuilder, BuildContext context, Path binaryOutputPath) {
if ((isLegacyWatchApp() || platform.getName().contains("watch"))
&& binary.get() instanceof WriteFile) {
Path watchKitStubDir = bundleRoot.resolve("_WatchKitStub");
stepsBuilder.add(
MkdirStep.of(
BuildCellRelativePath.fromCellRelativePath(
context.getBuildCellRootPath(), getProjectFilesystem(), watchKitStubDir)),
CopyStep.forFile(
getProjectFilesystem(), binaryOutputPath, watchKitStubDir.resolve("WK")));
}
}
private void appendCopyDsymStep(
ImmutableList.Builder<Step> stepsBuilder,
BuildableContext buildableContext,
BuildContext buildContext) {
if (appleDsym.isPresent()) {
stepsBuilder.add(
CopyStep.forDirectory(
getProjectFilesystem(),
buildContext
.getSourcePathResolver()
.getAbsolutePath(appleDsym.get().getSourcePathToOutput()),
bundleRoot.getParent(),
CopyStep.DirectoryMode.DIRECTORY_AND_CONTENTS));
appendDsymRenameStepToMatchBundleName(stepsBuilder, buildableContext, buildContext);
}
}
private void appendDsymRenameStepToMatchBundleName(
ImmutableList.Builder<Step> stepsBuilder,
BuildableContext buildableContext,
BuildContext buildContext) {
Preconditions.checkArgument(hasBinary && appleDsym.isPresent());
// rename dSYM bundle to match bundle name
Path dsymPath =
buildContext
.getSourcePathResolver()
.getRelativePath(appleDsym.get().getSourcePathToOutput());
Path dsymSourcePath = bundleRoot.getParent().resolve(dsymPath.getFileName());
Path dsymDestinationPath =
bundleRoot
.getParent()
.resolve(bundleRoot.getFileName() + "." + AppleBundleExtension.DSYM.toFileExtension());
stepsBuilder.add(
RmStep.of(
BuildCellRelativePath.fromCellRelativePath(
buildContext.getBuildCellRootPath(),
getProjectFilesystem(),
dsymDestinationPath))
.withRecursive(true));
stepsBuilder.add(new MoveStep(getProjectFilesystem(), dsymSourcePath, dsymDestinationPath));
String dwarfFilename =
AppleDsym.getDwarfFilenameForDsymTarget(appleDsym.get().getBuildTarget());
// rename DWARF file inside dSYM bundle to match bundle name
Path dwarfFolder = dsymDestinationPath.resolve(AppleDsym.DSYM_DWARF_FILE_FOLDER);
Path dwarfSourcePath = dwarfFolder.resolve(dwarfFilename);
Path dwarfDestinationPath = dwarfFolder.resolve(MorePaths.getNameWithoutExtension(bundleRoot));
stepsBuilder.add(new MoveStep(getProjectFilesystem(), dwarfSourcePath, dwarfDestinationPath));
// record dSYM so we can fetch it from cache
buildableContext.recordArtifact(dsymDestinationPath);
}
private void addStepsToCopyExtensionBundlesDependencies(
BuildContext context,
ImmutableList.Builder<Step> stepsBuilder,
ImmutableList.Builder<Path> codeSignOnCopyPathsBuilder) {
for (Map.Entry<SourcePath, String> entry : extensionBundlePaths.entrySet()) {
Path srcPath = context.getSourcePathResolver().getAbsolutePath(entry.getKey());
Path destPath = bundleRoot.resolve(entry.getValue());
stepsBuilder.add(
MkdirStep.of(
BuildCellRelativePath.fromCellRelativePath(
context.getBuildCellRootPath(), getProjectFilesystem(), destPath)));
stepsBuilder.add(
CopyStep.forDirectory(
getProjectFilesystem(),
srcPath,
destPath,
CopyStep.DirectoryMode.DIRECTORY_AND_CONTENTS));
if (srcPath.toString().endsWith("." + FRAMEWORK_EXTENSION)) {
codeSignOnCopyPathsBuilder.add(destPath.resolve(srcPath.getFileName()));
}
}
}
public static ImmutableMap<String, String> withDefaults(
ImmutableMap<String, String> map, ImmutableMap<String, String> defaults) {
ImmutableMap.Builder<String, String> builder =
ImmutableMap.<String, String>builder().putAll(map);
for (ImmutableMap.Entry<String, String> entry : defaults.entrySet()) {
if (!map.containsKey(entry.getKey())) {
builder = builder.put(entry.getKey(), entry.getValue());
}
}
return builder.build();
}
private boolean needsLSRequiresIPhoneOSInfoPlistKeyOnMac() {
return !extension.equals(AppleBundleExtension.XPC.toFileExtension());
}
private ImmutableMap<String, NSObject> getInfoPlistOverrideKeys() {
ImmutableMap.Builder<String, NSObject> keys = ImmutableMap.builder();
if (platform.getType() == ApplePlatformType.MAC) {
if (needsLSRequiresIPhoneOSInfoPlistKeyOnMac()) {
keys.put("LSRequiresIPhoneOS", new NSNumber(false));
}
} else if (!platform.getType().isWatch() && !isLegacyWatchApp()) {
keys.put("LSRequiresIPhoneOS", new NSNumber(true));
}
return keys.build();
}
private boolean needsAppInfoPlistKeysOnMac() {
// XPC bundles on macOS don't require app-specific keys
// (which also confuses Finder in displaying the XPC bundles as apps)
return !extension.equals(AppleBundleExtension.XPC.toFileExtension());
}
private ImmutableMap<String, NSObject> getInfoPlistAdditionalKeys() {
ImmutableMap.Builder<String, NSObject> keys = ImmutableMap.builder();
switch (platform.getType()) {
case MAC:
if (needsAppInfoPlistKeysOnMac()) {
keys.put("NSHighResolutionCapable", new NSNumber(true));
keys.put("NSSupportsAutomaticGraphicsSwitching", new NSNumber(true));
}
keys.put("CFBundleSupportedPlatforms", new NSArray(new NSString("MacOSX")));
break;
case IOS_DEVICE:
keys.put("CFBundleSupportedPlatforms", new NSArray(new NSString("iPhoneOS")));
break;
case IOS_SIMULATOR:
keys.put("CFBundleSupportedPlatforms", new NSArray(new NSString("iPhoneSimulator")));
break;
case WATCH_DEVICE:
if (!isLegacyWatchApp()) {
keys.put("CFBundleSupportedPlatforms", new NSArray(new NSString("WatchOS")));
}
break;
case WATCH_SIMULATOR:
if (!isLegacyWatchApp()) {
keys.put("CFBundleSupportedPlatforms", new NSArray(new NSString("WatchSimulator")));
}
break;
case TV_DEVICE:
case TV_SIMULATOR:
case UNKNOWN:
break;
}
keys.put("DTPlatformName", new NSString(platform.getName()));
keys.put("DTPlatformVersion", new NSString(sdkVersion));
keys.put("DTSDKName", new NSString(sdkName + sdkVersion));
keys.put("MinimumOSVersion", new NSString(minOSVersion));
if (platformBuildVersion.isPresent()) {
keys.put("DTPlatformBuild", new NSString(platformBuildVersion.get()));
keys.put("DTSDKBuild", new NSString(platformBuildVersion.get()));
}
if (xcodeBuildVersion.isPresent()) {
keys.put("DTXcodeBuild", new NSString(xcodeBuildVersion.get()));
}
if (xcodeVersion.isPresent()) {
keys.put("DTXcode", new NSString(xcodeVersion.get()));
}
return keys.build();
}
public void addSwiftStdlibStepIfNeeded(
SourcePathResolver resolver,
Path destinationPath,
Optional<Supplier<CodeSignIdentity>> codeSignIdentitySupplier,
ImmutableList.Builder<Step> stepsBuilder,
boolean isForPackaging) {
// It's apparently safe to run this even on a non-swift bundle (in that case, no libs
// are copied over).
boolean shouldCopySwiftStdlib =
!extension.equals(AppleBundleExtension.APPEX.toFileExtension())
&& (!extension.equals(AppleBundleExtension.FRAMEWORK.toFileExtension())
|| copySwiftStdlibToFrameworks);
if (swiftStdlibTool.isPresent() && shouldCopySwiftStdlib) {
String tempDirPattern = isForPackaging ? "__swift_packaging_temp__%s" : "__swift_temp__%s";
stepsBuilder.add(
new SwiftStdlibStep(
getProjectFilesystem().getRootPath(),
BuildTargetPaths.getScratchPath(
getProjectFilesystem(), getBuildTarget(), tempDirPattern),
this.sdkPath,
destinationPath,
swiftStdlibTool.get().getCommandPrefix(resolver),
lipo.getCommandPrefix(resolver),
bundleBinaryPath,
ImmutableSet.of(destinations.getFrameworksPath(), destinations.getPlugInsPath()),
codeSignIdentitySupplier));
}
}
private void addStoryboardProcessingSteps(
SourcePathResolver resolver,
Path sourcePath,
Path destinationPath,
ImmutableList.Builder<Step> stepsBuilder) {
ImmutableList<String> modifiedFlags =
ImmutableList.<String>builder().addAll(BASE_IBTOOL_FLAGS).addAll(ibtoolFlags).build();
if (platform.getName().contains("watch") || isLegacyWatchApp()) {
LOG.debug(
"Compiling storyboard %s to storyboardc %s and linking", sourcePath, destinationPath);
Path compiledStoryboardPath =
BuildTargetPaths.getScratchPath(
getProjectFilesystem(), getBuildTarget(), "%s.storyboardc");
stepsBuilder.add(
new IbtoolStep(
getProjectFilesystem(),
ibtool.getEnvironment(resolver),
ibtool.getCommandPrefix(resolver),
ibtoolModuleFlag ? Optional.of(binaryName) : Optional.empty(),
ImmutableList.<String>builder()
.addAll(modifiedFlags)
.add("--target-device", "watch", "--compile")
.build(),
sourcePath,
compiledStoryboardPath));
stepsBuilder.add(
new IbtoolStep(
getProjectFilesystem(),
ibtool.getEnvironment(resolver),
ibtool.getCommandPrefix(resolver),
ibtoolModuleFlag ? Optional.of(binaryName) : Optional.empty(),
ImmutableList.<String>builder()
.addAll(modifiedFlags)
.add("--target-device", "watch", "--link")
.build(),
compiledStoryboardPath,
destinationPath.getParent()));
} else {
LOG.debug("Compiling storyboard %s to storyboardc %s", sourcePath, destinationPath);
String compiledStoryboardFilename =
Files.getNameWithoutExtension(destinationPath.toString()) + ".storyboardc";
Path compiledStoryboardPath = destinationPath.getParent().resolve(compiledStoryboardFilename);
stepsBuilder.add(
new IbtoolStep(
getProjectFilesystem(),
ibtool.getEnvironment(resolver),
ibtool.getCommandPrefix(resolver),
ibtoolModuleFlag ? Optional.of(binaryName) : Optional.empty(),
ImmutableList.<String>builder().addAll(modifiedFlags).add("--compile").build(),
sourcePath,
compiledStoryboardPath));
}
}
private void addResourceProcessingSteps(
SourcePathResolver resolver,
Path sourcePath,
Path destinationPath,
ImmutableList.Builder<Step> stepsBuilder) {
String sourcePathExtension =
Files.getFileExtension(sourcePath.toString()).toLowerCase(Locale.US);
switch (sourcePathExtension) {
case "plist":
case "stringsdict":
LOG.debug("Converting plist %s to binary plist %s", sourcePath, destinationPath);
stepsBuilder.add(
new PlistProcessStep(
getProjectFilesystem(),
sourcePath,
Optional.empty(),
destinationPath,
ImmutableMap.of(),
ImmutableMap.of(),
PlistProcessStep.OutputFormat.BINARY));
break;
case "storyboard":
addStoryboardProcessingSteps(resolver, sourcePath, destinationPath, stepsBuilder);
break;
case "xib":
String compiledNibFilename =
Files.getNameWithoutExtension(destinationPath.toString()) + ".nib";
Path compiledNibPath = destinationPath.getParent().resolve(compiledNibFilename);
LOG.debug("Compiling XIB %s to NIB %s", sourcePath, destinationPath);
stepsBuilder.add(
new IbtoolStep(
getProjectFilesystem(),
ibtool.getEnvironment(resolver),
ibtool.getCommandPrefix(resolver),
ibtoolModuleFlag ? Optional.of(binaryName) : Optional.empty(),
ImmutableList.<String>builder()
.addAll(BASE_IBTOOL_FLAGS)
.addAll(ibtoolFlags)
.addAll(ImmutableList.of("--compile"))
.build(),
sourcePath,
compiledNibPath));
break;
default:
stepsBuilder.add(CopyStep.forFile(getProjectFilesystem(), sourcePath, destinationPath));
break;
}
}
@Override
public boolean isTestedBy(BuildTarget testRule) {
if (tests.contains(testRule)) {
return true;
}
if (binary.isPresent()) {
BuildRule binaryRule = binary.get();
if (binaryRule instanceof NativeTestable) {
return ((NativeTestable) binaryRule).isTestedBy(testRule);
}
}
return false;
}
@Override
public CxxPreprocessorInput getPrivateCxxPreprocessorInput(
CxxPlatform cxxPlatform, ActionGraphBuilder graphBuilder) {
if (binary.isPresent()) {
BuildRule binaryRule = binary.get();
if (binaryRule instanceof NativeTestable) {
return ((NativeTestable) binaryRule)
.getPrivateCxxPreprocessorInput(cxxPlatform, graphBuilder);
}
}
return CxxPreprocessorInput.of();
}
private boolean adHocCodeSignIsSufficient() {
return ApplePlatform.adHocCodeSignIsSufficient(platform.getName());
}
// .framework bundles will be code-signed when they're copied into the containing bundle.
private boolean needCodeSign() {
return binary.isPresent()
&& ApplePlatform.needsCodeSign(platform.getName())
&& !extension.equals(FRAMEWORK_EXTENSION);
}
@Override
public BuildRule getBinaryBuildRule() {
return binary.get();
}
@Override
public Stream<BuildTarget> getRuntimeDeps(SourcePathRuleFinder ruleFinder) {
// When "running" an app bundle, ensure debug symbols are available.
if (binary.get() instanceof HasAppleDebugSymbolDeps) {
List<BuildRule> symbolDeps =
((HasAppleDebugSymbolDeps) binary.get())
.getAppleDebugSymbolDeps()
.collect(Collectors.toList());
if (!symbolDeps.isEmpty()) {
return Stream.concat(Stream.of(binary.get()), symbolDeps.stream())
.map(BuildRule::getBuildTarget);
}
}
return Stream.empty();
}
@Override
public boolean isCacheable() {
return cacheable;
}
@Override
public Tool getExecutableCommand() {
return new CommandTool.Builder()
.addArg(SourcePathArg.of(PathSourcePath.of(getProjectFilesystem(), bundleBinaryPath)))
.build();
}
}
| romanoid/buck | src/com/facebook/buck/apple/AppleBundle.java | Java | apache-2.0 | 47,888 |
/*
* Copyright 2017 GcsSloop
*
* 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.
*
* Last modified 2017-04-09 20:45:09
*
* GitHub: https://github.com/GcsSloop
* Website: http://www.gcssloop.com
* Weibo: http://weibo.com/GcsSloop
*/
package com.gcssloop.diycode.fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import com.gcssloop.diycode.fragment.base.SimpleRefreshRecyclerFragment;
import com.gcssloop.diycode.fragment.provider.TopicProvider;
import com.gcssloop.diycode_sdk.api.topic.bean.Topic;
import com.gcssloop.diycode_sdk.api.user.event.GetUserCollectionTopicListEvent;
import com.gcssloop.recyclerview.adapter.multitype.HeaderFooterAdapter;
/**
* 用户收藏的 topic 列表
*/
public class UserCollectionTopicFragment extends SimpleRefreshRecyclerFragment<Topic,
GetUserCollectionTopicListEvent> {
private static String Key_User_Login_Name = "Key_User_Login_Name";
private String loginName;
public static UserCollectionTopicFragment newInstance(String user_login_name) {
Bundle args = new Bundle();
args.putString(Key_User_Login_Name, user_login_name);
UserCollectionTopicFragment fragment = new UserCollectionTopicFragment();
fragment.setArguments(args);
return fragment;
}
@Override public void initData(HeaderFooterAdapter adapter) {
Bundle args = getArguments();
loginName = args.getString(Key_User_Login_Name);
loadMore();
}
@Override
protected void setAdapterRegister(Context context, RecyclerView recyclerView,
HeaderFooterAdapter adapter) {
adapter.register(Topic.class, new TopicProvider(context));
}
@NonNull @Override protected String request(int offset, int limit) {
return mDiycode.getUserCollectionTopicList(loginName, offset, limit);
}
}
| GcsSloop/diycode | diycode-app/src/main/java/com/gcssloop/diycode/fragment/UserCollectionTopicFragment.java | Java | apache-2.0 | 2,469 |
/*
* Copyright 2014 Leonardo Rossetto
*
* 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.leonardoxh.masks;
import android.widget.EditText;
/**
* Default input mask this will change the <code>#</code> char to an number
* but this class also handle the two possible brazilian masks, for Sao Paulo
* that have a 9 number first and for other countrys
* @see com.github.leonardoxh.masks.Masks
* @author Leonardo Rossetto
*/
public class BrazilPhoneMask extends InputMask {
public BrazilPhoneMask(EditText editText) {
super(editText, Masks.DEFAULT_BRAZIL_MASK);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.toString().startsWith("(11)")) {
mMask = Masks.DEFAULT_SAO_PAULO_MASK;
} else {
mMask = Masks.DEFAULT_BRAZIL_MASK;
}
super.onTextChanged(s, start, before, count);
}
}
| leonardoxh/Masks | library/library/src/main/java/com/github/leonardoxh/masks/BrazilPhoneMask.java | Java | apache-2.0 | 1,440 |
/* Generic definitions */
/* Assertions (useful to generate conditional code) */
/* Current type and class (and size, if applicable) */
/* Value methods */
/* Interfaces (keys) */
/* Interfaces (values) */
/* Abstract implementations (keys) */
/* Abstract implementations (values) */
/* Static containers (keys) */
/* Static containers (values) */
/* Implementations */
/* Synchronized wrappers */
/* Unmodifiable wrappers */
/* Other wrappers */
/* Methods (keys) */
/* Methods (values) */
/* Methods (keys/values) */
/* Methods that have special names depending on keys (but the special names depend on values) */
/* Equality */
/* Object/Reference-only definitions (keys) */
/* Primitive-type-only definitions (keys) */
/* Object/Reference-only definitions (values) */
/*
* Copyright (C) 2002-2015 Sebastiano Vigna
*
* 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.
*
*
*
* For the sorting and binary search code:
*
* Copyright (C) 1999 CERN - European Organization for Nuclear Research.
*
* Permission to use, copy, modify, distribute and sell this software and
* its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and that
* both that copyright notice and this permission notice appear in
* supporting documentation. CERN makes no representations about the
* suitability of this software for any purpose. It is provided "as is"
* without expressed or implied warranty.
*/
package vigna.fastutil.bytes;
import vigna.fastutil.Arrays;
import vigna.fastutil.Hash;
import vigna.fastutil.ints.IntArrays;
import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
/** A class providing static methods and objects that do useful things with type-specific arrays.
*
* <p>In particular, the <code>ensureCapacity()</code>, <code>grow()</code>, <code>trim()</code> and <code>setLength()</code> methods allow to handle arrays much like array lists. This can be very
* useful when efficiency (or syntactic simplicity) reasons make array lists unsuitable.
*
* <P>Note that {@link it.unimi.dsi.fastutil.io.BinIO} and {@link it.unimi.dsi.fastutil.io.TextIO} contain several methods make it possible to load and save arrays of primitive types as sequences of
* elements in {@link java.io.DataInput} format (i.e., not as objects) or as sequences of lines of text.
*
* <h2>Sorting</h2>
*
* <p>There are several sorting methods available. The main theme is that of letting you choose the sorting algorithm you prefer (i.e., trading stability of mergesort for no memory allocation in
* quicksort). Several algorithms provide a parallel version, that will use the {@linkplain Runtime#availableProcessors() number of cores available}. Some algorithms also provide an explicit
* <em>indirect</em> sorting facility, which makes it possible to sort an array using the values in another array as comparator.
*
* <p>All comparison-based algorithm have an implementation based on a type-specific comparator.
*
* <p>As a general rule, sequential radix sort is significantly faster than quicksort or mergesort, in particular on random-looking data. In the parallel case, up to a few cores parallel radix sort is
* still the fastest, but at some point quicksort exploits parallelism better.
*
* <p>If you are fine with not knowing exactly which algorithm will be run (in particular, not knowing exactly whether a support array will be allocated), the dual-pivot parallel sorts in
* {@link java.util.Arrays} are about 50% faster than the classical single-pivot implementation used here.
*
* <p>In any case, if sorting time is important I suggest that you benchmark your sorting load with your data distribution and on your architecture.
*
* @see java.util.Arrays */
public class ByteArrays {
private ByteArrays() {}
/** A static, final, empty array. */
public final static byte[] EMPTY_ARRAY = {};
/** Ensures that an array can contain the given number of entries.
*
* <P>If you cannot foresee whether this array will need again to be enlarged, you should probably use <code>grow()</code> instead.
*
* @param array an array.
* @param length the new minimum length for this array.
* @return <code>array</code>, if it contains <code>length</code> entries or more; otherwise, an array with <code>length</code> entries whose first <code>array.length</code> entries are the same
* as those of <code>array</code>. */
public static byte[] ensureCapacity( final byte[] array, final int length ) {
if ( length > array.length ) {
final byte t[] =
new byte[ length ];
System.arraycopy( array, 0, t, 0, array.length );
return t;
}
return array;
}
/** Ensures that an array can contain the given number of entries, preserving just a part of the array.
*
* @param array an array.
* @param length the new minimum length for this array.
* @param preserve the number of elements of the array that must be preserved in case a new allocation is necessary.
* @return <code>array</code>, if it can contain <code>length</code> entries or more; otherwise, an array with <code>length</code> entries whose first <code>preserve</code> entries are the same as
* those of <code>array</code>. */
public static byte[] ensureCapacity( final byte[] array, final int length, final int preserve ) {
if ( length > array.length ) {
final byte t[] =
new byte[ length ];
System.arraycopy( array, 0, t, 0, preserve );
return t;
}
return array;
}
/** Grows the given array to the maximum between the given length and the current length multiplied by two, provided that the given length is larger than the current length.
*
* <P>If you want complete control on the array growth, you should probably use <code>ensureCapacity()</code> instead.
*
* @param array an array.
* @param length the new minimum length for this array.
* @return <code>array</code>, if it can contain <code>length</code> entries; otherwise, an array with max(<code>length</code>,<code>array.length</code>/φ) entries whose first
* <code>array.length</code> entries are the same as those of <code>array</code>. */
public static byte[] grow( final byte[] array, final int length ) {
if ( length > array.length ) {
final int newLength = (int) Math.max( Math.min( 2L * array.length, Arrays.MAX_ARRAY_SIZE ), length );
final byte t[] =
new byte[ newLength ];
System.arraycopy( array, 0, t, 0, array.length );
return t;
}
return array;
}
/** Grows the given array to the maximum between the given length and the current length multiplied by two, provided that the given length is larger than the current length, preserving just a part
* of the array.
*
* <P>If you want complete control on the array growth, you should probably use <code>ensureCapacity()</code> instead.
*
* @param array an array.
* @param length the new minimum length for this array.
* @param preserve the number of elements of the array that must be preserved in case a new allocation is necessary.
* @return <code>array</code>, if it can contain <code>length</code> entries; otherwise, an array with max(<code>length</code>,<code>array.length</code>/φ) entries whose first
* <code>preserve</code> entries are the same as those of <code>array</code>. */
public static byte[] grow( final byte[] array, final int length, final int preserve ) {
if ( length > array.length ) {
final int newLength = (int) Math.max( Math.min( 2L * array.length, Arrays.MAX_ARRAY_SIZE ), length );
final byte t[] =
new byte[ newLength ];
System.arraycopy( array, 0, t, 0, preserve );
return t;
}
return array;
}
/** Trims the given array to the given length.
*
* @param array an array.
* @param length the new maximum length for the array.
* @return <code>array</code>, if it contains <code>length</code> entries or less; otherwise, an array with <code>length</code> entries whose entries are the same as the first <code>length</code>
* entries of <code>array</code>. */
public static byte[] trim( final byte[] array, final int length ) {
if ( length >= array.length ) return array;
final byte t[] =
length == 0 ? EMPTY_ARRAY : new byte[ length ];
System.arraycopy( array, 0, t, 0, length );
return t;
}
/** Sets the length of the given array.
*
* @param array an array.
* @param length the new length for the array.
* @return <code>array</code>, if it contains exactly <code>length</code> entries; otherwise, if it contains <em>more</em> than <code>length</code> entries, an array with <code>length</code>
* entries whose entries are the same as the first <code>length</code> entries of <code>array</code>; otherwise, an array with <code>length</code> entries whose first <code>array.length</code>
* entries are the same as those of <code>array</code>. */
public static byte[] setLength( final byte[] array, final int length ) {
if ( length == array.length ) return array;
if ( length < array.length ) return trim( array, length );
return ensureCapacity( array, length );
}
/** Returns a copy of a portion of an array.
*
* @param array an array.
* @param offset the first element to copy.
* @param length the number of elements to copy.
* @return a new array containing <code>length</code> elements of <code>array</code> starting at <code>offset</code>. */
public static byte[] copy( final byte[] array, final int offset, final int length ) {
ensureOffsetLength( array, offset, length );
final byte[] a =
length == 0 ? EMPTY_ARRAY : new byte[ length ];
System.arraycopy( array, offset, a, 0, length );
return a;
}
/** Returns a copy of an array.
*
* @param array an array.
* @return a copy of <code>array</code>. */
public static byte[] copy( final byte[] array ) {
return array.clone();
}
/** Fills the given array with the given value.
*
* @param array an array.
* @param value the new value for all elements of the array.
* @deprecated Please use the corresponding {@link java.util.Arrays} method. */
@Deprecated
public static void fill( final byte[] array, final byte value ) {
int i = array.length;
while ( i-- != 0 )
array[ i ] = value;
}
/** Fills a portion of the given array with the given value.
*
* @param array an array.
* @param from the starting index of the portion to fill (inclusive).
* @param to the end index of the portion to fill (exclusive).
* @param value the new value for all elements of the specified portion of the array.
* @deprecated Please use the corresponding {@link java.util.Arrays} method. */
@Deprecated
public static void fill( final byte[] array, final int from, int to, final byte value ) {
ensureFromTo( array, from, to );
if ( from == 0 ) while ( to-- != 0 )
array[ to ] = value;
else for ( int i = from; i < to; i++ )
array[ i ] = value;
}
/** Returns true if the two arrays are elementwise equal.
*
* @param a1 an array.
* @param a2 another array.
* @return true if the two arrays are of the same length, and their elements are equal.
* @deprecated Please use the corresponding {@link java.util.Arrays} method, which is intrinsified in recent JVMs. */
@Deprecated
public static boolean equals( final byte[] a1, final byte a2[] ) {
int i = a1.length;
if ( i != a2.length ) return false;
while ( i-- != 0 )
if ( !( ( a1[ i ] ) == ( a2[ i ] ) ) ) return false;
return true;
}
/** Ensures that a range given by its first (inclusive) and last (exclusive) elements fits an array.
*
* <P>This method may be used whenever an array range check is needed.
*
* @param a an array.
* @param from a start index (inclusive).
* @param to an end index (exclusive).
* @throws IllegalArgumentException if <code>from</code> is greater than <code>to</code>.
* @throws ArrayIndexOutOfBoundsException if <code>from</code> or <code>to</code> are greater than the array length or negative. */
public static void ensureFromTo( final byte[] a, final int from, final int to ) {
Arrays.ensureFromTo( a.length, from, to );
}
/** Ensures that a range given by an offset and a length fits an array.
*
* <P>This method may be used whenever an array range check is needed.
*
* @param a an array.
* @param offset a start index.
* @param length a length (the number of elements in the range).
* @throws IllegalArgumentException if <code>length</code> is negative.
* @throws ArrayIndexOutOfBoundsException if <code>offset</code> is negative or <code>offset</code>+<code>length</code> is greater than the array length. */
public static void ensureOffsetLength( final byte[] a, final int offset, final int length ) {
Arrays.ensureOffsetLength( a.length, offset, length );
}
/** Ensures that two arrays are of the same length.
*
* @param a an array.
* @param b another array.
* @throws IllegalArgumentException if the two argument arrays are not of the same length. */
public static void ensureSameLength( final byte[] a, final byte[] b ) {
if ( a.length != b.length ) throw new IllegalArgumentException( "Array size mismatch: " + a.length + " != " + b.length );
}
private static final int QUICKSORT_NO_REC = 16;
private static final int PARALLEL_QUICKSORT_NO_FORK = 8192;
private static final int QUICKSORT_MEDIAN_OF_9 = 128;
private static final int MERGESORT_NO_REC = 16;
/** Swaps two elements of an anrray.
*
* @param x an array.
* @param a a position in {@code x}.
* @param b another position in {@code x}. */
public static void swap( final byte x[], final int a, final int b ) {
final byte t = x[ a ];
x[ a ] = x[ b ];
x[ b ] = t;
}
/** Swaps two sequences of elements of an array.
*
* @param x an array.
* @param a a position in {@code x}.
* @param b another position in {@code x}.
* @param n the number of elements to exchange starting at {@code a} and {@code b}. */
public static void swap( final byte[] x, int a, int b, final int n ) {
for ( int i = 0; i < n; i++, a++, b++ )
swap( x, a, b );
}
private static int med3( final byte x[], final int a, final int b, final int c, ByteComparator comp ) {
final int ab = comp.compare( x[ a ], x[ b ] );
final int ac = comp.compare( x[ a ], x[ c ] );
final int bc = comp.compare( x[ b ], x[ c ] );
return ( ab < 0 ?
( bc < 0 ? b : ac < 0 ? c : a ) :
( bc > 0 ? b : ac > 0 ? c : a ) );
}
private static void selectionSort( final byte[] a, final int from, final int to, final ByteComparator comp ) {
for ( int i = from; i < to - 1; i++ ) {
int m = i;
for ( int j = i + 1; j < to; j++ )
if ( comp.compare( a[ j ], a[ m ] ) < 0 ) m = j;
if ( m != i ) {
final byte u = a[ i ];
a[ i ] = a[ m ];
a[ m ] = u;
}
}
}
private static void insertionSort( final byte[] a, final int from, final int to, final ByteComparator comp ) {
for ( int i = from; ++i < to; ) {
byte t = a[ i ];
int j = i;
for ( byte u = a[ j - 1 ]; comp.compare( t, u ) < 0; u = a[ --j - 1 ] ) {
a[ j ] = u;
if ( from == j - 1 ) {
--j;
break;
}
}
a[ j ] = t;
}
}
/** Sorts the specified range of elements according to the order induced by the specified comparator using quicksort.
*
* <p>The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy, “Engineering a Sort Function”, <i>Software: Practice and Experience</i>, 23(11),
* pages 1249−1265, 1993.
*
* <p>Note that this implementation does not allocate any object, contrarily to the implementation used to sort primitive types in {@link java.util.Arrays}, which switches to mergesort on large
* inputs.
*
* @param x the array to be sorted.
* @param from the index of the first element (inclusive) to be sorted.
* @param to the index of the last element (exclusive) to be sorted.
* @param comp the comparator to determine the sorting order. */
public static void quickSort( final byte[] x, final int from, final int to, final ByteComparator comp ) {
final int len = to - from;
// Selection sort on smallest arrays
if ( len < QUICKSORT_NO_REC ) {
selectionSort( x, from, to, comp );
return;
}
// Choose a partition element, v
int m = from + len / 2;
int l = from;
int n = to - 1;
if ( len > QUICKSORT_MEDIAN_OF_9 ) { // Big arrays, pseudomedian of 9
int s = len / 8;
l = med3( x, l, l + s, l + 2 * s, comp );
m = med3( x, m - s, m, m + s, comp );
n = med3( x, n - 2 * s, n - s, n, comp );
}
m = med3( x, l, m, n, comp ); // Mid-size, med of 3
final byte v = x[ m ];
// Establish Invariant: v* (<v)* (>v)* v*
int a = from, b = a, c = to - 1, d = c;
while ( true ) {
int comparison;
while ( b <= c && ( comparison = comp.compare( x[ b ], v ) ) <= 0 ) {
if ( comparison == 0 ) swap( x, a++, b );
b++;
}
while ( c >= b && ( comparison = comp.compare( x[ c ], v ) ) >= 0 ) {
if ( comparison == 0 ) swap( x, c, d-- );
c--;
}
if ( b > c ) break;
swap( x, b++, c-- );
}
// Swap partition elements back to middle
int s;
s = Math.min( a - from, b - a );
swap( x, from, b - s, s );
s = Math.min( d - c, to - d - 1 );
swap( x, b, to - s, s );
// Recursively sort non-partition-elements
if ( ( s = b - a ) > 1 ) quickSort( x, from, from + s, comp );
if ( ( s = d - c ) > 1 ) quickSort( x, to - s, to, comp );
}
/** Sorts an array according to the order induced by the specified comparator using quicksort.
*
* <p>The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy, “Engineering a Sort Function”, <i>Software: Practice and Experience</i>, 23(11),
* pages 1249−1265, 1993.
*
* <p>Note that this implementation does not allocate any object, contrarily to the implementation used to sort primitive types in {@link java.util.Arrays}, which switches to mergesort on large
* inputs.
*
* @param x the array to be sorted.
* @param comp the comparator to determine the sorting order. */
public static void quickSort( final byte[] x, final ByteComparator comp ) {
quickSort( x, 0, x.length, comp );
}
protected static class ForkJoinQuickSortComp extends RecursiveAction {
private static final long serialVersionUID = 1L;
private final int from;
private final int to;
private final byte[] x;
private final ByteComparator comp;
public ForkJoinQuickSortComp( final byte[] x, final int from, final int to, final ByteComparator comp ) {
this.from = from;
this.to = to;
this.x = x;
this.comp = comp;
}
@Override
protected void compute() {
final byte[] x = this.x;
final int len = to - from;
if ( len < PARALLEL_QUICKSORT_NO_FORK ) {
quickSort( x, from, to, comp );
return;
}
// Choose a partition element, v
int m = from + len / 2;
int l = from;
int n = to - 1;
int s = len / 8;
l = med3( x, l, l + s, l + 2 * s );
m = med3( x, m - s, m, m + s );
n = med3( x, n - 2 * s, n - s, n );
m = med3( x, l, m, n );
final byte v = x[ m ];
// Establish Invariant: v* (<v)* (>v)* v*
int a = from, b = a, c = to - 1, d = c;
while ( true ) {
int comparison;
while ( b <= c && ( comparison = comp.compare( x[ b ], v ) ) <= 0 ) {
if ( comparison == 0 ) swap( x, a++, b );
b++;
}
while ( c >= b && ( comparison = comp.compare( x[ c ], v ) ) >= 0 ) {
if ( comparison == 0 ) swap( x, c, d-- );
c--;
}
if ( b > c ) break;
swap( x, b++, c-- );
}
// Swap partition elements back to middle
int t;
s = Math.min( a - from, b - a );
swap( x, from, b - s, s );
s = Math.min( d - c, to - d - 1 );
swap( x, b, to - s, s );
// Recursively sort non-partition-elements
s = b - a;
t = d - c;
if ( s > 1 && t > 1 ) invokeAll( new ForkJoinQuickSortComp( x, from, from + s, comp ), new ForkJoinQuickSortComp( x, to - t, to, comp ) );
else if ( s > 1 ) invokeAll( new ForkJoinQuickSortComp( x, from, from + s, comp ) );
else invokeAll( new ForkJoinQuickSortComp( x, to - t, to, comp ) );
}
}
/** Sorts the specified range of elements according to the order induced by the specified comparator using a parallel quicksort.
*
* <p>The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy, “Engineering a Sort Function”, <i>Software: Practice and Experience</i>, 23(11),
* pages 1249−1265, 1993.
*
* <p>This implementation uses a {@link ForkJoinPool} executor service with {@link Runtime#availableProcessors()} parallel threads.
*
* @param x the array to be sorted.
* @param from the index of the first element (inclusive) to be sorted.
* @param to the index of the last element (exclusive) to be sorted.
* @param comp the comparator to determine the sorting order. */
public static void parallelQuickSort( final byte[] x, final int from, final int to, final ByteComparator comp ) {
if ( to - from < PARALLEL_QUICKSORT_NO_FORK ) quickSort( x, from, to, comp );
else {
final ForkJoinPool pool = new ForkJoinPool( Runtime.getRuntime().availableProcessors() );
pool.invoke( new ForkJoinQuickSortComp( x, from, to, comp ) );
pool.shutdown();
}
}
/** Sorts an array according to the order induced by the specified comparator using a parallel quicksort.
*
* <p>The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy, “Engineering a Sort Function”, <i>Software: Practice and Experience</i>, 23(11),
* pages 1249−1265, 1993.
*
* <p>This implementation uses a {@link ForkJoinPool} executor service with {@link Runtime#availableProcessors()} parallel threads.
*
* @param x the array to be sorted.
* @param comp the comparator to determine the sorting order. */
public static void parallelQuickSort( final byte[] x, final ByteComparator comp ) {
parallelQuickSort( x, 0, x.length, comp );
}
private static int med3( final byte x[], final int a, final int b, final int c ) {
final int ab = ( Byte.compare( ( x[ a ] ), ( x[ b ] ) ) );
final int ac = ( Byte.compare( ( x[ a ] ), ( x[ c ] ) ) );
final int bc = ( Byte.compare( ( x[ b ] ), ( x[ c ] ) ) );
return ( ab < 0 ?
( bc < 0 ? b : ac < 0 ? c : a ) :
( bc > 0 ? b : ac > 0 ? c : a ) );
}
private static void selectionSort( final byte[] a, final int from, final int to ) {
for ( int i = from; i < to - 1; i++ ) {
int m = i;
for ( int j = i + 1; j < to; j++ )
if ( ( ( a[ j ] ) < ( a[ m ] ) ) ) m = j;
if ( m != i ) {
final byte u = a[ i ];
a[ i ] = a[ m ];
a[ m ] = u;
}
}
}
private static void insertionSort( final byte[] a, final int from, final int to ) {
for ( int i = from; ++i < to; ) {
byte t = a[ i ];
int j = i;
for ( byte u = a[ j - 1 ]; ( ( t ) < ( u ) ); u = a[ --j - 1 ] ) {
a[ j ] = u;
if ( from == j - 1 ) {
--j;
break;
}
}
a[ j ] = t;
}
}
/** Sorts the specified range of elements according to the natural ascending order using quicksort.
*
* <p>The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy, “Engineering a Sort Function”, <i>Software: Practice and Experience</i>, 23(11),
* pages 1249−1265, 1993.
*
* <p>Note that this implementation does not allocate any object, contrarily to the implementation used to sort primitive types in {@link java.util.Arrays}, which switches to mergesort on large
* inputs.
*
* @param x the array to be sorted.
* @param from the index of the first element (inclusive) to be sorted.
* @param to the index of the last element (exclusive) to be sorted. */
public static void quickSort( final byte[] x, final int from, final int to ) {
final int len = to - from;
// Selection sort on smallest arrays
if ( len < QUICKSORT_NO_REC ) {
selectionSort( x, from, to );
return;
}
// Choose a partition element, v
int m = from + len / 2;
int l = from;
int n = to - 1;
if ( len > QUICKSORT_MEDIAN_OF_9 ) { // Big arrays, pseudomedian of 9
int s = len / 8;
l = med3( x, l, l + s, l + 2 * s );
m = med3( x, m - s, m, m + s );
n = med3( x, n - 2 * s, n - s, n );
}
m = med3( x, l, m, n ); // Mid-size, med of 3
final byte v = x[ m ];
// Establish Invariant: v* (<v)* (>v)* v*
int a = from, b = a, c = to - 1, d = c;
while ( true ) {
int comparison;
while ( b <= c && ( comparison = ( Byte.compare( ( x[ b ] ), ( v ) ) ) ) <= 0 ) {
if ( comparison == 0 ) swap( x, a++, b );
b++;
}
while ( c >= b && ( comparison = ( Byte.compare( ( x[ c ] ), ( v ) ) ) ) >= 0 ) {
if ( comparison == 0 ) swap( x, c, d-- );
c--;
}
if ( b > c ) break;
swap( x, b++, c-- );
}
// Swap partition elements back to middle
int s;
s = Math.min( a - from, b - a );
swap( x, from, b - s, s );
s = Math.min( d - c, to - d - 1 );
swap( x, b, to - s, s );
// Recursively sort non-partition-elements
if ( ( s = b - a ) > 1 ) quickSort( x, from, from + s );
if ( ( s = d - c ) > 1 ) quickSort( x, to - s, to );
}
/** Sorts an array according to the natural ascending order using quicksort.
*
* <p>The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy, “Engineering a Sort Function”, <i>Software: Practice and Experience</i>, 23(11),
* pages 1249−1265, 1993.
*
* <p>Note that this implementation does not allocate any object, contrarily to the implementation used to sort primitive types in {@link java.util.Arrays}, which switches to mergesort on large
* inputs.
*
* @param x the array to be sorted. */
public static void quickSort( final byte[] x ) {
quickSort( x, 0, x.length );
}
protected static class ForkJoinQuickSort extends RecursiveAction {
private static final long serialVersionUID = 1L;
private final int from;
private final int to;
private final byte[] x;
public ForkJoinQuickSort( final byte[] x, final int from, final int to ) {
this.from = from;
this.to = to;
this.x = x;
}
@Override
protected void compute() {
final byte[] x = this.x;
final int len = to - from;
if ( len < PARALLEL_QUICKSORT_NO_FORK ) {
quickSort( x, from, to );
return;
}
// Choose a partition element, v
int m = from + len / 2;
int l = from;
int n = to - 1;
int s = len / 8;
l = med3( x, l, l + s, l + 2 * s );
m = med3( x, m - s, m, m + s );
n = med3( x, n - 2 * s, n - s, n );
m = med3( x, l, m, n );
final byte v = x[ m ];
// Establish Invariant: v* (<v)* (>v)* v*
int a = from, b = a, c = to - 1, d = c;
while ( true ) {
int comparison;
while ( b <= c && ( comparison = ( Byte.compare( ( x[ b ] ), ( v ) ) ) ) <= 0 ) {
if ( comparison == 0 ) swap( x, a++, b );
b++;
}
while ( c >= b && ( comparison = ( Byte.compare( ( x[ c ] ), ( v ) ) ) ) >= 0 ) {
if ( comparison == 0 ) swap( x, c, d-- );
c--;
}
if ( b > c ) break;
swap( x, b++, c-- );
}
// Swap partition elements back to middle
int t;
s = Math.min( a - from, b - a );
swap( x, from, b - s, s );
s = Math.min( d - c, to - d - 1 );
swap( x, b, to - s, s );
// Recursively sort non-partition-elements
s = b - a;
t = d - c;
if ( s > 1 && t > 1 ) invokeAll( new ForkJoinQuickSort( x, from, from + s ), new ForkJoinQuickSort( x, to - t, to ) );
else if ( s > 1 ) invokeAll( new ForkJoinQuickSort( x, from, from + s ) );
else invokeAll( new ForkJoinQuickSort( x, to - t, to ) );
}
}
/** Sorts the specified range of elements according to the natural ascending order using a parallel quicksort.
*
* <p>The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy, “Engineering a Sort Function”, <i>Software: Practice and Experience</i>, 23(11),
* pages 1249−1265, 1993.
*
* <p>This implementation uses a {@link ForkJoinPool} executor service with {@link Runtime#availableProcessors()} parallel threads.
*
* @param x the array to be sorted.
* @param from the index of the first element (inclusive) to be sorted.
* @param to the index of the last element (exclusive) to be sorted. */
public static void parallelQuickSort( final byte[] x, final int from, final int to ) {
if ( to - from < PARALLEL_QUICKSORT_NO_FORK ) quickSort( x, from, to );
else {
final ForkJoinPool pool = new ForkJoinPool( Runtime.getRuntime().availableProcessors() );
pool.invoke( new ForkJoinQuickSort( x, from, to ) );
pool.shutdown();
}
}
/** Sorts an array according to the natural ascending order using a parallel quicksort.
*
* <p>The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy, “Engineering a Sort Function”, <i>Software: Practice and Experience</i>, 23(11),
* pages 1249−1265, 1993.
*
* <p>This implementation uses a {@link ForkJoinPool} executor service with {@link Runtime#availableProcessors()} parallel threads.
*
* @param x the array to be sorted. */
public static void parallelQuickSort( final byte[] x ) {
parallelQuickSort( x, 0, x.length );
}
private static int med3Indirect( final int perm[], final byte x[], final int a, final int b, final int c ) {
final byte aa = x[ perm[ a ] ];
final byte bb = x[ perm[ b ] ];
final byte cc = x[ perm[ c ] ];
final int ab = ( Byte.compare( ( aa ), ( bb ) ) );
final int ac = ( Byte.compare( ( aa ), ( cc ) ) );
final int bc = ( Byte.compare( ( bb ), ( cc ) ) );
return ( ab < 0 ?
( bc < 0 ? b : ac < 0 ? c : a ) :
( bc > 0 ? b : ac > 0 ? c : a ) );
}
private static void insertionSortIndirect( final int[] perm, final byte[] a, final int from, final int to ) {
for ( int i = from; ++i < to; ) {
int t = perm[ i ];
int j = i;
for ( int u = perm[ j - 1 ]; ( ( a[ t ] ) < ( a[ u ] ) ); u = perm[ --j - 1 ] ) {
perm[ j ] = u;
if ( from == j - 1 ) {
--j;
break;
}
}
perm[ j ] = t;
}
}
/** Sorts the specified range of elements according to the natural ascending order using indirect quicksort.
*
* <p>The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy, “Engineering a Sort Function”, <i>Software: Practice and Experience</i>, 23(11),
* pages 1249−1265, 1993.
*
* <p>This method implement an <em>indirect</em> sort. The elements of <code>perm</code> (which must be exactly the numbers in the interval <code>[0..perm.length)</code>) will be permuted so that
* <code>x[ perm[ i ] ] ≤ x[ perm[ i + 1 ] ]</code>.
*
* <p>Note that this implementation does not allocate any object, contrarily to the implementation used to sort primitive types in {@link java.util.Arrays}, which switches to mergesort on large
* inputs.
*
* @param perm a permutation array indexing {@code x}.
* @param x the array to be sorted.
* @param from the index of the first element (inclusive) to be sorted.
* @param to the index of the last element (exclusive) to be sorted. */
public static void quickSortIndirect( final int[] perm, final byte[] x, final int from, final int to ) {
final int len = to - from;
// Selection sort on smallest arrays
if ( len < QUICKSORT_NO_REC ) {
insertionSortIndirect( perm, x, from, to );
return;
}
// Choose a partition element, v
int m = from + len / 2;
int l = from;
int n = to - 1;
if ( len > QUICKSORT_MEDIAN_OF_9 ) { // Big arrays, pseudomedian of 9
int s = len / 8;
l = med3Indirect( perm, x, l, l + s, l + 2 * s );
m = med3Indirect( perm, x, m - s, m, m + s );
n = med3Indirect( perm, x, n - 2 * s, n - s, n );
}
m = med3Indirect( perm, x, l, m, n ); // Mid-size, med of 3
final byte v = x[ perm[ m ] ];
// Establish Invariant: v* (<v)* (>v)* v*
int a = from, b = a, c = to - 1, d = c;
while ( true ) {
int comparison;
while ( b <= c && ( comparison = ( Byte.compare( ( x[ perm[ b ] ] ), ( v ) ) ) ) <= 0 ) {
if ( comparison == 0 ) IntArrays.swap( perm, a++, b );
b++;
}
while ( c >= b && ( comparison = ( Byte.compare( ( x[ perm[ c ] ] ), ( v ) ) ) ) >= 0 ) {
if ( comparison == 0 ) IntArrays.swap( perm, c, d-- );
c--;
}
if ( b > c ) break;
IntArrays.swap( perm, b++, c-- );
}
// Swap partition elements back to middle
int s;
s = Math.min( a - from, b - a );
IntArrays.swap( perm, from, b - s, s );
s = Math.min( d - c, to - d - 1 );
IntArrays.swap( perm, b, to - s, s );
// Recursively sort non-partition-elements
if ( ( s = b - a ) > 1 ) quickSortIndirect( perm, x, from, from + s );
if ( ( s = d - c ) > 1 ) quickSortIndirect( perm, x, to - s, to );
}
/** Sorts an array according to the natural ascending order using indirect quicksort.
*
* <p>The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy, “Engineering a Sort Function”, <i>Software: Practice and Experience</i>, 23(11),
* pages 1249−1265, 1993.
*
* <p>This method implement an <em>indirect</em> sort. The elements of <code>perm</code> (which must be exactly the numbers in the interval <code>[0..perm.length)</code>) will be permuted so that
* <code>x[ perm[ i ] ] ≤ x[ perm[ i + 1 ] ]</code>.
*
* <p>Note that this implementation does not allocate any object, contrarily to the implementation used to sort primitive types in {@link java.util.Arrays}, which switches to mergesort on large
* inputs.
*
* @param perm a permutation array indexing {@code x}.
* @param x the array to be sorted. */
public static void quickSortIndirect( final int perm[], final byte[] x ) {
quickSortIndirect( perm, x, 0, x.length );
}
protected static class ForkJoinQuickSortIndirect extends RecursiveAction {
private static final long serialVersionUID = 1L;
private final int from;
private final int to;
private final int[] perm;
private final byte[] x;
public ForkJoinQuickSortIndirect( final int perm[], final byte[] x, final int from, final int to ) {
this.from = from;
this.to = to;
this.x = x;
this.perm = perm;
}
@Override
protected void compute() {
final byte[] x = this.x;
final int len = to - from;
if ( len < PARALLEL_QUICKSORT_NO_FORK ) {
quickSortIndirect( perm, x, from, to );
return;
}
// Choose a partition element, v
int m = from + len / 2;
int l = from;
int n = to - 1;
int s = len / 8;
l = med3Indirect( perm, x, l, l + s, l + 2 * s );
m = med3Indirect( perm, x, m - s, m, m + s );
n = med3Indirect( perm, x, n - 2 * s, n - s, n );
m = med3Indirect( perm, x, l, m, n );
final byte v = x[ perm[ m ] ];
// Establish Invariant: v* (<v)* (>v)* v*
int a = from, b = a, c = to - 1, d = c;
while ( true ) {
int comparison;
while ( b <= c && ( comparison = ( Byte.compare( ( x[ perm[ b ] ] ), ( v ) ) ) ) <= 0 ) {
if ( comparison == 0 ) IntArrays.swap( perm, a++, b );
b++;
}
while ( c >= b && ( comparison = ( Byte.compare( ( x[ perm[ c ] ] ), ( v ) ) ) ) >= 0 ) {
if ( comparison == 0 ) IntArrays.swap( perm, c, d-- );
c--;
}
if ( b > c ) break;
IntArrays.swap( perm, b++, c-- );
}
// Swap partition elements back to middle
int t;
s = Math.min( a - from, b - a );
IntArrays.swap( perm, from, b - s, s );
s = Math.min( d - c, to - d - 1 );
IntArrays.swap( perm, b, to - s, s );
// Recursively sort non-partition-elements
s = b - a;
t = d - c;
if ( s > 1 && t > 1 ) invokeAll( new ForkJoinQuickSortIndirect( perm, x, from, from + s ), new ForkJoinQuickSortIndirect( perm, x, to - t, to ) );
else if ( s > 1 ) invokeAll( new ForkJoinQuickSortIndirect( perm, x, from, from + s ) );
else invokeAll( new ForkJoinQuickSortIndirect( perm, x, to - t, to ) );
}
}
/** Sorts the specified range of elements according to the natural ascending order using a parallel indirect quicksort.
*
* <p>The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy, “Engineering a Sort Function”, <i>Software: Practice and Experience</i>, 23(11),
* pages 1249−1265, 1993.
*
* <p>This method implement an <em>indirect</em> sort. The elements of <code>perm</code> (which must be exactly the numbers in the interval <code>[0..perm.length)</code>) will be permuted so that
* <code>x[ perm[ i ] ] ≤ x[ perm[ i + 1 ] ]</code>.
*
* <p>This implementation uses a {@link ForkJoinPool} executor service with {@link Runtime#availableProcessors()} parallel threads.
*
* @param perm a permutation array indexing {@code x}.
* @param x the array to be sorted.
* @param from the index of the first element (inclusive) to be sorted.
* @param to the index of the last element (exclusive) to be sorted. */
public static void parallelQuickSortIndirect( final int[] perm, final byte[] x, final int from, final int to ) {
if ( to - from < PARALLEL_QUICKSORT_NO_FORK ) quickSortIndirect( perm, x, from, to );
else {
final ForkJoinPool pool = new ForkJoinPool( Runtime.getRuntime().availableProcessors() );
pool.invoke( new ForkJoinQuickSortIndirect( perm, x, from, to ) );
pool.shutdown();
}
}
/** Sorts an array according to the natural ascending order using a parallel indirect quicksort.
*
* <p>The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy, “Engineering a Sort Function”, <i>Software: Practice and Experience</i>, 23(11),
* pages 1249−1265, 1993.
*
* <p>This method implement an <em>indirect</em> sort. The elements of <code>perm</code> (which must be exactly the numbers in the interval <code>[0..perm.length)</code>) will be permuted so that
* <code>x[ perm[ i ] ] ≤ x[ perm[ i + 1 ] ]</code>.
*
* <p>This implementation uses a {@link ForkJoinPool} executor service with {@link Runtime#availableProcessors()} parallel threads.
*
* @param perm a permutation array indexing {@code x}.
* @param x the array to be sorted. */
public static void parallelQuickSortIndirect( final int perm[], final byte[] x ) {
parallelQuickSortIndirect( perm, x, 0, x.length );
}
/** Stabilizes a permutation.
*
* <p>This method can be used to stabilize the permutation generated by an indirect sorting, assuming that initially the permutation array was in ascending order (e.g., the identity, as usually
* happens). This method scans the permutation, and for each non-singleton block of elements with the same associated values in {@code x}, permutes them in ascending order. The resulting
* permutation corresponds to a stable sort.
*
* <p>Usually combining an unstable indirect sort and this method is more efficient than using a stable sort, as most stable sort algorithms require a support array.
*
* <p>More precisely, assuming that <code>x[ perm[ i ] ] ≤ x[ perm[ i + 1 ] ]</code>, after stabilization we will also have that <code>x[ perm[ i ] ] = x[ perm[ i + 1 ] ]</code> implies
* <code>perm[ i ] ≤ perm[ i + 1 ]</code>.
*
* @param perm a permutation array indexing {@code x} so that it is sorted.
* @param x the sorted array to be stabilized.
* @param from the index of the first element (inclusive) to be stabilized.
* @param to the index of the last element (exclusive) to be stabilized. */
public static void stabilize( final int perm[], final byte[] x, final int from, final int to ) {
int curr = from;
for ( int i = from + 1; i < to; i++ ) {
if ( x[ perm[ i ] ] != x[ perm[ curr ] ] ) {
if ( i - curr > 1 ) IntArrays.parallelQuickSort( perm, curr, i );
curr = i;
}
}
if ( to - curr > 1 ) IntArrays.parallelQuickSort( perm, curr, to );
}
/** Stabilizes a permutation.
*
* <p>This method can be used to stabilize the permutation generated by an indirect sorting, assuming that initially the permutation array was in ascending order (e.g., the identity, as usually
* happens). This method scans the permutation, and for each non-singleton block of elements with the same associated values in {@code x}, permutes them in ascending order. The resulting
* permutation corresponds to a stable sort.
*
* <p>Usually combining an unstable indirect sort and this method is more efficient than using a stable sort, as most stable sort algorithms require a support array.
*
* <p>More precisely, assuming that <code>x[ perm[ i ] ] ≤ x[ perm[ i + 1 ] ]</code>, after stabilization we will also have that <code>x[ perm[ i ] ] = x[ perm[ i + 1 ] ]</code> implies
* <code>perm[ i ] ≤ perm[ i + 1 ]</code>.
*
* @param perm a permutation array indexing {@code x} so that it is sorted.
* @param x the sorted array to be stabilized. */
public static void stabilize( final int perm[], final byte[] x ) {
stabilize( perm, x, 0, perm.length );
}
private static int med3( final byte x[], final byte[] y, final int a, final int b, final int c ) {
int t;
final int ab = ( t = ( Byte.compare( ( x[ a ] ), ( x[ b ] ) ) ) ) == 0 ? ( Byte.compare( ( y[ a ] ), ( y[ b ] ) ) ) : t;
final int ac = ( t = ( Byte.compare( ( x[ a ] ), ( x[ c ] ) ) ) ) == 0 ? ( Byte.compare( ( y[ a ] ), ( y[ c ] ) ) ) : t;
final int bc = ( t = ( Byte.compare( ( x[ b ] ), ( x[ c ] ) ) ) ) == 0 ? ( Byte.compare( ( y[ b ] ), ( y[ c ] ) ) ) : t;
return ( ab < 0 ?
( bc < 0 ? b : ac < 0 ? c : a ) :
( bc > 0 ? b : ac > 0 ? c : a ) );
}
private static void swap( final byte x[], final byte[] y, final int a, final int b ) {
final byte t = x[ a ];
final byte u = y[ a ];
x[ a ] = x[ b ];
y[ a ] = y[ b ];
x[ b ] = t;
y[ b ] = u;
}
private static void swap( final byte[] x, final byte[] y, int a, int b, final int n ) {
for ( int i = 0; i < n; i++, a++, b++ )
swap( x, y, a, b );
}
private static void selectionSort( final byte[] a, final byte[] b, final int from, final int to ) {
for ( int i = from; i < to - 1; i++ ) {
int m = i, u;
for ( int j = i + 1; j < to; j++ )
if ( ( u = ( Byte.compare( ( a[ j ] ), ( a[ m ] ) ) ) ) < 0 || u == 0 && ( ( b[ j ] ) < ( b[ m ] ) ) ) m = j;
if ( m != i ) {
byte t = a[ i ];
a[ i ] = a[ m ];
a[ m ] = t;
t = b[ i ];
b[ i ] = b[ m ];
b[ m ] = t;
}
}
}
/** Sorts the specified range of elements of two arrays according to the natural lexicographical ascending order using quicksort.
*
* <p>The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy, “Engineering a Sort Function”, <i>Software: Practice and Experience</i>, 23(11),
* pages 1249−1265, 1993.
*
* <p>This method implements a <em>lexicographical</em> sorting of the arguments. Pairs of elements in the same position in the two provided arrays will be considered a single key, and permuted
* accordingly. In the end, either <code>x[ i ] < x[ i + 1 ]</code> or <code>x[ i ] == x[ i + 1 ]</code> and <code>y[ i ] ≤ y[ i + 1 ]</code>.
*
* @param x the first array to be sorted.
* @param y the second array to be sorted.
* @param from the index of the first element (inclusive) to be sorted.
* @param to the index of the last element (exclusive) to be sorted. */
public static void quickSort( final byte[] x, final byte[] y, final int from, final int to ) {
final int len = to - from;
if ( len < QUICKSORT_NO_REC ) {
selectionSort( x, y, from, to );
return;
}
// Choose a partition element, v
int m = from + len / 2;
int l = from;
int n = to - 1;
if ( len > QUICKSORT_MEDIAN_OF_9 ) { // Big arrays, pseudomedian of 9
int s = len / 8;
l = med3( x, y, l, l + s, l + 2 * s );
m = med3( x, y, m - s, m, m + s );
n = med3( x, y, n - 2 * s, n - s, n );
}
m = med3( x, y, l, m, n ); // Mid-size, med of 3
final byte v = x[ m ], w = y[ m ];
// Establish Invariant: v* (<v)* (>v)* v*
int a = from, b = a, c = to - 1, d = c;
while ( true ) {
int comparison, t;
while ( b <= c && ( comparison = ( t = ( Byte.compare( ( x[ b ] ), ( v ) ) ) ) == 0 ? ( Byte.compare( ( y[ b ] ), ( w ) ) ) : t ) <= 0 ) {
if ( comparison == 0 ) swap( x, y, a++, b );
b++;
}
while ( c >= b && ( comparison = ( t = ( Byte.compare( ( x[ c ] ), ( v ) ) ) ) == 0 ? ( Byte.compare( ( y[ c ] ), ( w ) ) ) : t ) >= 0 ) {
if ( comparison == 0 ) swap( x, y, c, d-- );
c--;
}
if ( b > c ) break;
swap( x, y, b++, c-- );
}
// Swap partition elements back to middle
int s;
s = Math.min( a - from, b - a );
swap( x, y, from, b - s, s );
s = Math.min( d - c, to - d - 1 );
swap( x, y, b, to - s, s );
// Recursively sort non-partition-elements
if ( ( s = b - a ) > 1 ) quickSort( x, y, from, from + s );
if ( ( s = d - c ) > 1 ) quickSort( x, y, to - s, to );
}
/** Sorts two arrays according to the natural lexicographical ascending order using quicksort.
*
* <p>The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy, “Engineering a Sort Function”, <i>Software: Practice and Experience</i>, 23(11),
* pages 1249−1265, 1993.
*
* <p>This method implements a <em>lexicographical</em> sorting of the arguments. Pairs of elements in the same position in the two provided arrays will be considered a single key, and permuted
* accordingly. In the end, either <code>x[ i ] < x[ i + 1 ]</code> or <code>x[ i ] == x[ i + 1 ]</code> and <code>y[ i ] ≤ y[ i + 1 ]</code>.
*
* @param x the first array to be sorted.
* @param y the second array to be sorted. */
public static void quickSort( final byte[] x, final byte[] y ) {
ensureSameLength( x, y );
quickSort( x, y, 0, x.length );
}
protected static class ForkJoinQuickSort2 extends RecursiveAction {
private static final long serialVersionUID = 1L;
private final int from;
private final int to;
private final byte[] x, y;
public ForkJoinQuickSort2( final byte[] x, final byte[] y, final int from, final int to ) {
this.from = from;
this.to = to;
this.x = x;
this.y = y;
}
@Override
protected void compute() {
final byte[] x = this.x;
final byte[] y = this.y;
final int len = to - from;
if ( len < PARALLEL_QUICKSORT_NO_FORK ) {
quickSort( x, y, from, to );
return;
}
// Choose a partition element, v
int m = from + len / 2;
int l = from;
int n = to - 1;
int s = len / 8;
l = med3( x, y, l, l + s, l + 2 * s );
m = med3( x, y, m - s, m, m + s );
n = med3( x, y, n - 2 * s, n - s, n );
m = med3( x, y, l, m, n );
final byte v = x[ m ], w = y[ m ];
// Establish Invariant: v* (<v)* (>v)* v*
int a = from, b = a, c = to - 1, d = c;
while ( true ) {
int comparison, t;
while ( b <= c && ( comparison = ( t = ( Byte.compare( ( x[ b ] ), ( v ) ) ) ) == 0 ? ( Byte.compare( ( y[ b ] ), ( w ) ) ) : t ) <= 0 ) {
if ( comparison == 0 ) swap( x, y, a++, b );
b++;
}
while ( c >= b && ( comparison = ( t = ( Byte.compare( ( x[ c ] ), ( v ) ) ) ) == 0 ? ( Byte.compare( ( y[ c ] ), ( w ) ) ) : t ) >= 0 ) {
if ( comparison == 0 ) swap( x, y, c, d-- );
c--;
}
if ( b > c ) break;
swap( x, y, b++, c-- );
}
// Swap partition elements back to middle
int t;
s = Math.min( a - from, b - a );
swap( x, y, from, b - s, s );
s = Math.min( d - c, to - d - 1 );
swap( x, y, b, to - s, s );
s = b - a;
t = d - c;
// Recursively sort non-partition-elements
if ( s > 1 && t > 1 ) invokeAll( new ForkJoinQuickSort2( x, y, from, from + s ), new ForkJoinQuickSort2( x, y, to - t, to ) );
else if ( s > 1 ) invokeAll( new ForkJoinQuickSort2( x, y, from, from + s ) );
else invokeAll( new ForkJoinQuickSort2( x, y, to - t, to ) );
}
}
/** Sorts the specified range of elements of two arrays according to the natural lexicographical ascending order using a parallel quicksort.
*
* <p>The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy, “Engineering a Sort Function”, <i>Software: Practice and Experience</i>, 23(11),
* pages 1249−1265, 1993.
*
* <p>This method implements a <em>lexicographical</em> sorting of the arguments. Pairs of elements in the same position in the two provided arrays will be considered a single key, and permuted
* accordingly. In the end, either <code>x[ i ] < x[ i + 1 ]</code> or <code>x[ i ] == x[ i + 1 ]</code> and <code>y[ i ] ≤ y[ i + 1 ]</code>.
*
* <p>This implementation uses a {@link ForkJoinPool} executor service with {@link Runtime#availableProcessors()} parallel threads.
*
* @param x the first array to be sorted.
* @param y the second array to be sorted.
* @param from the index of the first element (inclusive) to be sorted.
* @param to the index of the last element (exclusive) to be sorted. */
public static void parallelQuickSort( final byte[] x, final byte[] y, final int from, final int to ) {
if ( to - from < PARALLEL_QUICKSORT_NO_FORK ) quickSort( x, y, from, to );
final ForkJoinPool pool = new ForkJoinPool( Runtime.getRuntime().availableProcessors() );
pool.invoke( new ForkJoinQuickSort2( x, y, from, to ) );
pool.shutdown();
}
/** Sorts two arrays according to the natural lexicographical ascending order using a parallel quicksort.
*
* <p>The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy, “Engineering a Sort Function”, <i>Software: Practice and Experience</i>, 23(11),
* pages 1249−1265, 1993.
*
* <p>This method implements a <em>lexicographical</em> sorting of the arguments. Pairs of elements in the same position in the two provided arrays will be considered a single key, and permuted
* accordingly. In the end, either <code>x[ i ] < x[ i + 1 ]</code> or <code>x[ i ] == x[ i + 1 ]</code> and <code>y[ i ] ≤ y[ i + 1 ]</code>.
*
* <p>This implementation uses a {@link ForkJoinPool} executor service with {@link Runtime#availableProcessors()} parallel threads.
*
* @param x the first array to be sorted.
* @param y the second array to be sorted. */
public static void parallelQuickSort( final byte[] x, final byte[] y ) {
ensureSameLength( x, y );
parallelQuickSort( x, y, 0, x.length );
}
/** Sorts the specified range of elements according to the natural ascending order using mergesort, using a given pre-filled support array.
*
* <p>This sort is guaranteed to be <i>stable</i>: equal elements will not be reordered as a result of the sort. Moreover, no support arrays will be allocated.
*
* @param a the array to be sorted.
* @param from the index of the first element (inclusive) to be sorted.
* @param to the index of the last element (exclusive) to be sorted.
* @param supp a support array containing at least <code>to</code> elements, and whose entries are identical to those of {@code a} in the specified range. */
public static void mergeSort( final byte a[], final int from, final int to, final byte supp[] ) {
int len = to - from;
// Insertion sort on smallest arrays
if ( len < MERGESORT_NO_REC ) {
insertionSort( a, from, to );
return;
}
// Recursively sort halves of a into supp
final int mid = ( from + to ) >>> 1;
mergeSort( supp, from, mid, a );
mergeSort( supp, mid, to, a );
// If list is already sorted, just copy from supp to a. This is an
// optimization that results in faster sorts for nearly ordered lists.
if ( ( ( supp[ mid - 1 ] ) <= ( supp[ mid ] ) ) ) {
System.arraycopy( supp, from, a, from, len );
return;
}
// Merge sorted halves (now in supp) into a
for ( int i = from, p = from, q = mid; i < to; i++ ) {
if ( q >= to || p < mid && ( ( supp[ p ] ) <= ( supp[ q ] ) ) ) a[ i ] = supp[ p++ ];
else a[ i ] = supp[ q++ ];
}
}
/** Sorts the specified range of elements according to the natural ascending order using mergesort.
*
* <p>This sort is guaranteed to be <i>stable</i>: equal elements will not be reordered as a result of the sort. An array as large as <code>a</code> will be allocated by this method.
*
* @param a the array to be sorted.
* @param from the index of the first element (inclusive) to be sorted.
* @param to the index of the last element (exclusive) to be sorted. */
public static void mergeSort( final byte a[], final int from, final int to ) {
mergeSort( a, from, to, a.clone() );
}
/** Sorts an array according to the natural ascending order using mergesort.
*
* <p>This sort is guaranteed to be <i>stable</i>: equal elements will not be reordered as a result of the sort. An array as large as <code>a</code> will be allocated by this method.
*
* @param a the array to be sorted. */
public static void mergeSort( final byte a[] ) {
mergeSort( a, 0, a.length );
}
/** Sorts the specified range of elements according to the order induced by the specified comparator using mergesort, using a given pre-filled support array.
*
* <p>This sort is guaranteed to be <i>stable</i>: equal elements will not be reordered as a result of the sort. Moreover, no support arrays will be allocated.
*
* @param a the array to be sorted.
* @param from the index of the first element (inclusive) to be sorted.
* @param to the index of the last element (exclusive) to be sorted.
* @param comp the comparator to determine the sorting order.
* @param supp a support array containing at least <code>to</code> elements, and whose entries are identical to those of {@code a} in the specified range. */
public static void mergeSort( final byte a[], final int from, final int to, ByteComparator comp, final byte supp[] ) {
int len = to - from;
// Insertion sort on smallest arrays
if ( len < MERGESORT_NO_REC ) {
insertionSort( a, from, to, comp );
return;
}
// Recursively sort halves of a into supp
final int mid = ( from + to ) >>> 1;
mergeSort( supp, from, mid, comp, a );
mergeSort( supp, mid, to, comp, a );
// If list is already sorted, just copy from supp to a. This is an
// optimization that results in faster sorts for nearly ordered lists.
if ( comp.compare( supp[ mid - 1 ], supp[ mid ] ) <= 0 ) {
System.arraycopy( supp, from, a, from, len );
return;
}
// Merge sorted halves (now in supp) into a
for ( int i = from, p = from, q = mid; i < to; i++ ) {
if ( q >= to || p < mid && comp.compare( supp[ p ], supp[ q ] ) <= 0 ) a[ i ] = supp[ p++ ];
else a[ i ] = supp[ q++ ];
}
}
/** Sorts the specified range of elements according to the order induced by the specified comparator using mergesort.
*
* <p>This sort is guaranteed to be <i>stable</i>: equal elements will not be reordered as a result of the sort. An array as large as <code>a</code> will be allocated by this method.
*
* @param a the array to be sorted.
* @param from the index of the first element (inclusive) to be sorted.
* @param to the index of the last element (exclusive) to be sorted.
* @param comp the comparator to determine the sorting order. */
public static void mergeSort( final byte a[], final int from, final int to, ByteComparator comp ) {
mergeSort( a, from, to, comp, a.clone() );
}
/** Sorts an array according to the order induced by the specified comparator using mergesort.
*
* <p>This sort is guaranteed to be <i>stable</i>: equal elements will not be reordered as a result of the sort. An array as large as <code>a</code> will be allocated by this method.
*
* @param a the array to be sorted.
* @param comp the comparator to determine the sorting order. */
public static void mergeSort( final byte a[], ByteComparator comp ) {
mergeSort( a, 0, a.length, comp );
}
/** Searches a range of the specified array for the specified value using the binary search algorithm. The range must be sorted prior to making this call. If it is not sorted, the results are
* undefined. If the range contains multiple elements with the specified value, there is no guarantee which one will be found.
*
* @param a the array to be searched.
* @param from the index of the first element (inclusive) to be searched.
* @param to the index of the last element (exclusive) to be searched.
* @param key the value to be searched for.
* @return index of the search key, if it is contained in the array; otherwise, <code>(-(<i>insertion point</i>) - 1)</code>. The <i>insertion point</i> is defined as the the point at which the
* value would be inserted into the array: the index of the first element greater than the key, or the length of the array, if all elements in the array are less than the specified key. Note that
* this guarantees that the return value will be ≥ 0 if and only if the key is found.
* @see java.util.Arrays */
public static int binarySearch( final byte[] a, int from, int to, final byte key ) {
byte midVal;
to--;
while ( from <= to ) {
final int mid = ( from + to ) >>> 1;
midVal = a[ mid ];
if ( midVal < key ) from = mid + 1;
else if ( midVal > key ) to = mid - 1;
else return mid;
}
return -( from + 1 );
}
/** Searches an array for the specified value using the binary search algorithm. The range must be sorted prior to making this call. If it is not sorted, the results are undefined. If the range
* contains multiple elements with the specified value, there is no guarantee which one will be found.
*
* @param a the array to be searched.
* @param key the value to be searched for.
* @return index of the search key, if it is contained in the array; otherwise, <code>(-(<i>insertion point</i>) - 1)</code>. The <i>insertion point</i> is defined as the the point at which the
* value would be inserted into the array: the index of the first element greater than the key, or the length of the array, if all elements in the array are less than the specified key. Note that
* this guarantees that the return value will be ≥ 0 if and only if the key is found.
* @see java.util.Arrays */
public static int binarySearch( final byte[] a, final byte key ) {
return binarySearch( a, 0, a.length, key );
}
/** Searches a range of the specified array for the specified value using the binary search algorithm and a specified comparator. The range must be sorted following the comparator prior to making
* this call. If it is not sorted, the results are undefined. If the range contains multiple elements with the specified value, there is no guarantee which one will be found.
*
* @param a the array to be searched.
* @param from the index of the first element (inclusive) to be searched.
* @param to the index of the last element (exclusive) to be searched.
* @param key the value to be searched for.
* @param c a comparator.
* @return index of the search key, if it is contained in the array; otherwise, <code>(-(<i>insertion point</i>) - 1)</code>. The <i>insertion point</i> is defined as the the point at which the
* value would be inserted into the array: the index of the first element greater than the key, or the length of the array, if all elements in the array are less than the specified key. Note that
* this guarantees that the return value will be ≥ 0 if and only if the key is found.
* @see java.util.Arrays */
public static int binarySearch( final byte[] a, int from, int to, final byte key, final ByteComparator c ) {
byte midVal;
to--;
while ( from <= to ) {
final int mid = ( from + to ) >>> 1;
midVal = a[ mid ];
final int cmp = c.compare( midVal, key );
if ( cmp < 0 ) from = mid + 1;
else if ( cmp > 0 ) to = mid - 1;
else return mid; // key found
}
return -( from + 1 );
}
/** Searches an array for the specified value using the binary search algorithm and a specified comparator. The range must be sorted following the comparator prior to making this call. If it is not
* sorted, the results are undefined. If the range contains multiple elements with the specified value, there is no guarantee which one will be found.
*
* @param a the array to be searched.
* @param key the value to be searched for.
* @param c a comparator.
* @return index of the search key, if it is contained in the array; otherwise, <code>(-(<i>insertion point</i>) - 1)</code>. The <i>insertion point</i> is defined as the the point at which the
* value would be inserted into the array: the index of the first element greater than the key, or the length of the array, if all elements in the array are less than the specified key. Note that
* this guarantees that the return value will be ≥ 0 if and only if the key is found.
* @see java.util.Arrays */
public static int binarySearch( final byte[] a, final byte key, final ByteComparator c ) {
return binarySearch( a, 0, a.length, key, c );
}
/** The size of a digit used during radix sort (must be a power of 2). */
private static final int DIGIT_BITS = 8;
/** The mask to extract a digit of {@link #DIGIT_BITS} bits. */
private static final int DIGIT_MASK = ( 1 << DIGIT_BITS ) - 1;
/** The number of digits per element. */
private static final int DIGITS_PER_ELEMENT = Byte.SIZE / DIGIT_BITS;
private static final int RADIXSORT_NO_REC = 1024;
private static final int PARALLEL_RADIXSORT_NO_FORK = 1024;
/** This method fixes negative numbers so that the combination exponent/significand is lexicographically sorted. */
/** Sorts the specified array using radix sort.
*
* <p>The sorting algorithm is a tuned radix sort adapted from Peter M. McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix sort”, <i>Computing Systems</i>, 6(1), pages
* 5−27 (1993).
*
* <p>This implementation is significantly faster than quicksort already at small sizes (say, more than 10000 elements), but it can only sort in ascending order.
*
* @param a the array to be sorted. */
public static void radixSort( final byte[] a ) {
radixSort( a, 0, a.length );
}
/** Sorts the specified range of an array using radix sort.
*
* <p>The sorting algorithm is a tuned radix sort adapted from Peter M. McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix sort”, <i>Computing Systems</i>, 6(1), pages
* 5−27 (1993).
*
* <p>This implementation is significantly faster than quicksort already at small sizes (say, more than 10000 elements), but it can only sort in ascending order.
*
* @param a the array to be sorted.
* @param from the index of the first element (inclusive) to be sorted.
* @param to the index of the last element (exclusive) to be sorted. */
public static void radixSort( final byte[] a, final int from, final int to ) {
if ( to - from < RADIXSORT_NO_REC ) {
quickSort( a, from, to );
return;
}
final int maxLevel = DIGITS_PER_ELEMENT - 1;
final int stackSize = ( ( 1 << DIGIT_BITS ) - 1 ) * ( DIGITS_PER_ELEMENT - 1 ) + 1;
int stackPos = 0;
final int[] offsetStack = new int[ stackSize ];
final int[] lengthStack = new int[ stackSize ];
final int[] levelStack = new int[ stackSize ];
offsetStack[ stackPos ] = from;
lengthStack[ stackPos ] = to - from;
levelStack[ stackPos++ ] = 0;
final int[] count = new int[ 1 << DIGIT_BITS ];
final int[] pos = new int[ 1 << DIGIT_BITS ];
while ( stackPos > 0 ) {
final int first = offsetStack[ --stackPos ];
final int length = lengthStack[ stackPos ];
final int level = levelStack[ stackPos ];
final int signMask = level % DIGITS_PER_ELEMENT == 0 ? 1 << DIGIT_BITS - 1 : 0;
final int shift = ( DIGITS_PER_ELEMENT - 1 - level % DIGITS_PER_ELEMENT ) * DIGIT_BITS; // This is the shift that extract the right byte from a key
// Count keys.
for ( int i = first + length; i-- != first; )
count[ ( ( a[ i ] ) >>> shift & DIGIT_MASK ^ signMask ) ]++;
// Compute cumulative distribution
int lastUsed = -1;
for ( int i = 0, p = first; i < 1 << DIGIT_BITS; i++ ) {
if ( count[ i ] != 0 ) lastUsed = i;
pos[ i ] = ( p += count[ i ] );
}
final int end = first + length - count[ lastUsed ];
// i moves through the start of each block
for ( int i = first, c = -1, d; i <= end; i += count[ c ], count[ c ] = 0 ) {
byte t = a[ i ];
c = ( ( t ) >>> shift & DIGIT_MASK ^ signMask );
if ( i < end ) { // When all slots are OK, the last slot is necessarily OK.
while ( ( d = --pos[ c ] ) > i ) {
final byte z = t;
t = a[ d ];
a[ d ] = z;
c = ( ( t ) >>> shift & DIGIT_MASK ^ signMask );
}
a[ i ] = t;
}
if ( level < maxLevel && count[ c ] > 1 ) {
if ( count[ c ] < RADIXSORT_NO_REC ) quickSort( a, i, i + count[ c ] );
else {
offsetStack[ stackPos ] = i;
lengthStack[ stackPos ] = count[ c ];
levelStack[ stackPos++ ] = level + 1;
}
}
}
}
}
protected final static class Segment {
protected final int offset, length, level;
protected Segment( final int offset, final int length, final int level ) {
this.offset = offset;
this.length = length;
this.level = level;
}
@Override
public String toString() {
return "Segment [offset=" + offset + ", length=" + length + ", level=" + level + "]";
}
}
protected final static Segment POISON_PILL = new Segment( -1, -1, -1 );
/** Sorts the specified range of an array using parallel radix sort.
*
* <p>The sorting algorithm is a tuned radix sort adapted from Peter M. McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix sort”, <i>Computing Systems</i>, 6(1), pages
* 5−27 (1993).
*
* <p>This implementation uses a pool of {@link Runtime#availableProcessors()} threads.
*
* @param a the array to be sorted.
* @param from the index of the first element (inclusive) to be sorted.
* @param to the index of the last element (exclusive) to be sorted. */
public static void parallelRadixSort( final byte[] a, final int from, final int to ) {
if ( to - from < PARALLEL_RADIXSORT_NO_FORK ) {
quickSort( a, from, to );
return;
}
final int maxLevel = DIGITS_PER_ELEMENT - 1;
final LinkedBlockingQueue<Segment> queue = new LinkedBlockingQueue<Segment>();
queue.add( new Segment( from, to - from, 0 ) );
final AtomicInteger queueSize = new AtomicInteger( 1 );
final int numberOfThreads = Runtime.getRuntime().availableProcessors();
final ExecutorService executorService = Executors.newFixedThreadPool( numberOfThreads, Executors.defaultThreadFactory() );
final ExecutorCompletionService<Void> executorCompletionService = new ExecutorCompletionService<Void>( executorService );
for ( int i = numberOfThreads; i-- != 0; )
executorCompletionService.submit( new Callable<Void>() {
public Void call() throws Exception {
final int[] count = new int[ 1 << DIGIT_BITS ];
final int[] pos = new int[ 1 << DIGIT_BITS ];
for ( ;; ) {
if ( queueSize.get() == 0 ) for ( int i = numberOfThreads; i-- != 0; )
queue.add( POISON_PILL );
final Segment segment = queue.take();
if ( segment == POISON_PILL ) return null;
final int first = segment.offset;
final int length = segment.length;
final int level = segment.level;
final int signMask = level % DIGITS_PER_ELEMENT == 0 ? 1 << DIGIT_BITS - 1 : 0;
final int shift = ( DIGITS_PER_ELEMENT - 1 - level % DIGITS_PER_ELEMENT ) * DIGIT_BITS; // This is the shift that extract the right byte from a key
// Count keys.
for ( int i = first + length; i-- != first; )
count[ ( ( a[ i ] ) >>> shift & DIGIT_MASK ^ signMask ) ]++;
// Compute cumulative distribution
int lastUsed = -1;
for ( int i = 0, p = first; i < 1 << DIGIT_BITS; i++ ) {
if ( count[ i ] != 0 ) lastUsed = i;
pos[ i ] = ( p += count[ i ] );
}
final int end = first + length - count[ lastUsed ];
// i moves through the start of each block
for ( int i = first, c = -1, d; i <= end; i += count[ c ], count[ c ] = 0 ) {
byte t = a[ i ];
c = ( ( t ) >>> shift & DIGIT_MASK ^ signMask );
if ( i < end ) {
while ( ( d = --pos[ c ] ) > i ) {
final byte z = t;
t = a[ d ];
a[ d ] = z;
c = ( ( t ) >>> shift & DIGIT_MASK ^ signMask );
}
a[ i ] = t;
}
if ( level < maxLevel && count[ c ] > 1 ) {
if ( count[ c ] < PARALLEL_RADIXSORT_NO_FORK ) quickSort( a, i, i + count[ c ] );
else {
queueSize.incrementAndGet();
queue.add( new Segment( i, count[ c ], level + 1 ) );
}
}
}
queueSize.decrementAndGet();
}
}
} );
Throwable problem = null;
for ( int i = numberOfThreads; i-- != 0; )
try {
executorCompletionService.take().get();
}
catch ( Exception e ) {
problem = e.getCause(); // We keep only the last one. They will be logged anyway.
}
executorService.shutdown();
if ( problem != null ) throw ( problem instanceof RuntimeException) ? (RuntimeException)problem : new RuntimeException( problem );
}
/** Sorts the specified array using parallel radix sort.
*
* <p>The sorting algorithm is a tuned radix sort adapted from Peter M. McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix sort”, <i>Computing Systems</i>, 6(1), pages
* 5−27 (1993).
*
* <p>This implementation uses a pool of {@link Runtime#availableProcessors()} threads.
*
* @param a the array to be sorted. */
public static void parallelRadixSort( final byte[] a ) {
parallelRadixSort( a, 0, a.length );
}
/** Sorts the specified array using indirect radix sort.
*
* <p>The sorting algorithm is a tuned radix sort adapted from Peter M. McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix sort”, <i>Computing Systems</i>, 6(1), pages
* 5−27 (1993).
*
* <p>This method implement an <em>indirect</em> sort. The elements of <code>perm</code> (which must be exactly the numbers in the interval <code>[0..perm.length)</code>) will be permuted so that
* <code>a[ perm[ i ] ] ≤ a[ perm[ i + 1 ] ]</code>.
*
* <p>This implementation will allocate, in the stable case, a support array as large as <code>perm</code> (note that the stable version is slightly faster).
*
* @param perm a permutation array indexing <code>a</code>.
* @param a the array to be sorted.
* @param stable whether the sorting algorithm should be stable. */
public static void radixSortIndirect( final int[] perm, final byte[] a, final boolean stable ) {
radixSortIndirect( perm, a, 0, perm.length, stable );
}
/** Sorts the specified array using indirect radix sort.
*
* <p>The sorting algorithm is a tuned radix sort adapted from Peter M. McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix sort”, <i>Computing Systems</i>, 6(1), pages
* 5−27 (1993).
*
* <p>This method implement an <em>indirect</em> sort. The elements of <code>perm</code> (which must be exactly the numbers in the interval <code>[0..perm.length)</code>) will be permuted so that
* <code>a[ perm[ i ] ] ≤ a[ perm[ i + 1 ] ]</code>.
*
* <p>This implementation will allocate, in the stable case, a support array as large as <code>perm</code> (note that the stable version is slightly faster).
*
* @param perm a permutation array indexing <code>a</code>.
* @param a the array to be sorted.
* @param from the index of the first element of <code>perm</code> (inclusive) to be permuted.
* @param to the index of the last element of <code>perm</code> (exclusive) to be permuted.
* @param stable whether the sorting algorithm should be stable. */
public static void radixSortIndirect( final int[] perm, final byte[] a, final int from, final int to, final boolean stable ) {
if ( to - from < RADIXSORT_NO_REC ) {
insertionSortIndirect( perm, a, from, to );
return;
}
final int maxLevel = DIGITS_PER_ELEMENT - 1;
final int stackSize = ( ( 1 << DIGIT_BITS ) - 1 ) * ( DIGITS_PER_ELEMENT - 1 ) + 1;
int stackPos = 0;
final int[] offsetStack = new int[ stackSize ];
final int[] lengthStack = new int[ stackSize ];
final int[] levelStack = new int[ stackSize ];
offsetStack[ stackPos ] = from;
lengthStack[ stackPos ] = to - from;
levelStack[ stackPos++ ] = 0;
final int[] count = new int[ 1 << DIGIT_BITS ];
final int[] pos = new int[ 1 << DIGIT_BITS ];
final int[] support = stable ? new int[ perm.length ] : null;
while ( stackPos > 0 ) {
final int first = offsetStack[ --stackPos ];
final int length = lengthStack[ stackPos ];
final int level = levelStack[ stackPos ];
final int signMask = level % DIGITS_PER_ELEMENT == 0 ? 1 << DIGIT_BITS - 1 : 0;
final int shift = ( DIGITS_PER_ELEMENT - 1 - level % DIGITS_PER_ELEMENT ) * DIGIT_BITS; // This is the shift that extract the right byte from a key
// Count keys.
for ( int i = first + length; i-- != first; )
count[ ( ( a[ perm[ i ] ] ) >>> shift & DIGIT_MASK ^ signMask ) ]++;
// Compute cumulative distribution
int lastUsed = -1;
for ( int i = 0, p = stable ? 0 : first; i < 1 << DIGIT_BITS; i++ ) {
if ( count[ i ] != 0 ) lastUsed = i;
pos[ i ] = ( p += count[ i ] );
}
if ( stable ) {
for ( int i = first + length; i-- != first; )
support[ --pos[ ( ( a[ perm[ i ] ] ) >>> shift & DIGIT_MASK ^ signMask ) ] ] = perm[ i ];
System.arraycopy( support, 0, perm, first, length );
for ( int i = 0, p = first; i <= lastUsed; i++ ) {
if ( level < maxLevel && count[ i ] > 1 ) {
if ( count[ i ] < RADIXSORT_NO_REC ) insertionSortIndirect( perm, a, p, p + count[ i ] );
else {
offsetStack[ stackPos ] = p;
lengthStack[ stackPos ] = count[ i ];
levelStack[ stackPos++ ] = level + 1;
}
}
p += count[ i ];
}
java.util.Arrays.fill( count, 0 );
}
else {
final int end = first + length - count[ lastUsed ];
// i moves through the start of each block
for ( int i = first, c = -1, d; i <= end; i += count[ c ], count[ c ] = 0 ) {
int t = perm[ i ];
c = ( ( a[ t ] ) >>> shift & DIGIT_MASK ^ signMask );
if ( i < end ) { // When all slots are OK, the last slot is necessarily OK.
while ( ( d = --pos[ c ] ) > i ) {
final int z = t;
t = perm[ d ];
perm[ d ] = z;
c = ( ( a[ t ] ) >>> shift & DIGIT_MASK ^ signMask );
}
perm[ i ] = t;
}
if ( level < maxLevel && count[ c ] > 1 ) {
if ( count[ c ] < RADIXSORT_NO_REC ) insertionSortIndirect( perm, a, i, i + count[ c ] );
else {
offsetStack[ stackPos ] = i;
lengthStack[ stackPos ] = count[ c ];
levelStack[ stackPos++ ] = level + 1;
}
}
}
}
}
}
/** Sorts the specified range of an array using parallel indirect radix sort.
*
* <p>The sorting algorithm is a tuned radix sort adapted from Peter M. McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix sort”, <i>Computing Systems</i>, 6(1), pages
* 5−27 (1993).
*
* <p>This method implement an <em>indirect</em> sort. The elements of <code>perm</code> (which must be exactly the numbers in the interval <code>[0..perm.length)</code>) will be permuted so that
* <code>a[ perm[ i ] ] ≤ a[ perm[ i + 1 ] ]</code>.
*
* <p>This implementation uses a pool of {@link Runtime#availableProcessors()} threads.
*
* @param perm a permutation array indexing <code>a</code>.
* @param a the array to be sorted.
* @param from the index of the first element (inclusive) to be sorted.
* @param to the index of the last element (exclusive) to be sorted.
* @param stable whether the sorting algorithm should be stable. */
public static void parallelRadixSortIndirect( final int perm[], final byte[] a, final int from, final int to, final boolean stable ) {
if ( to - from < PARALLEL_RADIXSORT_NO_FORK ) {
radixSortIndirect( perm, a, from, to, stable );
return;
}
final int maxLevel = DIGITS_PER_ELEMENT - 1;
final LinkedBlockingQueue<Segment> queue = new LinkedBlockingQueue<Segment>();
queue.add( new Segment( from, to - from, 0 ) );
final AtomicInteger queueSize = new AtomicInteger( 1 );
final int numberOfThreads = Runtime.getRuntime().availableProcessors();
final ExecutorService executorService = Executors.newFixedThreadPool( numberOfThreads, Executors.defaultThreadFactory() );
final ExecutorCompletionService<Void> executorCompletionService = new ExecutorCompletionService<Void>( executorService );
final int[] support = stable ? new int[ perm.length ] : null;
for ( int i = numberOfThreads; i-- != 0; )
executorCompletionService.submit( new Callable<Void>() {
public Void call() throws Exception {
final int[] count = new int[ 1 << DIGIT_BITS ];
final int[] pos = new int[ 1 << DIGIT_BITS ];
for ( ;; ) {
if ( queueSize.get() == 0 ) for ( int i = numberOfThreads; i-- != 0; )
queue.add( POISON_PILL );
final Segment segment = queue.take();
if ( segment == POISON_PILL ) return null;
final int first = segment.offset;
final int length = segment.length;
final int level = segment.level;
final int signMask = level % DIGITS_PER_ELEMENT == 0 ? 1 << DIGIT_BITS - 1 : 0;
final int shift = ( DIGITS_PER_ELEMENT - 1 - level % DIGITS_PER_ELEMENT ) * DIGIT_BITS; // This is the shift that extract the right byte from a key
// Count keys.
for ( int i = first + length; i-- != first; )
count[ ( ( a[ perm[ i ] ] ) >>> shift & DIGIT_MASK ^ signMask ) ]++;
// Compute cumulative distribution
int lastUsed = -1;
for ( int i = 0, p = first; i < 1 << DIGIT_BITS; i++ ) {
if ( count[ i ] != 0 ) lastUsed = i;
pos[ i ] = ( p += count[ i ] );
}
if ( stable ) {
for ( int i = first + length; i-- != first; )
support[ --pos[ ( ( a[ perm[ i ] ] ) >>> shift & DIGIT_MASK ^ signMask ) ] ] = perm[ i ];
System.arraycopy( support, first, perm, first, length );
for ( int i = 0, p = first; i <= lastUsed; i++ ) {
if ( level < maxLevel && count[ i ] > 1 ) {
if ( count[ i ] < PARALLEL_RADIXSORT_NO_FORK ) radixSortIndirect( perm, a, p, p + count[ i ], stable );
else {
queueSize.incrementAndGet();
queue.add( new Segment( p, count[ i ], level + 1 ) );
}
}
p += count[ i ];
}
java.util.Arrays.fill( count, 0 );
}
else {
final int end = first + length - count[ lastUsed ];
// i moves through the start of each block
for ( int i = first, c = -1, d; i <= end; i += count[ c ], count[ c ] = 0 ) {
int t = perm[ i ];
c = ( ( a[ t ] ) >>> shift & DIGIT_MASK ^ signMask );
if ( i < end ) { // When all slots are OK, the last slot is necessarily OK.
while ( ( d = --pos[ c ] ) > i ) {
final int z = t;
t = perm[ d ];
perm[ d ] = z;
c = ( ( a[ t ] ) >>> shift & DIGIT_MASK ^ signMask );
}
perm[ i ] = t;
}
if ( level < maxLevel && count[ c ] > 1 ) {
if ( count[ c ] < PARALLEL_RADIXSORT_NO_FORK ) radixSortIndirect( perm, a, i, i + count[ c ], stable );
else {
queueSize.incrementAndGet();
queue.add( new Segment( i, count[ c ], level + 1 ) );
}
}
}
}
queueSize.decrementAndGet();
}
}
} );
Throwable problem = null;
for ( int i = numberOfThreads; i-- != 0; )
try {
executorCompletionService.take().get();
}
catch ( Exception e ) {
problem = e.getCause(); // We keep only the last one. They will be logged anyway.
}
executorService.shutdown();
if ( problem != null ) throw ( problem instanceof RuntimeException) ? (RuntimeException)problem : new RuntimeException( problem );
}
/** Sorts the specified array using parallel indirect radix sort.
*
* <p>The sorting algorithm is a tuned radix sort adapted from Peter M. McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix sort”, <i>Computing Systems</i>, 6(1), pages
* 5−27 (1993).
*
* <p>This method implement an <em>indirect</em> sort. The elements of <code>perm</code> (which must be exactly the numbers in the interval <code>[0..perm.length)</code>) will be permuted so that
* <code>a[ perm[ i ] ] ≤ a[ perm[ i + 1 ] ]</code>.
*
* <p>This implementation uses a pool of {@link Runtime#availableProcessors()} threads.
*
* @param perm a permutation array indexing <code>a</code>.
* @param a the array to be sorted.
* @param stable whether the sorting algorithm should be stable. */
public static void parallelRadixSortIndirect( final int perm[], final byte[] a, final boolean stable ) {
parallelRadixSortIndirect( perm, a, 0, a.length, stable );
}
/** Sorts the specified pair of arrays lexicographically using radix sort. <p>The sorting algorithm is a tuned radix sort adapted from Peter M. McIlroy, Keith Bostic and M. Douglas McIlroy,
* “Engineering radix sort”, <i>Computing Systems</i>, 6(1), pages 5−27 (1993).
*
* <p>This method implements a <em>lexicographical</em> sorting of the arguments. Pairs of elements in the same position in the two provided arrays will be considered a single key, and permuted
* accordingly. In the end, either <code>a[ i ] < a[ i + 1 ]</code> or <code>a[ i ] == a[ i + 1 ]</code> and <code>b[ i ] ≤ b[ i + 1 ]</code>.
*
* @param a the first array to be sorted.
* @param b the second array to be sorted. */
public static void radixSort( final byte[] a, final byte[] b ) {
ensureSameLength( a, b );
radixSort( a, b, 0, a.length );
}
/** Sorts the specified range of elements of two arrays using radix sort.
*
* <p>The sorting algorithm is a tuned radix sort adapted from Peter M. McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix sort”, <i>Computing Systems</i>, 6(1), pages
* 5−27 (1993).
*
* <p>This method implements a <em>lexicographical</em> sorting of the arguments. Pairs of elements in the same position in the two provided arrays will be considered a single key, and permuted
* accordingly. In the end, either <code>a[ i ] < a[ i + 1 ]</code> or <code>a[ i ] == a[ i + 1 ]</code> and <code>b[ i ] ≤ b[ i + 1 ]</code>.
*
* @param a the first array to be sorted.
* @param b the second array to be sorted.
* @param from the index of the first element (inclusive) to be sorted.
* @param to the index of the last element (exclusive) to be sorted. */
public static void radixSort( final byte[] a, final byte[] b, final int from, final int to ) {
if ( to - from < RADIXSORT_NO_REC ) {
selectionSort( a, b, from, to );
return;
}
final int layers = 2;
final int maxLevel = DIGITS_PER_ELEMENT * layers - 1;
final int stackSize = ( ( 1 << DIGIT_BITS ) - 1 ) * ( layers * DIGITS_PER_ELEMENT - 1 ) + 1;
int stackPos = 0;
final int[] offsetStack = new int[ stackSize ];
final int[] lengthStack = new int[ stackSize ];
final int[] levelStack = new int[ stackSize ];
offsetStack[ stackPos ] = from;
lengthStack[ stackPos ] = to - from;
levelStack[ stackPos++ ] = 0;
final int[] count = new int[ 1 << DIGIT_BITS ];
final int[] pos = new int[ 1 << DIGIT_BITS ];
while ( stackPos > 0 ) {
final int first = offsetStack[ --stackPos ];
final int length = lengthStack[ stackPos ];
final int level = levelStack[ stackPos ];
final int signMask = level % DIGITS_PER_ELEMENT == 0 ? 1 << DIGIT_BITS - 1 : 0;
final byte[] k = level < DIGITS_PER_ELEMENT ? a : b; // This is the key array
final int shift = ( DIGITS_PER_ELEMENT - 1 - level % DIGITS_PER_ELEMENT ) * DIGIT_BITS; // This is the shift that extract the right byte from a key
// Count keys.
for ( int i = first + length; i-- != first; )
count[ ( ( k[ i ] ) >>> shift & DIGIT_MASK ^ signMask ) ]++;
// Compute cumulative distribution
int lastUsed = -1;
for ( int i = 0, p = first; i < 1 << DIGIT_BITS; i++ ) {
if ( count[ i ] != 0 ) lastUsed = i;
pos[ i ] = ( p += count[ i ] );
}
final int end = first + length - count[ lastUsed ];
// i moves through the start of each block
for ( int i = first, c = -1, d; i <= end; i += count[ c ], count[ c ] = 0 ) {
byte t = a[ i ];
byte u = b[ i ];
c = ( ( k[ i ] ) >>> shift & DIGIT_MASK ^ signMask );
if ( i < end ) { // When all slots are OK, the last slot is necessarily OK.
while ( ( d = --pos[ c ] ) > i ) {
c = ( ( k[ d ] ) >>> shift & DIGIT_MASK ^ signMask );
byte z = t;
t = a[ d ];
a[ d ] = z;
z = u;
u = b[ d ];
b[ d ] = z;
}
a[ i ] = t;
b[ i ] = u;
}
if ( level < maxLevel && count[ c ] > 1 ) {
if ( count[ c ] < RADIXSORT_NO_REC ) selectionSort( a, b, i, i + count[ c ] );
else {
offsetStack[ stackPos ] = i;
lengthStack[ stackPos ] = count[ c ];
levelStack[ stackPos++ ] = level + 1;
}
}
}
}
}
/** Sorts the specified range of elements of two arrays using a parallel radix sort.
*
* <p>The sorting algorithm is a tuned radix sort adapted from Peter M. McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix sort”, <i>Computing Systems</i>, 6(1), pages
* 5−27 (1993).
*
* <p>This method implements a <em>lexicographical</em> sorting of the arguments. Pairs of elements in the same position in the two provided arrays will be considered a single key, and permuted
* accordingly. In the end, either <code>a[ i ] < a[ i + 1 ]</code> or <code>a[ i ] == a[ i + 1 ]</code> and <code>b[ i ] ≤ b[ i + 1 ]</code>.
*
* <p>This implementation uses a pool of {@link Runtime#availableProcessors()} threads.
*
* @param a the first array to be sorted.
* @param b the second array to be sorted.
* @param from the index of the first element (inclusive) to be sorted.
* @param to the index of the last element (exclusive) to be sorted. */
public static void parallelRadixSort( final byte[] a, final byte[] b, final int from, final int to ) {
if ( to - from < PARALLEL_RADIXSORT_NO_FORK ) {
quickSort( a, b, from, to );
return;
}
final int layers = 2;
if ( a.length != b.length ) throw new IllegalArgumentException( "Array size mismatch." );
final int maxLevel = DIGITS_PER_ELEMENT * layers - 1;
final LinkedBlockingQueue<Segment> queue = new LinkedBlockingQueue<Segment>();
queue.add( new Segment( from, to - from, 0 ) );
final AtomicInteger queueSize = new AtomicInteger( 1 );
final int numberOfThreads = Runtime.getRuntime().availableProcessors();
final ExecutorService executorService = Executors.newFixedThreadPool( numberOfThreads, Executors.defaultThreadFactory() );
final ExecutorCompletionService<Void> executorCompletionService = new ExecutorCompletionService<Void>( executorService );
for ( int i = numberOfThreads; i-- != 0; )
executorCompletionService.submit( new Callable<Void>() {
public Void call() throws Exception {
final int[] count = new int[ 1 << DIGIT_BITS ];
final int[] pos = new int[ 1 << DIGIT_BITS ];
for ( ;; ) {
if ( queueSize.get() == 0 ) for ( int i = numberOfThreads; i-- != 0; )
queue.add( POISON_PILL );
final Segment segment = queue.take();
if ( segment == POISON_PILL ) return null;
final int first = segment.offset;
final int length = segment.length;
final int level = segment.level;
final int signMask = level % DIGITS_PER_ELEMENT == 0 ? 1 << DIGIT_BITS - 1 : 0;
final byte[] k = level < DIGITS_PER_ELEMENT ? a : b; // This is the key array
final int shift = ( DIGITS_PER_ELEMENT - 1 - level % DIGITS_PER_ELEMENT ) * DIGIT_BITS;
// Count keys.
for ( int i = first + length; i-- != first; )
count[ ( ( k[ i ] ) >>> shift & DIGIT_MASK ^ signMask ) ]++;
// Compute cumulative distribution
int lastUsed = -1;
for ( int i = 0, p = first; i < 1 << DIGIT_BITS; i++ ) {
if ( count[ i ] != 0 ) lastUsed = i;
pos[ i ] = ( p += count[ i ] );
}
final int end = first + length - count[ lastUsed ];
for ( int i = first, c = -1, d; i <= end; i += count[ c ], count[ c ] = 0 ) {
byte t = a[ i ];
byte u = b[ i ];
c = ( ( k[ i ] ) >>> shift & DIGIT_MASK ^ signMask );
if ( i < end ) { // When all slots are OK, the last slot is necessarily OK.
while ( ( d = --pos[ c ] ) > i ) {
c = ( ( k[ d ] ) >>> shift & DIGIT_MASK ^ signMask );
final byte z = t;
final byte w = u;
t = a[ d ];
u = b[ d ];
a[ d ] = z;
b[ d ] = w;
}
a[ i ] = t;
b[ i ] = u;
}
if ( level < maxLevel && count[ c ] > 1 ) {
if ( count[ c ] < PARALLEL_RADIXSORT_NO_FORK ) quickSort( a, b, i, i + count[ c ] );
else {
queueSize.incrementAndGet();
queue.add( new Segment( i, count[ c ], level + 1 ) );
}
}
}
queueSize.decrementAndGet();
}
}
} );
Throwable problem = null;
for ( int i = numberOfThreads; i-- != 0; )
try {
executorCompletionService.take().get();
}
catch ( Exception e ) {
problem = e.getCause(); // We keep only the last one. They will be logged anyway.
}
executorService.shutdown();
if ( problem != null ) throw ( problem instanceof RuntimeException) ? (RuntimeException)problem : new RuntimeException( problem );
}
/** Sorts two arrays using a parallel radix sort.
*
* <p>The sorting algorithm is a tuned radix sort adapted from Peter M. McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix sort”, <i>Computing Systems</i>, 6(1), pages
* 5−27 (1993).
*
* <p>This method implements a <em>lexicographical</em> sorting of the arguments. Pairs of elements in the same position in the two provided arrays will be considered a single key, and permuted
* accordingly. In the end, either <code>a[ i ] < a[ i + 1 ]</code> or <code>a[ i ] == a[ i + 1 ]</code> and <code>b[ i ] ≤ b[ i + 1 ]</code>.
*
* <p>This implementation uses a pool of {@link Runtime#availableProcessors()} threads.
*
* @param a the first array to be sorted.
* @param b the second array to be sorted. */
public static void parallelRadixSort( final byte[] a, final byte[] b ) {
ensureSameLength( a, b );
parallelRadixSort( a, b, 0, a.length );
}
private static void insertionSortIndirect( final int[] perm, final byte[] a, final byte[] b, final int from, final int to ) {
for ( int i = from; ++i < to; ) {
int t = perm[ i ];
int j = i;
for ( int u = perm[ j - 1 ]; ( ( a[ t ] ) < ( a[ u ] ) ) || ( ( a[ t ] ) == ( a[ u ] ) ) && ( ( b[ t ] ) < ( b[ u ] ) ); u = perm[ --j - 1 ] ) {
perm[ j ] = u;
if ( from == j - 1 ) {
--j;
break;
}
}
perm[ j ] = t;
}
}
/** Sorts the specified pair of arrays lexicographically using indirect radix sort.
*
* <p>The sorting algorithm is a tuned radix sort adapted from Peter M. McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix sort”, <i>Computing Systems</i>, 6(1), pages
* 5−27 (1993).
*
* <p>This method implement an <em>indirect</em> sort. The elements of <code>perm</code> (which must be exactly the numbers in the interval <code>[0..perm.length)</code>) will be permuted so that
* <code>a[ perm[ i ] ] ≤ a[ perm[ i + 1 ] ]</code>.
*
* <p>This implementation will allocate, in the stable case, a further support array as large as <code>perm</code> (note that the stable version is slightly faster).
*
* @param perm a permutation array indexing <code>a</code>.
* @param a the array to be sorted.
* @param b the second array to be sorted.
* @param stable whether the sorting algorithm should be stable. */
public static void radixSortIndirect( final int[] perm, final byte[] a, final byte[] b, final boolean stable ) {
ensureSameLength( a, b );
radixSortIndirect( perm, a, b, 0, a.length, stable );
}
/** Sorts the specified pair of arrays lexicographically using indirect radix sort.
*
* <p>The sorting algorithm is a tuned radix sort adapted from Peter M. McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix sort”, <i>Computing Systems</i>, 6(1), pages
* 5−27 (1993).
*
* <p>This method implement an <em>indirect</em> sort. The elements of <code>perm</code> (which must be exactly the numbers in the interval <code>[0..perm.length)</code>) will be permuted so that
* <code>a[ perm[ i ] ] ≤ a[ perm[ i + 1 ] ]</code>.
*
* <p>This implementation will allocate, in the stable case, a further support array as large as <code>perm</code> (note that the stable version is slightly faster).
*
* @param perm a permutation array indexing <code>a</code>.
* @param a the array to be sorted.
* @param b the second array to be sorted.
* @param from the index of the first element of <code>perm</code> (inclusive) to be permuted.
* @param to the index of the last element of <code>perm</code> (exclusive) to be permuted.
* @param stable whether the sorting algorithm should be stable. */
public static void radixSortIndirect( final int[] perm, final byte[] a, final byte[] b, final int from, final int to, final boolean stable ) {
if ( to - from < RADIXSORT_NO_REC ) {
insertionSortIndirect( perm, a, b, from, to );
return;
}
final int layers = 2;
final int maxLevel = DIGITS_PER_ELEMENT * layers - 1;
final int stackSize = ( ( 1 << DIGIT_BITS ) - 1 ) * ( layers * DIGITS_PER_ELEMENT - 1 ) + 1;
int stackPos = 0;
final int[] offsetStack = new int[ stackSize ];
final int[] lengthStack = new int[ stackSize ];
final int[] levelStack = new int[ stackSize ];
offsetStack[ stackPos ] = from;
lengthStack[ stackPos ] = to - from;
levelStack[ stackPos++ ] = 0;
final int[] count = new int[ 1 << DIGIT_BITS ];
final int[] pos = new int[ 1 << DIGIT_BITS ];
final int[] support = stable ? new int[ perm.length ] : null;
while ( stackPos > 0 ) {
final int first = offsetStack[ --stackPos ];
final int length = lengthStack[ stackPos ];
final int level = levelStack[ stackPos ];
final int signMask = level % DIGITS_PER_ELEMENT == 0 ? 1 << DIGIT_BITS - 1 : 0;
final byte[] k = level < DIGITS_PER_ELEMENT ? a : b; // This is the key array
final int shift = ( DIGITS_PER_ELEMENT - 1 - level % DIGITS_PER_ELEMENT ) * DIGIT_BITS; // This is the shift that extract the right byte from a key
// Count keys.
for ( int i = first + length; i-- != first; )
count[ ( ( k[ perm[ i ] ] ) >>> shift & DIGIT_MASK ^ signMask ) ]++;
// Compute cumulative distribution
int lastUsed = -1;
for ( int i = 0, p = stable ? 0 : first; i < 1 << DIGIT_BITS; i++ ) {
if ( count[ i ] != 0 ) lastUsed = i;
pos[ i ] = ( p += count[ i ] );
}
if ( stable ) {
for ( int i = first + length; i-- != first; )
support[ --pos[ ( ( k[ perm[ i ] ] ) >>> shift & DIGIT_MASK ^ signMask ) ] ] = perm[ i ];
System.arraycopy( support, 0, perm, first, length );
for ( int i = 0, p = first; i < 1 << DIGIT_BITS; i++ ) {
if ( level < maxLevel && count[ i ] > 1 ) {
if ( count[ i ] < RADIXSORT_NO_REC ) insertionSortIndirect( perm, a, b, p, p + count[ i ] );
else {
offsetStack[ stackPos ] = p;
lengthStack[ stackPos ] = count[ i ];
levelStack[ stackPos++ ] = level + 1;
}
}
p += count[ i ];
}
java.util.Arrays.fill( count, 0 );
}
else {
final int end = first + length - count[ lastUsed ];
// i moves through the start of each block
for ( int i = first, c = -1, d; i <= end; i += count[ c ], count[ c ] = 0 ) {
int t = perm[ i ];
c = ( ( k[ t ] ) >>> shift & DIGIT_MASK ^ signMask );
if ( i < end ) { // When all slots are OK, the last slot is necessarily OK.
while ( ( d = --pos[ c ] ) > i ) {
final int z = t;
t = perm[ d ];
perm[ d ] = z;
c = ( ( k[ t ] ) >>> shift & DIGIT_MASK ^ signMask );
}
perm[ i ] = t;
}
if ( level < maxLevel && count[ c ] > 1 ) {
if ( count[ c ] < RADIXSORT_NO_REC ) insertionSortIndirect( perm, a, b, i, i + count[ c ] );
else {
offsetStack[ stackPos ] = i;
lengthStack[ stackPos ] = count[ c ];
levelStack[ stackPos++ ] = level + 1;
}
}
}
}
}
}
private static void selectionSort( final byte[][] a, final int from, final int to, final int level ) {
final int layers = a.length;
final int firstLayer = level / DIGITS_PER_ELEMENT;
for ( int i = from; i < to - 1; i++ ) {
int m = i;
for ( int j = i + 1; j < to; j++ ) {
for ( int p = firstLayer; p < layers; p++ ) {
if ( a[ p ][ j ] < a[ p ][ m ] ) {
m = j;
break;
}
else if ( a[ p ][ j ] > a[ p ][ m ] ) break;
}
}
if ( m != i ) {
for ( int p = layers; p-- != 0; ) {
final byte u = a[ p ][ i ];
a[ p ][ i ] = a[ p ][ m ];
a[ p ][ m ] = u;
}
}
}
}
/** Sorts the specified array of arrays lexicographically using radix sort.
*
* <p>The sorting algorithm is a tuned radix sort adapted from Peter M. McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix sort”, <i>Computing Systems</i>, 6(1), pages
* 5−27 (1993).
*
* <p>This method implements a <em>lexicographical</em> sorting of the provided arrays. Tuples of elements in the same position will be considered a single key, and permuted accordingly.
*
* @param a an array containing arrays of equal length to be sorted lexicographically in parallel. */
public static void radixSort( final byte[][] a ) {
radixSort( a, 0, a[ 0 ].length );
}
/** Sorts the specified array of arrays lexicographically using radix sort.
*
* <p>The sorting algorithm is a tuned radix sort adapted from Peter M. McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix sort”, <i>Computing Systems</i>, 6(1), pages
* 5−27 (1993).
*
* <p>This method implements a <em>lexicographical</em> sorting of the provided arrays. Tuples of elements in the same position will be considered a single key, and permuted accordingly.
*
* @param a an array containing arrays of equal length to be sorted lexicographically in parallel.
* @param from the index of the first element (inclusive) to be sorted.
* @param to the index of the last element (exclusive) to be sorted. */
public static void radixSort( final byte[][] a, final int from, final int to ) {
if ( to - from < RADIXSORT_NO_REC ) {
selectionSort( a, from, to, 0 );
return;
}
final int layers = a.length;
final int maxLevel = DIGITS_PER_ELEMENT * layers - 1;
for ( int p = layers, l = a[ 0 ].length; p-- != 0; )
if ( a[ p ].length != l ) throw new IllegalArgumentException( "The array of index " + p + " has not the same length of the array of index 0." );
final int stackSize = ( ( 1 << DIGIT_BITS ) - 1 ) * ( layers * DIGITS_PER_ELEMENT - 1 ) + 1;
int stackPos = 0;
final int[] offsetStack = new int[ stackSize ];
final int[] lengthStack = new int[ stackSize ];
final int[] levelStack = new int[ stackSize ];
offsetStack[ stackPos ] = from;
lengthStack[ stackPos ] = to - from;
levelStack[ stackPos++ ] = 0;
final int[] count = new int[ 1 << DIGIT_BITS ];
final int[] pos = new int[ 1 << DIGIT_BITS ];
final byte[] t = new byte[ layers ];
while ( stackPos > 0 ) {
final int first = offsetStack[ --stackPos ];
final int length = lengthStack[ stackPos ];
final int level = levelStack[ stackPos ];
final int signMask = level % DIGITS_PER_ELEMENT == 0 ? 1 << DIGIT_BITS - 1 : 0;
final byte[] k = a[ level / DIGITS_PER_ELEMENT ]; // This is the key array
final int shift = ( DIGITS_PER_ELEMENT - 1 - level % DIGITS_PER_ELEMENT ) * DIGIT_BITS; // This is the shift that extract the right byte from a key
// Count keys.
for ( int i = first + length; i-- != first; )
count[ ( ( k[ i ] ) >>> shift & DIGIT_MASK ^ signMask ) ]++;
// Compute cumulative distribution
int lastUsed = -1;
for ( int i = 0, p = first; i < 1 << DIGIT_BITS; i++ ) {
if ( count[ i ] != 0 ) lastUsed = i;
pos[ i ] = ( p += count[ i ] );
}
final int end = first + length - count[ lastUsed ];
// i moves through the start of each block
for ( int i = first, c = -1, d; i <= end; i += count[ c ], count[ c ] = 0 ) {
for ( int p = layers; p-- != 0; )
t[ p ] = a[ p ][ i ];
c = ( ( k[ i ] ) >>> shift & DIGIT_MASK ^ signMask );
if ( i < end ) { // When all slots are OK, the last slot is necessarily OK.
while ( ( d = --pos[ c ] ) > i ) {
c = ( ( k[ d ] ) >>> shift & DIGIT_MASK ^ signMask );
for ( int p = layers; p-- != 0; ) {
final byte u = t[ p ];
t[ p ] = a[ p ][ d ];
a[ p ][ d ] = u;
}
}
for ( int p = layers; p-- != 0; )
a[ p ][ i ] = t[ p ];
}
if ( level < maxLevel && count[ c ] > 1 ) {
if ( count[ c ] < RADIXSORT_NO_REC ) selectionSort( a, i, i + count[ c ], level + 1 );
else {
offsetStack[ stackPos ] = i;
lengthStack[ stackPos ] = count[ c ];
levelStack[ stackPos++ ] = level + 1;
}
}
}
}
}
/** Shuffles the specified array fragment using the specified pseudorandom number generator.
*
* @param a the array to be shuffled.
* @param from the index of the first element (inclusive) to be shuffled.
* @param to the index of the last element (exclusive) to be shuffled.
* @param random a pseudorandom number generator (please use a <a href="http://dsiutils.dsi.unimi.it/docs/it/unimi/dsi/util/XorShiftStarRandom.html">XorShift*</a> generator).
* @return <code>a</code>. */
public static byte[] shuffle( final byte[] a, final int from, final int to, final Random random ) {
for ( int i = to - from; i-- != 0; ) {
final int p = random.nextInt( i + 1 );
final byte t = a[ from + i ];
a[ from + i ] = a[ from + p ];
a[ from + p ] = t;
}
return a;
}
/** Shuffles the specified array using the specified pseudorandom number generator.
*
* @param a the array to be shuffled.
* @param random a pseudorandom number generator (please use a <a href="http://dsiutils.dsi.unimi.it/docs/it/unimi/dsi/util/XorShiftStarRandom.html">XorShift*</a> generator).
* @return <code>a</code>. */
public static byte[] shuffle( final byte[] a, final Random random ) {
for ( int i = a.length; i-- != 0; ) {
final int p = random.nextInt( i + 1 );
final byte t = a[ i ];
a[ i ] = a[ p ];
a[ p ] = t;
}
return a;
}
/** Reverses the order of the elements in the specified array.
*
* @param a the array to be reversed.
* @return <code>a</code>. */
public static byte[] reverse( final byte[] a ) {
final int length = a.length;
for ( int i = length / 2; i-- != 0; ) {
final byte t = a[ length - i - 1 ];
a[ length - i - 1 ] = a[ i ];
a[ i ] = t;
}
return a;
}
/** Reverses the order of the elements in the specified array fragment.
*
* @param a the array to be reversed.
* @param from the index of the first element (inclusive) to be reversed.
* @param to the index of the last element (exclusive) to be reversed.
* @return <code>a</code>. */
public static byte[] reverse( final byte[] a, final int from, final int to ) {
final int length = to - from;
for ( int i = length / 2; i-- != 0; ) {
final byte t = a[ from + length - i - 1 ];
a[ from + length - i - 1 ] = a[ from + i ];
a[ from + i ] = t;
}
return a;
}
/** A type-specific content-based hash strategy for arrays. */
private static final class ArrayHashStrategy implements Hash.Strategy<byte[]>, java.io.Serializable {
private static final long serialVersionUID = -7046029254386353129L;
public int hashCode( final byte[] o ) {
return java.util.Arrays.hashCode( o );
}
public boolean equals( final byte[] a, final byte[] b ) {
return java.util.Arrays.equals( a, b );
}
}
/** A type-specific content-based hash strategy for arrays.
*
* <P>This hash strategy may be used in custom hash collections whenever keys are arrays, and they must be considered equal by content. This strategy will handle <code>null</code> correctly, and
* it is serializable. */
public final static Hash.Strategy<byte[]> HASH_STRATEGY = new ArrayHashStrategy();
}
| tommyettinger/doughyo | src/main/java/vigna/fastutil/bytes/ByteArrays.java | Java | apache-2.0 | 104,967 |
/*
* Copyright 2017-2022 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.appmesh.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.appmesh.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* MeshSpec JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class MeshSpecJsonUnmarshaller implements Unmarshaller<MeshSpec, JsonUnmarshallerContext> {
public MeshSpec unmarshall(JsonUnmarshallerContext context) throws Exception {
MeshSpec meshSpec = new MeshSpec();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("egressFilter", targetDepth)) {
context.nextToken();
meshSpec.setEgressFilter(EgressFilterJsonUnmarshaller.getInstance().unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return meshSpec;
}
private static MeshSpecJsonUnmarshaller instance;
public static MeshSpecJsonUnmarshaller getInstance() {
if (instance == null)
instance = new MeshSpecJsonUnmarshaller();
return instance;
}
}
| aws/aws-sdk-java | aws-java-sdk-appmesh/src/main/java/com/amazonaws/services/appmesh/model/transform/MeshSpecJsonUnmarshaller.java | Java | apache-2.0 | 2,665 |
package com.evolveum.midpoint.model.api.context;
import com.evolveum.midpoint.xml.ns._public.common.common_3.NonceCredentialsPolicyType;
public class NonceAuthenticationContext extends AbstractAuthenticationContext {
private String nonce;
private NonceCredentialsPolicyType policy;
public NonceAuthenticationContext(String username, String nonce, NonceCredentialsPolicyType policy) {
super(username);
this.nonce = nonce;
this.policy = policy;
}
public String getNonce() {
return nonce;
}
public NonceCredentialsPolicyType getPolicy() {
return policy;
}
@Override
public Object getEnteredCredential() {
return getNonce();
}
}
| Pardus-Engerek/engerek | model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/NonceAuthenticationContext.java | Java | apache-2.0 | 658 |
/*
* 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.usergrid.mq;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import javax.xml.bind.annotation.XmlRootElement;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
@XmlRootElement
public class QueueSet {
List<QueueInfo> queues = new ArrayList<QueueInfo>();
boolean more;
public QueueSet() {
}
public List<QueueInfo> getQueues() {
return queues;
}
public void setQueues( List<QueueInfo> queues ) {
if ( queues == null ) {
queues = new ArrayList<QueueInfo>();
}
this.queues = queues;
}
public QueueSet addQueue( String queuePath, UUID queueId ) {
QueueInfo queue = new QueueInfo( queuePath, queueId );
queues.add( queue );
return this;
}
public boolean isMore() {
return more;
}
public void setMore( boolean more ) {
this.more = more;
}
public boolean hasMore() {
return more;
}
public int size() {
return queues.size();
}
@XmlRootElement
public static class QueueInfo {
String path;
UUID uuid;
public QueueInfo() {
}
public QueueInfo( String path, UUID uuid ) {
this.path = path;
this.uuid = uuid;
}
public String getPath() {
return path;
}
public void setPath( String path ) {
this.path = path;
}
public UUID getUuid() {
return uuid;
}
public void setUuid( UUID uuid ) {
this.uuid = uuid;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = ( prime * result ) + ( ( path == null ) ? 0 : path.hashCode() );
result = ( prime * result ) + ( ( uuid == null ) ? 0 : uuid.hashCode() );
return result;
}
@Override
public boolean equals( Object obj ) {
if ( this == obj ) {
return true;
}
if ( obj == null ) {
return false;
}
if ( getClass() != obj.getClass() ) {
return false;
}
QueueInfo other = ( QueueInfo ) obj;
if ( path == null ) {
if ( other.path != null ) {
return false;
}
}
else if ( !path.equals( other.path ) ) {
return false;
}
if ( uuid == null ) {
if ( other.uuid != null ) {
return false;
}
}
else if ( !uuid.equals( other.uuid ) ) {
return false;
}
return true;
}
@Override
public String toString() {
return "QueueInfo [path=" + path + ", uuid=" + uuid + "]";
}
}
public void setCursorToLastResult() {
// TODO Auto-generated method stub
}
@JsonSerialize(include = Inclusion.NON_NULL)
public Object getCursor() {
// TODO Auto-generated method stub
return null;
}
public void and( QueueSet r ) {
Set<QueueInfo> oldSet = new HashSet<QueueInfo>( queues );
List<QueueInfo> newList = new ArrayList<QueueInfo>();
for ( QueueInfo q : r.getQueues() ) {
if ( oldSet.contains( q ) ) {
newList.add( q );
}
}
queues = newList;
}
}
| mesosphere/usergrid | stack/core/src/main/java/org/apache/usergrid/mq/QueueSet.java | Java | apache-2.0 | 4,495 |
// Copyright 2011 Google Inc. 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.enterprise.adaptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.text.MessageFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;
/**
* Custom log formatter for ease of development. It is specifically targeted to
* use in console output and is able to produce color output on Unix terminals.
*/
public class CustomFormatter extends Formatter {
private Date date = new Date();
// The format for a color is '\x1b[30;40m' where 30 and 40 are the foreground
// and background colors, respectively. The ';' isn't required. If you don't
// provide a foreground or background, it will be set to the default.
private MessageFormat formatter = new MessageFormat(
"\u001b[3{5}m{0,date,MM-dd HH:mm:ss.SSS}"
+ " \u001b[3{6}m{1}\u001b[3{5}m {2} {3}:\u001b[m {4}");
/** Is identical to {@link #formatter} except for colors */
private MessageFormat noColorFormatter = new MessageFormat(
"{0,date,MM-dd HH:mm:ss.SSS} {1} {2} {3}: {4}");
private StringBuffer buffer = new StringBuffer();
private PrintWriter writer = new PrintWriter(new StringBufferWriter(buffer));
/**
* Flag for whether color escapes should be used. Defaults to false on
* Windows and true on all other platforms. Can be overridden with the
* {@code com.google.enterprise.adaptor.CustomFormatter.useColor} logging
* configuration property.
*/
private boolean useColor = !System.getProperty("os.name").contains("Windows");
/**
* Default highlight color is a cyan on my terminal. This color needs to be
* readable on both light-on-dark and dark-on-light setups.
*/
private int highlightColor = 6;
/** Colors range from 30-37 for foreground and 40-47 for background */
private final int numberOfColors = 8;
public CustomFormatter() {
LogManager manager = LogManager.getLogManager();
String className = getClass().getName();
String value = manager.getProperty(className + ".useColor");
if (value != null) {
setUseColor(Boolean.parseBoolean(value));
}
}
private CustomFormatter(boolean useColor) {
setUseColor(useColor);
}
/** A CustomFormatter that forces the use of colors. */
public static class Color extends CustomFormatter {
public Color() {
super(true);
}
}
/** A CustomFormatter that does not use colors. */
public static class NoColor extends CustomFormatter {
public NoColor() {
super(false);
}
}
public synchronized String format(LogRecord record) {
buffer.delete(0, buffer.length());
date.setTime(record.getMillis());
String threadName;
if (record.getThreadID() == Thread.currentThread().getId()) {
threadName = Thread.currentThread().getName();
} else {
threadName = "" + record.getThreadID();
}
// We know that one of the colors is used for the background. The default
// for terminals is 40, so we avoid using color 30 here.
int threadColor = (record.getThreadID() % (numberOfColors - 1)) + 1;
String method = record.getSourceClassName() + "."
+ record.getSourceMethodName() + "()";
if (method.length() > 30) {
method = method.substring(method.length() - 30);
}
getActiveFormat().format(
new Object[] {date, threadName, method,
record.getLevel().getLocalizedName(), formatMessage(record),
highlightColor, threadColor
}, buffer, null);
buffer.append(System.getProperty("line.separator"));
if (record.getThrown() != null) {
record.getThrown().printStackTrace(writer);
}
String formatted = buffer.toString();
buffer.delete(0, buffer.length());
return formatted;
}
private MessageFormat getActiveFormat() {
return useColor ? formatter : noColorFormatter;
}
public boolean isUseColor() {
return useColor;
}
public void setUseColor(boolean useColor) {
this.useColor = useColor;
}
private static class StringBufferWriter extends Writer {
private StringBuffer sb;
public StringBufferWriter(StringBuffer sb) {
this.sb = sb;
}
public void close() {
sb = null;
}
public void flush() throws IOException {
if (sb == null) {
throw new IOException("Writer closed");
}
}
public void write(char[] cbuf, int off, int len) throws IOException {
if (sb == null) {
throw new IOException("Writer closed");
}
sb.append(cbuf, off, len);
}
}
}
| googlegsa/library | src/com/google/enterprise/adaptor/CustomFormatter.java | Java | apache-2.0 | 5,184 |
/*
* Copyright 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 software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.enhanced.dynamodb.Document;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.client.DefaultDynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.TransactGetItemsEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
public class AsyncTransactGetItemsTest extends LocalDynamoDbAsyncTestBase {
private static class Record1 {
private Integer id;
private Integer getId() {
return id;
}
private Record1 setId(Integer id) {
this.id = id;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record1 record1 = (Record1) o;
return Objects.equals(id, record1.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
private static class Record2 {
private Integer id;
private Integer getId() {
return id;
}
private Record2 setId(Integer id) {
this.id = id;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record2 record2 = (Record2) o;
return Objects.equals(id, record2.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
private static final TableSchema<Record1> TABLE_SCHEMA_1 =
StaticTableSchema.builder(Record1.class)
.newItemSupplier(Record1::new)
.addAttribute(Integer.class, a -> a.name("id_1")
.getter(Record1::getId)
.setter(Record1::setId)
.tags(primaryPartitionKey()))
.build();
private static final TableSchema<Record2> TABLE_SCHEMA_2 =
StaticTableSchema.builder(Record2.class)
.newItemSupplier(Record2::new)
.addAttribute(Integer.class, a -> a.name("id_2")
.getter(Record2::getId)
.setter(Record2::setId)
.tags(primaryPartitionKey()))
.build();
private DynamoDbEnhancedAsyncClient enhancedAsyncClient =
DefaultDynamoDbEnhancedAsyncClient.builder()
.dynamoDbClient(getDynamoDbAsyncClient())
.build();
private DynamoDbAsyncTable<Record1> mappedTable1 = enhancedAsyncClient.table(getConcreteTableName("table-name-1"),
TABLE_SCHEMA_1);
private DynamoDbAsyncTable<Record2> mappedTable2 = enhancedAsyncClient.table(getConcreteTableName("table-name-2"),
TABLE_SCHEMA_2);
private static final List<Record1> RECORDS_1 =
IntStream.range(0, 2)
.mapToObj(i -> new Record1().setId(i))
.collect(Collectors.toList());
private static final List<Record2> RECORDS_2 =
IntStream.range(0, 2)
.mapToObj(i -> new Record2().setId(i))
.collect(Collectors.toList());
@Before
public void createTable() {
mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join();
mappedTable2.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join();
}
@After
public void deleteTable() {
getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name-1"))
.build()).join();
getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name-2"))
.build()).join();
}
private void insertRecords() {
RECORDS_1.forEach(record -> mappedTable1.putItem(r -> r.item(record)).join());
RECORDS_2.forEach(record -> mappedTable2.putItem(r -> r.item(record)).join());
}
@Test
public void getRecordsFromMultipleTables() {
insertRecords();
TransactGetItemsEnhancedRequest transactGetItemsEnhancedRequest =
TransactGetItemsEnhancedRequest.builder()
.addGetItem(mappedTable1, Key.builder().partitionValue(0).build())
.addGetItem(mappedTable2, Key.builder().partitionValue(0).build())
.addGetItem(mappedTable2, Key.builder().partitionValue(1).build())
.addGetItem(mappedTable1, Key.builder().partitionValue(1).build())
.build();
List<Document> results = enhancedAsyncClient.transactGetItems(transactGetItemsEnhancedRequest).join();
assertThat(results.size(), is(4));
assertThat(results.get(0).getItem(mappedTable1), is(RECORDS_1.get(0)));
assertThat(results.get(1).getItem(mappedTable2), is(RECORDS_2.get(0)));
assertThat(results.get(2).getItem(mappedTable2), is(RECORDS_2.get(1)));
assertThat(results.get(3).getItem(mappedTable1), is(RECORDS_1.get(1)));
}
@Test
public void notFoundRecordReturnsNull() {
insertRecords();
TransactGetItemsEnhancedRequest transactGetItemsEnhancedRequest =
TransactGetItemsEnhancedRequest.builder()
.addGetItem(mappedTable1, Key.builder().partitionValue(0).build())
.addGetItem(mappedTable2, Key.builder().partitionValue(0).build())
.addGetItem(mappedTable2, Key.builder().partitionValue(5).build())
.addGetItem(mappedTable1, Key.builder().partitionValue(1).build())
.build();
List<Document> results = enhancedAsyncClient.transactGetItems(transactGetItemsEnhancedRequest).join();
assertThat(results.size(), is(4));
assertThat(results.get(0).getItem(mappedTable1), is(RECORDS_1.get(0)));
assertThat(results.get(1).getItem(mappedTable2), is(RECORDS_2.get(0)));
assertThat(results.get(2).getItem(mappedTable2), is(nullValue()));
assertThat(results.get(3).getItem(mappedTable1), is(RECORDS_1.get(1)));
}
}
| aws/aws-sdk-java-v2 | services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncTransactGetItemsTest.java | Java | apache-2.0 | 8,610 |
/*
* 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.gobblin.dataset;
import org.testng.Assert;
import org.testng.annotations.Test;
public class DescriptorTest {
@Test
public void testDatasetDescriptor() {
DatasetDescriptor dataset = new DatasetDescriptor("hdfs", "/data/tracking/PageViewEvent");
dataset.addMetadata("fsUri", "hdfs://test.com:2018");
DatasetDescriptor copy = dataset.copy();
Assert.assertEquals(copy.getName(), dataset.getName());
Assert.assertEquals(copy.getPlatform(), dataset.getPlatform());
Assert.assertEquals(copy.getMetadata(), dataset.getMetadata());
Assert.assertEquals(dataset, copy);
Assert.assertEquals(dataset.hashCode(), copy.hashCode());
}
@Test
public void testPartitionDescriptor() {
DatasetDescriptor dataset = new DatasetDescriptor("hdfs", "/data/tracking/PageViewEvent");
String partitionName = "hourly/2018/08/14/18";
PartitionDescriptor partition = new PartitionDescriptor(partitionName, dataset);
// Test copy with new dataset
DatasetDescriptor dataset2 = new DatasetDescriptor("hive", "/data/tracking/PageViewEvent");
Descriptor partition2 = partition.copyWithNewDataset(dataset2);
Assert.assertEquals(partition2.getName(), partition.getName());
Assert.assertEquals(((PartitionDescriptor)partition2).getDataset(), dataset2);
// Test copy
PartitionDescriptor partition3 = partition.copy();
Assert.assertEquals(partition3.getDataset(), dataset);
Assert.assertEquals(partition3.getName(), partitionName);
}
}
| ibuenros/gobblin | gobblin-api/src/test/java/org/apache/gobblin/dataset/DescriptorTest.java | Java | apache-2.0 | 2,315 |
/*
* Copyright 2015 Delft University of Technology
*
* 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 science.atlarge.granula.modeller.platform.operation;
import science.atlarge.granula.modeller.Type;
import science.atlarge.granula.modeller.rule.derivation.ColorDerivation;
import science.atlarge.granula.modeller.rule.derivation.FilialCompletenessDerivation;
import science.atlarge.granula.modeller.rule.derivation.SimpleSummaryDerivation;
import science.atlarge.granula.modeller.rule.derivation.time.DurationDerivation;
import science.atlarge.granula.modeller.rule.derivation.time.JobEndTimeDerivation;
import science.atlarge.granula.modeller.rule.derivation.time.SiblingStartTimeDerivation;
import science.atlarge.granula.modeller.rule.linking.UniqueParentLinking;
public class PowergraphCleanup extends AbstractOperationModel {
public PowergraphCleanup() {
super(Type.PowerGraph, Type.Cleanup);
}
public void loadRules() {
super.loadRules();
addLinkingRule(new UniqueParentLinking(Type.PowerGraph, Type.Job));
addInfoDerivation(new SiblingStartTimeDerivation(5, Type.PowerGraph, Type.OffloadGraph));
addInfoDerivation(new JobEndTimeDerivation(1));
addInfoDerivation(new DurationDerivation(6));
this.addInfoDerivation(new FilialCompletenessDerivation(2));
String summary = "Prepare.";
addInfoDerivation(new SimpleSummaryDerivation(11, summary));
addInfoDerivation(new ColorDerivation(11, "#666"));
}
}
| tudelft-atlarge/graphalytics-platforms-powergraph | src/main/java/science/atlarge/granula/modeller/platform/operation/PowergraphCleanup.java | Java | apache-2.0 | 2,036 |
package testcase.result;
import com.alibaba.fastjson.annotation.JSONField;
import elong.HotelList;
public class HotelListResult extends BaseResult {
@JSONField(name="Result")
private HotelList result;
public HotelList getResult() {
return result;
}
public void setResult(HotelList result) {
this.result = result;
}
}
| leonmaybe/eLong-OpenAPI-JAVA-demo | src/testcase/result/HotelListResult.java | Java | apache-2.0 | 361 |
package com.vtapadia.experiments.web;
import com.vtapadia.experiments.domain.User;
import com.vtapadia.experiments.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.UriComponentsBuilder;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@RestController
@RequestMapping(value = "users")
public class UserController {
private UserRepository userRepository;
@Autowired
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@RequestMapping(method = RequestMethod.GET)
public List<User> getUsers() {
return userRepository.findAll();
}
@RequestMapping(path = "{userId}", method = RequestMethod.GET)
public User getUser(@PathVariable("userId") Long userId) {
return userRepository.findOne(userId);
}
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> add(
@Validated @RequestBody User user
) {
HttpServletRequest curRequest =
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();
User entity = userRepository.saveAndFlush(user);
if (entity != null && entity.getId() != null) {
return ResponseEntity
.created(UriComponentsBuilder
.fromHttpUrl(curRequest.getRequestURL().toString())
.pathSegment(entity.getId().toString())
.build().toUri())
.build();
} else {
return ResponseEntity.badRequest().body("Failed to create user");
}
}
}
| vtapadia/springPlayground | src/main/java/com/vtapadia/experiments/web/UserController.java | Java | apache-2.0 | 2,045 |
/* -----------------------------------------------------------------------------
* Rule_cmdRemFloat2addr.java
* -----------------------------------------------------------------------------
*
* Producer : com.parse2.aparse.Parser 2.3
* Produced : Fri Apr 12 10:40:21 MUT 2013
*
* -----------------------------------------------------------------------------
*/
package com.litecoding.smali2java.parser.cmd.rem;
import java.util.ArrayList;
import com.litecoding.smali2java.builder.Visitor;
import com.litecoding.smali2java.parser.ParserContext;
import com.litecoding.smali2java.parser.Rule;
import com.litecoding.smali2java.parser.Terminal_StringValue;
import com.litecoding.smali2java.parser.smali.Rule_codeRegister;
import com.litecoding.smali2java.parser.smali.Rule_codeRegisterVDst;
import com.litecoding.smali2java.parser.smali.Rule_commentSequence;
import com.litecoding.smali2java.parser.smali.Rule_listSeparator;
import com.litecoding.smali2java.parser.smali.Rule_optPadding;
import com.litecoding.smali2java.parser.smali.Rule_padding;
import com.litecoding.smali2java.parser.text.Rule_CRLF;
final public class Rule_cmdRemFloat2addr extends Rule
{
private Rule_cmdRemFloat2addr(String spelling, ArrayList<Rule> rules)
{
super(spelling, rules);
}
public Object accept(Visitor visitor)
{
return visitor.visit(this);
}
public static Rule_cmdRemFloat2addr parse(ParserContext context)
{
context.push("cmdRemFloat2addr");
boolean parsed = true;
int s0 = context.index;
ArrayList<Rule> e0 = new ArrayList<Rule>();
Rule rule;
parsed = false;
if (!parsed)
{
{
ArrayList<Rule> e1 = new ArrayList<Rule>();
int s1 = context.index;
parsed = true;
if (parsed)
{
boolean f1 = true;
int c1 = 0;
for (int i1 = 0; i1 < 1 && f1; i1++)
{
rule = Rule_optPadding.parse(context);
if ((f1 = rule != null))
{
e1.add(rule);
c1++;
}
}
parsed = c1 == 1;
}
if (parsed)
{
boolean f1 = true;
int c1 = 0;
for (int i1 = 0; i1 < 1 && f1; i1++)
{
rule = Terminal_StringValue.parse(context, "rem-float/2addr");
if ((f1 = rule != null))
{
e1.add(rule);
c1++;
}
}
parsed = c1 == 1;
}
if (parsed)
{
boolean f1 = true;
int c1 = 0;
for (int i1 = 0; i1 < 1 && f1; i1++)
{
rule = Rule_padding.parse(context);
if ((f1 = rule != null))
{
e1.add(rule);
c1++;
}
}
parsed = c1 == 1;
}
if (parsed)
{
boolean f1 = true;
int c1 = 0;
for (int i1 = 0; i1 < 1 && f1; i1++)
{
rule = Rule_codeRegisterVDst.parse(context);
if ((f1 = rule != null))
{
e1.add(rule);
c1++;
}
}
parsed = c1 == 1;
}
if (parsed)
{
boolean f1 = true;
int c1 = 0;
for (int i1 = 0; i1 < 1 && f1; i1++)
{
rule = Rule_listSeparator.parse(context);
if ((f1 = rule != null))
{
e1.add(rule);
c1++;
}
}
parsed = c1 == 1;
}
if (parsed)
{
boolean f1 = true;
int c1 = 0;
for (int i1 = 0; i1 < 1 && f1; i1++)
{
rule = Rule_codeRegister.parse(context);
if ((f1 = rule != null))
{
e1.add(rule);
c1++;
}
}
parsed = c1 == 1;
}
if (parsed)
{
boolean f1 = true;
int c1 = 0;
for (int i1 = 0; i1 < 1 && f1; i1++)
{
rule = Rule_optPadding.parse(context);
if ((f1 = rule != null))
{
e1.add(rule);
c1++;
}
}
parsed = c1 == 1;
}
if (parsed)
{
boolean f1 = true;
@SuppressWarnings("unused")
int c1 = 0;
for (int i1 = 0; i1 < 1 && f1; i1++)
{
int g1 = context.index;
parsed = false;
if (!parsed)
{
{
ArrayList<Rule> e2 = new ArrayList<Rule>();
int s2 = context.index;
parsed = true;
if (parsed)
{
boolean f2 = true;
int c2 = 0;
for (int i2 = 0; i2 < 1 && f2; i2++)
{
rule = Rule_padding.parse(context);
if ((f2 = rule != null))
{
e2.add(rule);
c2++;
}
}
parsed = c2 == 1;
}
if (parsed)
{
boolean f2 = true;
int c2 = 0;
for (int i2 = 0; i2 < 1 && f2; i2++)
{
rule = Rule_commentSequence.parse(context);
if ((f2 = rule != null))
{
e2.add(rule);
c2++;
}
}
parsed = c2 == 1;
}
if (parsed)
e1.addAll(e2);
else
context.index = s2;
}
}
f1 = context.index > g1;
if (parsed) c1++;
}
parsed = true;
}
if (parsed)
{
boolean f1 = true;
int c1 = 0;
for (int i1 = 0; i1 < 1 && f1; i1++)
{
rule = Rule_CRLF.parse(context);
if ((f1 = rule != null))
{
e1.add(rule);
c1++;
}
}
parsed = c1 == 1;
}
if (parsed)
e0.addAll(e1);
else
context.index = s1;
}
}
rule = null;
if (parsed)
rule = new Rule_cmdRemFloat2addr(context.text.substring(s0, context.index), e0);
else
context.index = s0;
context.pop("cmdRemFloat2addr", parsed);
return (Rule_cmdRemFloat2addr)rule;
}
}
/* -----------------------------------------------------------------------------
* eof
* -----------------------------------------------------------------------------
*/
| Crysty-Yui/smali2java | src/main/java/com/litecoding/smali2java/parser/cmd/rem/Rule_cmdRemFloat2addr.java | Java | apache-2.0 | 6,769 |
/*
* 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.recovery;
import org.apache.lucene.store.RateLimiter;
import org.apache.lucene.store.RateLimiter.SimpleRateLimiter;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;
public class RecoverySettings extends AbstractComponent {
public static final Setting<ByteSizeValue> INDICES_RECOVERY_MAX_BYTES_PER_SEC_SETTING =
Setting.byteSizeSetting("indices.recovery.max_bytes_per_sec", new ByteSizeValue(40, ByteSizeUnit.MB),
Property.Dynamic, Property.NodeScope);
/**
* how long to wait before retrying after issues cause by cluster state syncing between nodes
* i.e., local node is not yet known on remote node, remote shard not yet started etc.
*/
public static final Setting<TimeValue> INDICES_RECOVERY_RETRY_DELAY_STATE_SYNC_SETTING =
Setting.positiveTimeSetting("indices.recovery.retry_delay_state_sync", TimeValue.timeValueMillis(500),
Property.Dynamic, Property.NodeScope);
/** how long to wait before retrying after network related issues */
public static final Setting<TimeValue> INDICES_RECOVERY_RETRY_DELAY_NETWORK_SETTING =
Setting.positiveTimeSetting("indices.recovery.retry_delay_network", TimeValue.timeValueSeconds(5),
Property.Dynamic, Property.NodeScope);
/** timeout value to use for requests made as part of the recovery process */
public static final Setting<TimeValue> INDICES_RECOVERY_INTERNAL_ACTION_TIMEOUT_SETTING =
Setting.positiveTimeSetting("indices.recovery.internal_action_timeout", TimeValue.timeValueMinutes(15),
Property.Dynamic, Property.NodeScope);
/**
* timeout value to use for requests made as part of the recovery process that are expected to take long time.
* defaults to twice `indices.recovery.internal_action_timeout`.
*/
public static final Setting<TimeValue> INDICES_RECOVERY_INTERNAL_LONG_ACTION_TIMEOUT_SETTING =
Setting.timeSetting("indices.recovery.internal_action_long_timeout",
(s) -> TimeValue.timeValueMillis(INDICES_RECOVERY_INTERNAL_ACTION_TIMEOUT_SETTING.get(s).millis() * 2),
TimeValue.timeValueSeconds(0), Property.Dynamic, Property.NodeScope);
/**
* recoveries that don't show any activity for more then this interval will be failed.
* defaults to `indices.recovery.internal_action_long_timeout`
*/
public static final Setting<TimeValue> INDICES_RECOVERY_ACTIVITY_TIMEOUT_SETTING =
Setting.timeSetting("indices.recovery.recovery_activity_timeout",
INDICES_RECOVERY_INTERNAL_LONG_ACTION_TIMEOUT_SETTING::get, TimeValue.timeValueSeconds(0),
Property.Dynamic, Property.NodeScope);
public static final ByteSizeValue DEFAULT_CHUNK_SIZE = new ByteSizeValue(512, ByteSizeUnit.KB);
private volatile ByteSizeValue maxBytesPerSec;
private volatile SimpleRateLimiter rateLimiter;
private volatile TimeValue retryDelayStateSync;
private volatile TimeValue retryDelayNetwork;
private volatile TimeValue activityTimeout;
private volatile TimeValue internalActionTimeout;
private volatile TimeValue internalActionLongTimeout;
private volatile ByteSizeValue chunkSize = DEFAULT_CHUNK_SIZE;
@Inject
public RecoverySettings(Settings settings, ClusterSettings clusterSettings) {
super(settings);
this.retryDelayStateSync = INDICES_RECOVERY_RETRY_DELAY_STATE_SYNC_SETTING.get(settings);
// doesn't have to be fast as nodes are reconnected every 10s by default (see InternalClusterService.ReconnectToNodes)
// and we want to give the master time to remove a faulty node
this.retryDelayNetwork = INDICES_RECOVERY_RETRY_DELAY_NETWORK_SETTING.get(settings);
this.internalActionTimeout = INDICES_RECOVERY_INTERNAL_ACTION_TIMEOUT_SETTING.get(settings);
this.internalActionLongTimeout = INDICES_RECOVERY_INTERNAL_LONG_ACTION_TIMEOUT_SETTING.get(settings);
this.activityTimeout = INDICES_RECOVERY_ACTIVITY_TIMEOUT_SETTING.get(settings);
this.maxBytesPerSec = INDICES_RECOVERY_MAX_BYTES_PER_SEC_SETTING.get(settings);
if (maxBytesPerSec.getBytes() <= 0) {
rateLimiter = null;
} else {
rateLimiter = new SimpleRateLimiter(maxBytesPerSec.getMbFrac());
}
logger.debug("using max_bytes_per_sec[{}]", maxBytesPerSec);
clusterSettings.addSettingsUpdateConsumer(INDICES_RECOVERY_MAX_BYTES_PER_SEC_SETTING, this::setMaxBytesPerSec);
clusterSettings.addSettingsUpdateConsumer(INDICES_RECOVERY_RETRY_DELAY_STATE_SYNC_SETTING, this::setRetryDelayStateSync);
clusterSettings.addSettingsUpdateConsumer(INDICES_RECOVERY_RETRY_DELAY_NETWORK_SETTING, this::setRetryDelayNetwork);
clusterSettings.addSettingsUpdateConsumer(INDICES_RECOVERY_INTERNAL_ACTION_TIMEOUT_SETTING, this::setInternalActionTimeout);
clusterSettings.addSettingsUpdateConsumer(INDICES_RECOVERY_INTERNAL_LONG_ACTION_TIMEOUT_SETTING, this::setInternalActionLongTimeout);
clusterSettings.addSettingsUpdateConsumer(INDICES_RECOVERY_ACTIVITY_TIMEOUT_SETTING, this::setActivityTimeout);
}
public RateLimiter rateLimiter() {
return rateLimiter;
}
public TimeValue retryDelayNetwork() {
return retryDelayNetwork;
}
public TimeValue retryDelayStateSync() {
return retryDelayStateSync;
}
public TimeValue activityTimeout() {
return activityTimeout;
}
public TimeValue internalActionTimeout() {
return internalActionTimeout;
}
public TimeValue internalActionLongTimeout() {
return internalActionLongTimeout;
}
public ByteSizeValue getChunkSize() { return chunkSize; }
void setChunkSize(ByteSizeValue chunkSize) { // only settable for tests
if (chunkSize.bytesAsInt() <= 0) {
throw new IllegalArgumentException("chunkSize must be > 0");
}
this.chunkSize = chunkSize;
}
public void setRetryDelayStateSync(TimeValue retryDelayStateSync) {
this.retryDelayStateSync = retryDelayStateSync;
}
public void setRetryDelayNetwork(TimeValue retryDelayNetwork) {
this.retryDelayNetwork = retryDelayNetwork;
}
public void setActivityTimeout(TimeValue activityTimeout) {
this.activityTimeout = activityTimeout;
}
public void setInternalActionTimeout(TimeValue internalActionTimeout) {
this.internalActionTimeout = internalActionTimeout;
}
public void setInternalActionLongTimeout(TimeValue internalActionLongTimeout) {
this.internalActionLongTimeout = internalActionLongTimeout;
}
private void setMaxBytesPerSec(ByteSizeValue maxBytesPerSec) {
this.maxBytesPerSec = maxBytesPerSec;
if (maxBytesPerSec.getBytes() <= 0) {
rateLimiter = null;
} else if (rateLimiter != null) {
rateLimiter.setMBPerSec(maxBytesPerSec.getMbFrac());
} else {
rateLimiter = new SimpleRateLimiter(maxBytesPerSec.getMbFrac());
}
}
}
| ricardocerq/elasticsearch | core/src/main/java/org/elasticsearch/indices/recovery/RecoverySettings.java | Java | apache-2.0 | 8,309 |
/*
* 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.yarn;
import org.apache.flink.client.cli.CliArgsException;
import org.apache.flink.client.cli.CliFrontend;
import org.apache.flink.client.cli.CliFrontendParser;
import org.apache.flink.client.cli.CustomCommandLine;
import org.apache.flink.client.cli.GenericCLI;
import org.apache.flink.client.deployment.ClusterClientFactory;
import org.apache.flink.client.deployment.ClusterClientServiceLoader;
import org.apache.flink.client.deployment.ClusterSpecification;
import org.apache.flink.client.deployment.DefaultClusterClientServiceLoader;
import org.apache.flink.configuration.AkkaOptions;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.CoreOptions;
import org.apache.flink.configuration.DeploymentOptions;
import org.apache.flink.configuration.HighAvailabilityOptions;
import org.apache.flink.configuration.JobManagerOptions;
import org.apache.flink.configuration.MemorySize;
import org.apache.flink.configuration.SecurityOptions;
import org.apache.flink.configuration.TaskManagerOptions;
import org.apache.flink.util.FlinkException;
import org.apache.flink.util.TestLogger;
import org.apache.flink.yarn.cli.FlinkYarnSessionCli;
import org.apache.flink.yarn.configuration.YarnConfigOptions;
import org.apache.flink.yarn.executors.YarnJobClusterExecutor;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.List;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/**
* Tests for the {@link FlinkYarnSessionCli}.
*/
public class FlinkYarnSessionCliTest extends TestLogger {
private static final ApplicationId TEST_YARN_APPLICATION_ID = ApplicationId.newInstance(System.currentTimeMillis(), 42);
private static final ApplicationId TEST_YARN_APPLICATION_ID_2 = ApplicationId.newInstance(System.currentTimeMillis(), 43);
private static final String TEST_YARN_JOB_MANAGER_ADDRESS = "22.33.44.55";
private static final int TEST_YARN_JOB_MANAGER_PORT = 6655;
private static final String validPropertiesFile = "applicationID=" + TEST_YARN_APPLICATION_ID;
private static final String invalidPropertiesFile = "jasfobManager=" + TEST_YARN_JOB_MANAGER_ADDRESS + ":asf" + TEST_YARN_JOB_MANAGER_PORT;
@Rule
public TemporaryFolder tmp = new TemporaryFolder();
@Test
public void testDynamicProperties() throws Exception {
FlinkYarnSessionCli cli = new FlinkYarnSessionCli(
new Configuration(),
tmp.getRoot().getAbsolutePath(),
"",
"",
false);
Options options = new Options();
cli.addGeneralOptions(options);
cli.addRunOptions(options);
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, new String[]{"run", "-j", "fake.jar",
"-D", AkkaOptions.ASK_TIMEOUT.key() + "=5 min",
"-D", CoreOptions.FLINK_JVM_OPTIONS.key() + "=-DappName=foobar",
"-D", SecurityOptions.SSL_INTERNAL_KEY_PASSWORD.key() + "=changeit"});
Configuration executorConfig = cli.applyCommandLineOptionsToConfiguration(cmd);
assertEquals("5 min", executorConfig.get(AkkaOptions.ASK_TIMEOUT));
assertEquals("-DappName=foobar", executorConfig.get(CoreOptions.FLINK_JVM_OPTIONS));
assertEquals("changeit", executorConfig.get(SecurityOptions.SSL_INTERNAL_KEY_PASSWORD));
}
@Test
public void testCorrectSettingOfMaxSlots() throws Exception {
String[] params =
new String[] {"-ys", "3"};
FlinkYarnSessionCli yarnCLI = createFlinkYarnSessionCliWithJmAndTmTotalMemory(2048);
final CommandLine commandLine = yarnCLI.parseCommandLineOptions(params, true);
final Configuration executorConfig = yarnCLI.applyCommandLineOptionsToConfiguration(commandLine);
final ClusterClientFactory<ApplicationId> clientFactory = getClusterClientFactory(executorConfig);
final ClusterSpecification clusterSpecification = clientFactory.getClusterSpecification(executorConfig);
// each task manager has 3 slots but the parallelism is 7. Thus the slots should be increased.
assertEquals(3, clusterSpecification.getSlotsPerTaskManager());
}
@Test
public void testCorrectSettingOfDetachedMode() throws Exception {
final String[] params = new String[] {"-yd"};
FlinkYarnSessionCli yarnCLI = createFlinkYarnSessionCli();
final CommandLine commandLine = yarnCLI.parseCommandLineOptions(params, true);
final Configuration executorConfig = yarnCLI.applyCommandLineOptionsToConfiguration(commandLine);
assertThat(executorConfig.get(DeploymentOptions.ATTACHED), is(false));
}
@Test
public void testZookeeperNamespaceProperty() throws Exception {
String zkNamespaceCliInput = "flink_test_namespace";
String[] params = new String[] {"-yz", zkNamespaceCliInput};
FlinkYarnSessionCli yarnCLI = createFlinkYarnSessionCli();
CommandLine commandLine = yarnCLI.parseCommandLineOptions(params, true);
Configuration executorConfig = yarnCLI.applyCommandLineOptionsToConfiguration(commandLine);
ClusterClientFactory<ApplicationId> clientFactory = getClusterClientFactory(executorConfig);
YarnClusterDescriptor descriptor = (YarnClusterDescriptor) clientFactory.createClusterDescriptor(executorConfig);
assertEquals(zkNamespaceCliInput, descriptor.getZookeeperNamespace());
}
@Test
public void testNodeLabelProperty() throws Exception {
String nodeLabelCliInput = "flink_test_nodelabel";
String[] params = new String[] {"-ynl", nodeLabelCliInput };
FlinkYarnSessionCli yarnCLI = createFlinkYarnSessionCli();
CommandLine commandLine = yarnCLI.parseCommandLineOptions(params, true);
Configuration executorConfig = yarnCLI.applyCommandLineOptionsToConfiguration(commandLine);
ClusterClientFactory<ApplicationId> clientFactory = getClusterClientFactory(executorConfig);
YarnClusterDescriptor descriptor = (YarnClusterDescriptor) clientFactory.createClusterDescriptor(executorConfig);
assertEquals(nodeLabelCliInput, descriptor.getNodeLabel());
}
@Test
public void testExecutorCLIisPrioritised() throws Exception {
final File directoryPath = writeYarnPropertiesFile(validPropertiesFile);
final Configuration configuration = new Configuration();
configuration.setString(YarnConfigOptions.PROPERTIES_FILE_LOCATION, directoryPath.getAbsolutePath());
validateYarnCLIisActive(configuration);
final String[] argsUnderTest = new String[] {"-e", YarnJobClusterExecutor.NAME};
validateExecutorCLIisPrioritised(configuration, argsUnderTest);
}
private void validateExecutorCLIisPrioritised(Configuration configuration, String[] argsUnderTest) throws IOException, CliArgsException {
final List<CustomCommandLine> customCommandLines = CliFrontend.loadCustomCommandLines(
configuration,
tmp.newFile().getAbsolutePath());
final CliFrontend cli = new CliFrontend(configuration, customCommandLines);
final CommandLine commandLine = cli.getCommandLine(
CliFrontendParser.getRunCommandOptions(),
argsUnderTest,
true);
final CustomCommandLine customCommandLine = cli.validateAndGetActiveCommandLine(commandLine);
assertTrue(customCommandLine instanceof GenericCLI);
}
private void validateYarnCLIisActive(Configuration configuration) throws FlinkException, CliArgsException {
final FlinkYarnSessionCli flinkYarnSessionCli = createFlinkYarnSessionCli(configuration);
final CommandLine testCLIArgs = flinkYarnSessionCli.parseCommandLineOptions(new String[] {}, true);
assertTrue(flinkYarnSessionCli.isActive(testCLIArgs));
}
/**
* Test that the CliFrontend is able to pick up the .yarn-properties file from a specified location.
*/
@Test
public void testResumeFromYarnPropertiesFile() throws Exception {
File directoryPath = writeYarnPropertiesFile(validPropertiesFile);
final Configuration configuration = new Configuration();
configuration.setString(YarnConfigOptions.PROPERTIES_FILE_LOCATION, directoryPath.getAbsolutePath());
final FlinkYarnSessionCli flinkYarnSessionCli = createFlinkYarnSessionCli(configuration);
final CommandLine commandLine = flinkYarnSessionCli.parseCommandLineOptions(new String[] {}, true);
final Configuration executorConfig = flinkYarnSessionCli.applyCommandLineOptionsToConfiguration(commandLine);
final ClusterClientFactory<ApplicationId> clientFactory = getClusterClientFactory(executorConfig);
final ApplicationId clusterId = clientFactory.getClusterId(executorConfig);
assertEquals(TEST_YARN_APPLICATION_ID, clusterId);
}
/**
* Tests that we fail when reading an invalid yarn properties file when retrieving
* the cluster id.
*/
@Test(expected = FlinkException.class)
public void testInvalidYarnPropertiesFile() throws Exception {
File directoryPath = writeYarnPropertiesFile(invalidPropertiesFile);
final Configuration configuration = new Configuration();
configuration.setString(YarnConfigOptions.PROPERTIES_FILE_LOCATION, directoryPath.getAbsolutePath());
createFlinkYarnSessionCli(configuration);
}
@Test
public void testResumeFromYarnID() throws Exception {
final FlinkYarnSessionCli flinkYarnSessionCli = createFlinkYarnSessionCli();
final CommandLine commandLine = flinkYarnSessionCli.parseCommandLineOptions(new String[] {"-yid", TEST_YARN_APPLICATION_ID.toString()}, true);
final Configuration executorConfig = flinkYarnSessionCli.applyCommandLineOptionsToConfiguration(commandLine);
final ClusterClientFactory<ApplicationId> clientFactory = getClusterClientFactory(executorConfig);
final ApplicationId clusterId = clientFactory.getClusterId(executorConfig);
assertEquals(TEST_YARN_APPLICATION_ID, clusterId);
}
@Test
public void testResumeFromYarnIDZookeeperNamespace() throws Exception {
final FlinkYarnSessionCli flinkYarnSessionCli = createFlinkYarnSessionCli();
final CommandLine commandLine = flinkYarnSessionCli.parseCommandLineOptions(new String[] {"-yid", TEST_YARN_APPLICATION_ID.toString()}, true);
final Configuration executorConfig = flinkYarnSessionCli.applyCommandLineOptionsToConfiguration(commandLine);
final ClusterClientFactory<ApplicationId> clientFactory = getClusterClientFactory(executorConfig);
final YarnClusterDescriptor clusterDescriptor = (YarnClusterDescriptor) clientFactory.createClusterDescriptor(executorConfig);
final Configuration clusterDescriptorConfiguration = clusterDescriptor.getFlinkConfiguration();
String zkNs = clusterDescriptorConfiguration.getValue(HighAvailabilityOptions.HA_CLUSTER_ID);
assertTrue(zkNs.matches("application_\\d+_0042"));
}
@Test
public void testResumeFromYarnIDZookeeperNamespaceOverride() throws Exception {
final FlinkYarnSessionCli flinkYarnSessionCli = createFlinkYarnSessionCli();
final String overrideZkNamespace = "my_cluster";
final CommandLine commandLine = flinkYarnSessionCli.parseCommandLineOptions(new String[] {"-yid", TEST_YARN_APPLICATION_ID.toString(), "-yz", overrideZkNamespace}, true);
final Configuration executorConfig = flinkYarnSessionCli.applyCommandLineOptionsToConfiguration(commandLine);
final ClusterClientFactory<ApplicationId> clientFactory = getClusterClientFactory(executorConfig);
final YarnClusterDescriptor clusterDescriptor = (YarnClusterDescriptor) clientFactory.createClusterDescriptor(executorConfig);
final Configuration clusterDescriptorConfiguration = clusterDescriptor.getFlinkConfiguration();
final String clusterId = clusterDescriptorConfiguration.getValue(HighAvailabilityOptions.HA_CLUSTER_ID);
assertEquals(overrideZkNamespace, clusterId);
}
@Test
public void testYarnIDOverridesPropertiesFile() throws Exception {
File directoryPath = writeYarnPropertiesFile(validPropertiesFile);
final Configuration configuration = new Configuration();
configuration.setString(YarnConfigOptions.PROPERTIES_FILE_LOCATION, directoryPath.getAbsolutePath());
final FlinkYarnSessionCli flinkYarnSessionCli = createFlinkYarnSessionCli(configuration);
final CommandLine commandLine = flinkYarnSessionCli.parseCommandLineOptions(new String[] {"-yid", TEST_YARN_APPLICATION_ID_2.toString() }, true);
final Configuration executorConfig = flinkYarnSessionCli.applyCommandLineOptionsToConfiguration(commandLine);
final ClusterClientFactory<ApplicationId> clientFactory = getClusterClientFactory(executorConfig);
final ApplicationId clusterId = clientFactory.getClusterId(executorConfig);
assertEquals(TEST_YARN_APPLICATION_ID_2, clusterId);
}
/**
* Tests that the command line arguments override the configuration settings
* when the {@link ClusterSpecification} is created.
*/
@Test
public void testCommandLineClusterSpecification() throws Exception {
final Configuration configuration = new Configuration();
final int jobManagerMemory = 1337;
final int taskManagerMemory = 7331;
final int slotsPerTaskManager = 30;
configuration.set(JobManagerOptions.TOTAL_PROCESS_MEMORY, MemorySize.ofMebiBytes(jobManagerMemory));
configuration.set(TaskManagerOptions.TOTAL_PROCESS_MEMORY, MemorySize.ofMebiBytes(taskManagerMemory));
configuration.setInteger(TaskManagerOptions.NUM_TASK_SLOTS, slotsPerTaskManager);
final String[] args = {"-yjm", String.valueOf(jobManagerMemory) + "m", "-ytm", String.valueOf(taskManagerMemory) + "m", "-ys", String.valueOf(slotsPerTaskManager)};
final FlinkYarnSessionCli flinkYarnSessionCli = createFlinkYarnSessionCli(configuration);
CommandLine commandLine = flinkYarnSessionCli.parseCommandLineOptions(args, false);
Configuration executorConfig = flinkYarnSessionCli.applyCommandLineOptionsToConfiguration(commandLine);
ClusterClientFactory<ApplicationId> clientFactory = getClusterClientFactory(executorConfig);
ClusterSpecification clusterSpecification = clientFactory.getClusterSpecification(executorConfig);
assertThat(clusterSpecification.getMasterMemoryMB(), is(jobManagerMemory));
assertThat(clusterSpecification.getTaskManagerMemoryMB(), is(taskManagerMemory));
assertThat(clusterSpecification.getSlotsPerTaskManager(), is(slotsPerTaskManager));
}
/**
* Tests that the configuration settings are used to create the
* {@link ClusterSpecification}.
*/
@Test
public void testConfigurationClusterSpecification() throws Exception {
final Configuration configuration = new Configuration();
final int jobManagerMemory = 1337;
configuration.set(JobManagerOptions.TOTAL_PROCESS_MEMORY, MemorySize.ofMebiBytes(jobManagerMemory));
final int taskManagerMemory = 7331;
configuration.set(TaskManagerOptions.TOTAL_PROCESS_MEMORY, MemorySize.ofMebiBytes(taskManagerMemory));
final int slotsPerTaskManager = 42;
configuration.setInteger(TaskManagerOptions.NUM_TASK_SLOTS, slotsPerTaskManager);
final String[] args = {};
final FlinkYarnSessionCli flinkYarnSessionCli = createFlinkYarnSessionCli(configuration);
CommandLine commandLine = flinkYarnSessionCli.parseCommandLineOptions(args, false);
Configuration executorConfig = flinkYarnSessionCli.applyCommandLineOptionsToConfiguration(commandLine);
ClusterClientFactory<ApplicationId> clientFactory = getClusterClientFactory(executorConfig);
ClusterSpecification clusterSpecification = clientFactory.getClusterSpecification(executorConfig);
assertThat(clusterSpecification.getMasterMemoryMB(), is(jobManagerMemory));
assertThat(clusterSpecification.getTaskManagerMemoryMB(), is(taskManagerMemory));
assertThat(clusterSpecification.getSlotsPerTaskManager(), is(slotsPerTaskManager));
}
/**
* Tests the specifying total process memory without unit for job manager and task manager.
*/
@Test
public void testMemoryPropertyWithoutUnit() throws Exception {
final String[] args = new String[] { "-yjm", "1024", "-ytm", "2048" };
final FlinkYarnSessionCli flinkYarnSessionCli = createFlinkYarnSessionCli();
final CommandLine commandLine = flinkYarnSessionCli.parseCommandLineOptions(args, false);
final Configuration executorConfig = flinkYarnSessionCli.applyCommandLineOptionsToConfiguration(commandLine);
final ClusterClientFactory<ApplicationId> clientFactory = getClusterClientFactory(executorConfig);
final ClusterSpecification clusterSpecification = clientFactory.getClusterSpecification(executorConfig);
assertThat(clusterSpecification.getMasterMemoryMB(), is(1024));
assertThat(clusterSpecification.getTaskManagerMemoryMB(), is(2048));
}
/**
* Tests the specifying total process memory with unit (MB) for job manager and task manager.
*/
@Test
public void testMemoryPropertyWithUnitMB() throws Exception {
final String[] args = new String[] { "-yjm", "1024m", "-ytm", "2048m" };
final FlinkYarnSessionCli flinkYarnSessionCli = createFlinkYarnSessionCli();
final CommandLine commandLine = flinkYarnSessionCli.parseCommandLineOptions(args, false);
final Configuration executorConfig = flinkYarnSessionCli.applyCommandLineOptionsToConfiguration(commandLine);
final ClusterClientFactory<ApplicationId> clientFactory = getClusterClientFactory(executorConfig);
final ClusterSpecification clusterSpecification = clientFactory.getClusterSpecification(executorConfig);
assertThat(clusterSpecification.getMasterMemoryMB(), is(1024));
assertThat(clusterSpecification.getTaskManagerMemoryMB(), is(2048));
}
/**
* Tests the specifying total process memory with arbitrary unit for job manager and task manager.
*/
@Test
public void testMemoryPropertyWithArbitraryUnit() throws Exception {
final String[] args = new String[] { "-yjm", "1g", "-ytm", "2g" };
final FlinkYarnSessionCli flinkYarnSessionCli = createFlinkYarnSessionCli();
final CommandLine commandLine = flinkYarnSessionCli.parseCommandLineOptions(args, false);
final Configuration executorConfig = flinkYarnSessionCli.applyCommandLineOptionsToConfiguration(commandLine);
final ClusterClientFactory<ApplicationId> clientFactory = getClusterClientFactory(executorConfig);
final ClusterSpecification clusterSpecification = clientFactory.getClusterSpecification(executorConfig);
assertThat(clusterSpecification.getMasterMemoryMB(), is(1024));
assertThat(clusterSpecification.getTaskManagerMemoryMB(), is(2048));
}
/**
* Tests the specifying heap memory with old config key for job manager and task manager.
*/
@Test
public void testHeapMemoryPropertyWithOldConfigKey() throws Exception {
Configuration configuration = new Configuration();
configuration.setInteger(JobManagerOptions.JOB_MANAGER_HEAP_MEMORY_MB, 2048);
configuration.setInteger(TaskManagerOptions.TASK_MANAGER_HEAP_MEMORY_MB, 4096);
final FlinkYarnSessionCli flinkYarnSessionCli = createFlinkYarnSessionCli(configuration);
final CommandLine commandLine = flinkYarnSessionCli.parseCommandLineOptions(new String[0], false);
final Configuration executorConfig = flinkYarnSessionCli.applyCommandLineOptionsToConfiguration(commandLine);
final ClusterClientFactory<ApplicationId> clientFactory = getClusterClientFactory(executorConfig);
final ClusterSpecification clusterSpecification = clientFactory.getClusterSpecification(executorConfig);
assertThat(clusterSpecification.getMasterMemoryMB(), is(2048));
assertThat(clusterSpecification.getTaskManagerMemoryMB(), is(4096));
}
/**
* Tests the specifying job manager total process memory with config default value for job manager and task manager.
*/
@Test
public void testJobManagerMemoryPropertyWithConfigDefaultValue() throws Exception {
int procMemory = 2048;
final FlinkYarnSessionCli flinkYarnSessionCli = createFlinkYarnSessionCliWithJmAndTmTotalMemory(procMemory);
final CommandLine commandLine = flinkYarnSessionCli.parseCommandLineOptions(new String[0], false);
final Configuration executorConfig = flinkYarnSessionCli.applyCommandLineOptionsToConfiguration(commandLine);
final ClusterClientFactory<ApplicationId> clientFactory = getClusterClientFactory(executorConfig);
final ClusterSpecification clusterSpecification = clientFactory.getClusterSpecification(executorConfig);
assertThat(clusterSpecification.getMasterMemoryMB(), is(procMemory));
assertThat(clusterSpecification.getTaskManagerMemoryMB(), is(procMemory));
}
@Test
public void testMultipleYarnShipOptions() throws Exception {
final String[] args = new String[]{"run", "--yarnship", tmp.newFolder().getAbsolutePath(), "--yarnship", tmp.newFolder().getAbsolutePath()};
final FlinkYarnSessionCli flinkYarnSessionCli = createFlinkYarnSessionCli();
final CommandLine commandLine = flinkYarnSessionCli.parseCommandLineOptions(args, false);
final Configuration executorConfig = flinkYarnSessionCli.applyCommandLineOptionsToConfiguration(commandLine);
final ClusterClientFactory<ApplicationId> clientFactory = getClusterClientFactory(executorConfig);
YarnClusterDescriptor flinkYarnDescriptor = (YarnClusterDescriptor) clientFactory.createClusterDescriptor(executorConfig);
assertEquals(2, flinkYarnDescriptor.getShipFiles().size());
}
///////////
// Utils //
///////////
private ClusterClientFactory<ApplicationId> getClusterClientFactory(final Configuration executorConfig) {
final ClusterClientServiceLoader clusterClientServiceLoader = new DefaultClusterClientServiceLoader();
return clusterClientServiceLoader.getClusterClientFactory(executorConfig);
}
private File writeYarnPropertiesFile(String contents) throws IOException {
File tmpFolder = tmp.newFolder();
String currentUser = System.getProperty("user.name");
// copy .yarn-properties-<username>
File testPropertiesFile = new File(tmpFolder, ".yarn-properties-" + currentUser);
Files.write(testPropertiesFile.toPath(), contents.getBytes(), StandardOpenOption.CREATE);
return tmpFolder.getAbsoluteFile();
}
private FlinkYarnSessionCli createFlinkYarnSessionCli() throws FlinkException {
return createFlinkYarnSessionCli(new Configuration());
}
private FlinkYarnSessionCli createFlinkYarnSessionCliWithJmAndTmTotalMemory(int totalMemomory) throws FlinkException {
Configuration configuration = new Configuration();
configuration.set(JobManagerOptions.TOTAL_PROCESS_MEMORY, MemorySize.ofMebiBytes(totalMemomory));
configuration.set(TaskManagerOptions.TOTAL_PROCESS_MEMORY, MemorySize.ofMebiBytes(totalMemomory));
return createFlinkYarnSessionCli(configuration);
}
private FlinkYarnSessionCli createFlinkYarnSessionCli(Configuration configuration) throws FlinkException {
return new FlinkYarnSessionCli(
configuration,
tmp.getRoot().getAbsolutePath(),
"y",
"yarn");
}
}
| jinglining/flink | flink-yarn/src/test/java/org/apache/flink/yarn/FlinkYarnSessionCliTest.java | Java | apache-2.0 | 23,552 |
package net.cherokeedictionary.bind;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.skife.jdbi.v2.SQLStatement;
import org.skife.jdbi.v2.sqlobject.Binder;
import org.skife.jdbi.v2.sqlobject.BinderFactory;
import org.skife.jdbi.v2.sqlobject.BindingAnnotation;
import net.cherokeedictionary.model.SearchField;
/**
* _search_field_
* @author mjoyner
*
*/
@BindingAnnotation(DefineSearchField.Factory.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.PARAMETER })
public @interface DefineSearchField {
public int value() default 0;
public static class Factory implements BinderFactory {
public Binder<DefineSearchField, SearchField> build(Annotation annotation) {
return new Binder<DefineSearchField, SearchField>() {
public void bind(SQLStatement<?> q, DefineSearchField bind, SearchField fields) {
q.define("_search_field_", fields.getFields());
}
};
}
}
}
| mjoyner-vbservices-net/CherokeeDictionaryDao | CherokeeDictionaryDao/src/main/java/net/cherokeedictionary/bind/DefineSearchField.java | Java | apache-2.0 | 1,070 |
package org.semanticcloud.semanticEngine.controll.reading.jena.propertyFactories;
import org.semanticcloud.semanticEngine.model.ontology.OntoProperty;
import org.semanticcloud.semanticEngine.controll.reading.jena.OwlPropertyFactory;
import org.semanticcloud.semanticEngine.model.ontology.properties.DateTimeProperty;
import org.apache.jena.ontology.OntProperty;
public class DateTimePropertyFactory extends OwlPropertyFactory {
@Override
public boolean canCreateProperty(OntProperty ontProperty) {
if(!ontProperty.isDatatypeProperty())
return false;
if(ontProperty.getRange() == null)
return false;
if(ontProperty.getRange().getURI() == null)
return false;
String rangeUri = ontProperty.getRange().getURI();
return rangeUri.equalsIgnoreCase("http://www.w3.org/2001/XMLSchema#datetime");
}
@Override
public OntoProperty createProperty(OntProperty ontProperty) {
return new DateTimeProperty(ontProperty.getNameSpace(), ontProperty.getLocalName(),ontProperty.isFunctionalProperty());
}
}
| SemanticCloud/SemanticCloud | SemanticEngineService/src/main/java/org/semanticcloud/semanticEngine/controll/reading/jena/propertyFactories/DateTimePropertyFactory.java | Java | apache-2.0 | 1,099 |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v10/services/asset_group_signal_service.proto
package com.google.ads.googleads.v10.services;
public interface MutateAssetGroupSignalsRequestOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.ads.googleads.v10.services.MutateAssetGroupSignalsRequest)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* Required. The ID of the customer whose asset group signals are being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The customerId.
*/
java.lang.String getCustomerId();
/**
* <pre>
* Required. The ID of the customer whose asset group signals are being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The bytes for customerId.
*/
com.google.protobuf.ByteString
getCustomerIdBytes();
/**
* <pre>
* Required. The list of operations to perform on individual asset group signals.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.AssetGroupSignalOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
java.util.List<com.google.ads.googleads.v10.services.AssetGroupSignalOperation>
getOperationsList();
/**
* <pre>
* Required. The list of operations to perform on individual asset group signals.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.AssetGroupSignalOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
com.google.ads.googleads.v10.services.AssetGroupSignalOperation getOperations(int index);
/**
* <pre>
* Required. The list of operations to perform on individual asset group signals.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.AssetGroupSignalOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
int getOperationsCount();
/**
* <pre>
* Required. The list of operations to perform on individual asset group signals.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.AssetGroupSignalOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
java.util.List<? extends com.google.ads.googleads.v10.services.AssetGroupSignalOperationOrBuilder>
getOperationsOrBuilderList();
/**
* <pre>
* Required. The list of operations to perform on individual asset group signals.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.services.AssetGroupSignalOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
com.google.ads.googleads.v10.services.AssetGroupSignalOperationOrBuilder getOperationsOrBuilder(
int index);
/**
* <pre>
* If true, successful operations will be carried out and invalid operations
* will return errors. If false, all operations will be carried out in one
* transaction if and only if they are all valid. Default is false.
* </pre>
*
* <code>bool partial_failure = 3;</code>
* @return The partialFailure.
*/
boolean getPartialFailure();
/**
* <pre>
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 4;</code>
* @return The validateOnly.
*/
boolean getValidateOnly();
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v10.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 5;</code>
* @return The enum numeric value on the wire for responseContentType.
*/
int getResponseContentTypeValue();
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v10.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 5;</code>
* @return The responseContentType.
*/
com.google.ads.googleads.v10.enums.ResponseContentTypeEnum.ResponseContentType getResponseContentType();
}
| googleads/google-ads-java | google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/services/MutateAssetGroupSignalsRequestOrBuilder.java | Java | apache-2.0 | 4,318 |
package me.tomassetti.turin.parser.ast.typeusage;
import me.tomassetti.jvm.JvmType;
import me.tomassetti.jvm.JvmTypeCategory;
import me.tomassetti.turin.definitions.TypeDefinition;
import me.tomassetti.turin.resolvers.SymbolResolver;
import me.tomassetti.turin.parser.ast.Node;
import me.tomassetti.turin.symbols.Symbol;
import me.tomassetti.turin.typesystem.*;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* A TypeUsage is the concrete usage of a type int the code.
* For example it can be a type definition with generic type parameter specified.
*/
public abstract class TypeUsageNode extends Node implements TypeUsage {
public TypeUsage typeUsage() {
return this;
}
public static TypeUsageNode wrap(TypeUsage typeUsage) {
return new TypeUsageWrapperNode(typeUsage) {
@Override
public TypeUsageNode copy() {
return this;
}
@Override
public Iterable<Node> getChildren() {
return Collections.emptyList();
}
@Override
public String toString() {
return "TypeUsageWrapperNode{"+typeUsage+"}";
}
};
}
public static class TypeVariableData {
private TypeVariableUsage.GenericDeclaration genericDeclaration;
private List<? extends TypeUsage> bounds;
public TypeVariableData(TypeVariableUsage.GenericDeclaration genericDeclaration, List<? extends TypeUsage> bounds) {
this.genericDeclaration = genericDeclaration;
this.bounds = bounds;
}
public TypeVariableUsage.GenericDeclaration getGenericDeclaration() {
return genericDeclaration;
}
public List<? extends TypeUsage> getBounds() {
return bounds;
}
}
public static TypeUsage fromJvmType(JvmType jvmType, SymbolResolver resolver, Map<String, TypeVariableData> visibleGenericTypes) {
Optional<PrimitiveTypeUsage> primitive = PrimitiveTypeUsage.findByJvmType(jvmType);
if (primitive.isPresent()) {
return primitive.get();
}
String signature = jvmType.getSignature();
if (signature.startsWith("[")) {
JvmType componentType = new JvmType(signature.substring(1));
return new ArrayTypeUsage(fromJvmType(componentType, resolver, visibleGenericTypes));
} else if (signature.startsWith("L") && signature.endsWith(";")) {
String typeName = signature.substring(1, signature.length() - 1);
typeName = typeName.replaceAll("/", ".");
Optional<TypeDefinition> typeDefinition = resolver.findTypeDefinitionIn(typeName, null, resolver);
if (!typeDefinition.isPresent()) {
throw new RuntimeException("Unable to find definition of type " + typeName + " using " + resolver);
}
return new ReferenceTypeUsage(typeDefinition.get());
} else if (signature.equals("V")) {
return new VoidTypeUsage();
} else {
for (String typeVariableName : visibleGenericTypes.keySet()) {
if (typeVariableName.equals(signature)) {
TypeVariableData typeVariableData = visibleGenericTypes.get(typeVariableName);
return new ConcreteTypeVariableUsage(typeVariableData.genericDeclaration, typeVariableName, typeVariableData.getBounds());
}
}
throw new UnsupportedOperationException("Signature="+signature+", type="+jvmType.getClass());
}
}
public final JvmTypeCategory toJvmTypeCategory() {
return this.jvmType().typeCategory();
}
@Override
public boolean isReferenceTypeUsage() {
return false;
}
@Override
public ReferenceTypeUsage asReferenceTypeUsage() {
throw new UnsupportedOperationException();
}
@Override
public me.tomassetti.turin.typesystem.ArrayTypeUsage asArrayTypeUsage() {
throw new UnsupportedOperationException();
}
@Override
public boolean canBeAssignedTo(TypeUsage type) {
throw new UnsupportedOperationException(this.getClass().getCanonicalName());
}
@Override
public boolean isArray() {
return false;
}
@Override
public boolean isPrimitive() {
return false;
}
@Override
public boolean isReference() {
return false;
}
@Override
public PrimitiveTypeUsage asPrimitiveTypeUsage() {
throw new UnsupportedOperationException(this.getClass().getCanonicalName());
}
@Override
public Symbol getInstanceField(String fieldName, Symbol instance) {
throw new UnsupportedOperationException(this.getClass().getCanonicalName());
}
@Override
public boolean isVoid() {
return false;
}
public abstract TypeUsageNode copy();
@Override
public <T extends TypeUsage> TypeUsage replaceTypeVariables(Map<String, T> typeParams) {
throw new UnsupportedOperationException(this.getClass().getCanonicalName());
}
}
| ftomassetti/turin-programming-language | turin-compiler/src/main/java/me/tomassetti/turin/parser/ast/typeusage/TypeUsageNode.java | Java | apache-2.0 | 5,167 |
package com.zuehlke.carrera.javapilot.akka.power;
import com.zuehlke.carrera.javapilot.akka.Config;
import com.zuehlke.carrera.javapilot.akka.controller.Autopilot;
import com.zuehlke.carrera.javapilot.akka.model.Sector;
import com.zuehlke.carrera.javapilot.akka.model.SectorHistory;
import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectLinkedOpenHashMap;
/**
* Created by Simon Gwerder on 29.11.2015.
*/
public class BaseProfile {
protected Int2ObjectLinkedOpenHashMap<Power> profile = new Int2ObjectLinkedOpenHashMap<>(20);
public Int2ObjectLinkedOpenHashMap<Power> getProfile() {
return profile;
}
private double powerDiffFunc(int distance, int velocity, int speedlimit) {
int diff = Math.abs(speedlimit - velocity);
if (velocity >= speedlimit - Config.POWERDIFF_DELTA) {
return -(diff) / ((distance + Config.POWERDIFF_DISTANCE_DELTA) * Config.FACTOR_DOWN);
}
else {
return (diff) / ((distance + Config.POWERDIFF_DISTANCE_DELTA) * Config.FACTOR_UP);
}
}
// private double powerDiffFunc(int distance, int velocity) {
// int diff = (Config.SPEEDLIMIT - velocity); // Play around with changing sign: (Config.SPEEDLIMIT +- x) - velocity
// if(velocity < Config.SPEEDLIMIT) {
// return Math.cbrt(diff) / (distance + 1);
// }
// else {
// return 2 * Math.cbrt(diff) / (distance + 1);
// }
// }
private int approxPotential(SectorHistory sectorHistory) {
double approxPotential = 0;
Int2ObjectArrayMap<Sector> affectingCheckpoints = sectorHistory.getAffectingCheckpoints();
for (int distance : affectingCheckpoints.keySet()) {
Sector checkpoint = affectingCheckpoints.get(distance);
Double velocity = checkpoint.getVelocityMeasured();
if (velocity != null) {
approxPotential += powerDiffFunc(distance, velocity.intValue(), sectorHistory.getSpeedlimit());
}
}
sectorHistory.clearAffectingCheckpoint(); // Uncool here
return (int) approxPotential;
}
public int changeValue(SectorHistory sectorHistory) {
int approxPotential = approxPotential(sectorHistory);
int changeValue = 0;
if (sectorHistory.hadPenaltyRecently()) {
changeValue = ((Config.POWER_DOWN * (sectorHistory.getConsecutivePenalty() + 1))) + approxPotential;
}
else {
changeValue = Config.POWER_UP + approxPotential;
}
return changeValue;
}
public int changeValue(Sector matching) {
if (matching.getPenalty()) {
return Config.POWER_DOWN;
}
return Config.POWER_UP;
}
}
| sgwerder/SpeedRacer | src/main/java/com/zuehlke/carrera/javapilot/akka/power/BaseProfile.java | Java | apache-2.0 | 2,793 |
// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.bamboo.soy.elements;
import com.google.bamboo.soy.parser.SoyEndTag;
import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;
public interface TagBlockElement extends PsiElement {
@NotNull
default TagElement getOpeningTag() {
return (TagElement) WhitespaceUtils.getFirstMeaningChild(this);
}
@NotNull
default IElementType getTagNameTokenType() {
return getOpeningTag().getTagNameTokenType();
}
@NotNull
default String getTagName() {
return getOpeningTag().getTagName();
}
default boolean isIncomplete() {
PsiElement lastChild = WhitespaceUtils.getLastMeaningChild(this);
return !(lastChild instanceof SoyEndTag);
}
}
| google/bamboo-soy | src/main/java/com/google/bamboo/soy/elements/TagBlockElement.java | Java | apache-2.0 | 1,337 |
/**
*
*/
package org.javarosa.demo.util;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.core.model.utils.IPreloadHandler;
import org.javarosa.core.model.User;
/**
* @author ctsims
*
*/
public class MetaPreloadHandler implements IPreloadHandler {
private static final String MIDLET_VERSION_PROPERTY = "MIDlet-Version";
private User u;
public MetaPreloadHandler(User u) {
this.u = u;
}
/* (non-Javadoc)
* @see org.javarosa.core.model.utils.IPreloadHandler#handlePostProcess(org.javarosa.core.model.instance.TreeElement, java.lang.String)
*/
public boolean handlePostProcess(TreeElement node, String params) {
// TODO Auto-generated method stub
return false;
}
/* (non-Javadoc)
* @see org.javarosa.core.model.utils.IPreloadHandler#handlePreload(java.lang.String)
*/
public IAnswerData handlePreload(String preloadParams) {
System.out.println("asked to preload: " + preloadParams);
if(preloadParams.equals("UserName")) {
return new StringData(u.getUsername());
}else if(preloadParams.equals("UserID")) {
// return new StringData(String.valueOf(u.getUserID())); commented because Anton could'nt run to review
return new StringData(u.getUsername());
}
System.out.println("FAILED to preload: " + preloadParams);
return null;
}
/* (non-Javadoc)
* @see org.javarosa.core.model.utils.IPreloadHandler#preloadHandled()
*/
public String preloadHandled() {
return "context";
}
}
| dimagi/javarosa | javarosa/j2me/javarosa-app/src/org/javarosa/demo/util/MetaPreloadHandler.java | Java | apache-2.0 | 1,697 |
/**
* 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.ambari.server.actionmanager;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.google.inject.persist.UnitOfWork;
import org.apache.ambari.server.agent.ActionQueue;
import org.apache.ambari.server.agent.CommandReport;
import org.apache.ambari.server.controller.HostsMap;
import org.apache.ambari.server.serveraction.ServerActionManager;
import org.apache.ambari.server.state.Clusters;
import org.apache.ambari.server.utils.StageUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
/**
* This class acts as the interface for action manager with other components.
*/
@Singleton
public class ActionManager {
private final ActionScheduler scheduler;
private final ActionDBAccessor db;
private final ActionQueue actionQueue;
private static Logger LOG = LoggerFactory.getLogger(ActionManager.class);
private final AtomicLong requestCounter;
@Inject
public ActionManager(@Named("schedulerSleeptime") long schedulerSleepTime,
@Named("actionTimeout") long actionTimeout,
ActionQueue aq, Clusters fsm, ActionDBAccessor db, HostsMap hostsMap,
ServerActionManager serverActionManager, UnitOfWork unitOfWork) {
this.actionQueue = aq;
this.db = db;
scheduler = new ActionScheduler(schedulerSleepTime, actionTimeout, db,
actionQueue, fsm, 2, hostsMap, serverActionManager, unitOfWork);
requestCounter = new AtomicLong(
db.getLastPersistedRequestIdWhenInitialized());
}
public void start() {
LOG.info("Starting scheduler thread");
scheduler.start();
}
public void shutdown() {
scheduler.stop();
}
public void sendActions(List<Stage> stages) {
if (LOG.isDebugEnabled()) {
for (Stage s : stages) {
LOG.debug("Persisting stage into db: " + s.toString());
}
}
db.persistActions(stages);
// Now scheduler should process actions
scheduler.awake();
}
public List<Stage> getRequestStatus(long requestId) {
return db.getAllStages(requestId);
}
public Stage getAction(long requestId, long stageId) {
return db.getAction(StageUtils.getActionId(requestId, stageId));
}
/**
* Get all actions(stages) for a request.
*
* @param requestId the request id
* @return list of all stages associated with the given request id
*/
public List<Stage> getActions(long requestId) {
return db.getAllStages(requestId);
}
/**
* Persists command reports into the db
*/
public void processTaskResponse(String hostname, List<CommandReport> reports) {
if (reports == null) {
return;
}
//persist the action response into the db.
for (CommandReport report : reports) {
if (LOG.isDebugEnabled()) {
LOG.debug("Processing command report : " + report.toString());
}
String actionId = report.getActionId();
long [] requestStageIds = StageUtils.getRequestStage(actionId);
long requestId = requestStageIds[0];
long stageId = requestStageIds[1];
HostRoleCommand command = db.getTask(report.getTaskId());
if (command == null) {
LOG.warn("The task " + report.getTaskId()
+ " is invalid");
continue;
}
if (!command.getStatus().equals(HostRoleStatus.IN_PROGRESS)
&& !command.getStatus().equals(HostRoleStatus.QUEUED)) {
LOG.warn("The task " + command.getTaskId()
+ " is not in progress, ignoring update");
continue;
}
db.updateHostRoleState(hostname, requestId, stageId, report.getRole(),
report);
}
}
public void handleLostHost(String host) {
//Do nothing, the task will timeout anyway.
//The actions can be failed faster as an optimization
//if action timeout happens to be much larger than
//heartbeat timeout.
}
public long getNextRequestId() {
return requestCounter.incrementAndGet();
}
public List<HostRoleCommand> getRequestTasks(long requestId) {
return db.getRequestTasks(requestId);
}
public List<HostRoleCommand> getAllTasksByRequestIds(Collection<Long> requestIds) {
return db.getAllTasksByRequestIds(requestIds);
}
public List<HostRoleCommand> getTasksByRequestAndTaskIds(Collection<Long> requestIds, Collection<Long> taskIds) {
return db.getTasksByRequestAndTaskIds(requestIds, taskIds);
}
public Collection<HostRoleCommand> getTasks(Collection<Long> taskIds) {
return db.getTasks(taskIds);
}
public List<Stage> getRequestsByHostRoleStatus(Set<HostRoleStatus> statuses) {
return db.getStagesByHostRoleStatus(statuses);
}
/**
* Returns last 20 requests
* @return
*/
public List<Long> getRequests() {
return db.getRequests();
}
/**
* Returns last 20 requests
* @return
*/
public List<Long> getRequestsByStatus(RequestStatus status) {
return db.getRequestsByStatus(status);
}
public Map<Long, String> getRequestContext(List<Long> requestIds) {
return db.getRequestContext(requestIds);
}
public String getRequestContext(long requestId) {
return db.getRequestContext(requestId);
}
}
| telefonicaid/fiware-cosmos-ambari | ambari-server/src/main/java/org/apache/ambari/server/actionmanager/ActionManager.java | Java | apache-2.0 | 6,090 |
/*
* Copyright 2016 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 io.pivotal.cla.egit.github.core.event;
import org.eclipse.egit.github.core.Repository;
/**
* @author Mark Paluch
*/
public interface RepositoryAware {
Repository getRepository();
}
| pivotalsoftware/pivotal-cla | src/main/java/io/pivotal/cla/egit/github/core/event/RepositoryAware.java | Java | apache-2.0 | 811 |
package ru.job4j.loop;
/**
* Class Board.
* @author Ilya.
* @since 2017.10.
*/
public class Board {
/**
* Method get.
* @param width args.
* @param height args.
* @return builder.toString().
*/
public String paint(int width, int height) {
StringBuilder builder = new StringBuilder();
for (int i = 1; i <= height; i++) {
for (int j = 1; j <= width; j++) {
if ((i + j) % 2 == 1) {
builder.append(" ");
} else {
builder.append("x");
}
}
builder.append(System.lineSeparator());
}
return builder.toString();
}
} | warham194/nevolin-isergeevich | chapter_001/src/main/java/ru/job4j/loop/Board.java | Java | apache-2.0 | 710 |
package navyblue.top.colortalk.util;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v4.app.TaskStackBuilder;
import android.support.v7.app.AppCompatActivity;
public class AppUtils {
private AppUtils() {}
public static PackageInfo getPackageInfo(Context context) {
try {
return context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
// Should never happen.
throw new RuntimeException(e);
}
}
// From http://developer.android.com/training/implementing-navigation/ancestral.html#NavigateUp .
public static void navigateUp(Activity activity, Bundle extras) {
Intent upIntent = NavUtils.getParentActivityIntent(activity);
if (upIntent != null) {
if (extras != null) {
upIntent.putExtras(extras);
}
if (NavUtils.shouldUpRecreateTask(activity, upIntent)) {
// This activity is NOT part of this app's task, so create a new task
// when navigating up, with a synthesized back stack.
TaskStackBuilder.create(activity)
// Add all of this activity's parents to the back stack.
.addNextIntentWithParentStack(upIntent)
// Navigate up to the closest parent.
.startActivities();
} else {
// This activity is part of this app's task, so simply
// navigate up to the logical parent activity.
// According to http://stackoverflow.com/a/14792752/2420519
//NavUtils.navigateUpTo(activity, upIntent);
upIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activity.startActivity(upIntent);
}
}
activity.finish();
}
public static void navigateUp(Activity activity) {
navigateUp(activity, null);
}
public static void setActionBarDisplayUp(AppCompatActivity activity) {
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
| YogiAi/ColorTalk_Android | app/src/main/java/navyblue/top/colortalk/util/AppUtils.java | Java | apache-2.0 | 2,372 |
package ru.stqa.pft.sandbox;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Created by pacman on 10/17/16.
*/
public class RectangleTests {
@Test
public void TestArea(){
Recntangle r = new Recntangle(5, 6);
Assert.assertEquals(r.area(), 30);
}
}
| 4joke/programming_for_testers | sandbox/src/test/java/ru/stqa/pft/sandbox/RectangleTests.java | Java | apache-2.0 | 299 |
/*
* Copyright 2017 EMBL - European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.ac.ebi.eva.vcfdump.server;
import io.swagger.annotations.Api;
import org.opencb.biodata.models.feature.Region;
import org.opencb.opencga.lib.auth.IllegalOpenCGACredentialsException;
import org.opencb.opencga.storage.core.StorageManagerException;
import org.opencb.opencga.storage.core.variant.adaptors.VariantDBAdaptor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
import uk.ac.ebi.eva.vcfdump.VariantExporterController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
@RestController
@RequestMapping(value = "/variants/")
@Api(tags = {"htsget"})
public class HtsgetVcfController {
private static final String VCF = "VCF";
private Properties evaProperties;
public HtsgetVcfController() throws IOException {
evaProperties = new Properties();
evaProperties.load(VcfDumperWSServer.class.getResourceAsStream("/eva.properties"));
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET, consumes = "application/*",
produces = "application/vnd.ga4gh.htsget.v0.2rc+json; charset=UTF-8")
public ResponseEntity getHtsgetUrls(
@PathVariable("id") String id,
@RequestParam(name = "format", required = false) String format,
@RequestParam(name = "referenceName", required = false) String referenceName,
@RequestParam(name = "species", required = false) String species,
@RequestParam(name = "start", required = false) Integer start,
@RequestParam(name = "end", required = false) Integer end,
@RequestParam(name = "fields", required = false) List<String> fields,
@RequestParam(name = "tags", required = false, defaultValue = "") String tags,
@RequestParam(name = "notags", required = false, defaultValue = "") String notags,
HttpServletRequest request,
HttpServletResponse response)
throws IllegalAccessException, IllegalOpenCGACredentialsException, InstantiationException, IOException,
StorageManagerException, URISyntaxException, ClassNotFoundException {
if (!VCF.equals(format)) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Collections.singletonMap("htsget",
new HtsGetError("UnsupportedFormat", "Specified format is not supported by this server")));
}
String dbName = "eva_" + species;
MultivaluedMap<String, String> queryParameters = new MultivaluedHashMap<>();
queryParameters.put(VariantDBAdaptor.REGION, Collections.singletonList(referenceName));
int blockSize = Integer.parseInt(evaProperties.getProperty("eva.htsget.blocksize"));
VariantExporterController controller = new VariantExporterController(dbName, Arrays.asList(id.split(",")),
evaProperties,
queryParameters, blockSize);
ResponseEntity errorResponse = validateRequest(referenceName, start, controller);
if (errorResponse != null) {
return errorResponse;
}
if (start != null && end != null && end <= start) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Collections.singletonMap("htsget",
new HtsGetError("InvalidRange", "The requested range cannot be satisfied")));
}
if (start == null) {
start = controller.getCoordinateOfFirstVariant(referenceName);
}
if (end == null) {
end = controller.getCoordinateOfLastVariant(referenceName);
}
if (end <= start) {
// Applies to valid requests such as chromosome 1, start: 1.000.000, end: empty.
// If variants exist only in region 200.000 to 800.000, getCoordinateOfLastVariant() will return 800.000.
// Given that 800.000 < 1.000.000, no region can be found.
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Collections.singletonMap("htsget",
new HtsGetError("NotFound", "The resource requested was not found")));
}
List<Region> regionList = controller.divideChromosomeInChunks(referenceName, start, end);
HtsGetResponse htsGetResponse = new HtsGetResponse(VCF, request.getLocalName() + ":" + request.getLocalPort(),
id, referenceName, species, regionList);
return ResponseEntity.status(HttpStatus.OK).body(Collections.singletonMap("htsget", htsGetResponse));
}
private ResponseEntity validateRequest(String referenceName, Integer start, VariantExporterController controller) {
if (!controller.validateSpecies()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(
Collections.singletonMap("htsget", new HtsGetError("InvalidInput", "The requested species is not available")));
}
if (!controller.validateStudies()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(
Collections.singletonMap("htsget", new HtsGetError("InvalidInput", "The requested study(ies) is not available")));
}
if (start != null && referenceName == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(
Collections.singletonMap("htsget", new HtsGetError("InvalidInput", "Reference name is not specified when start is specified")));
}
return null;
}
@RequestMapping(value = "/headers", method = RequestMethod.GET, produces = "application/octet-stream")
public StreamingResponseBody getHtsgetHeaders(
@RequestParam(name = "species") String species,
@RequestParam(name = "studies") List<String> studies,
HttpServletResponse response)
throws IllegalAccessException, IllegalOpenCGACredentialsException, InstantiationException, IOException,
StorageManagerException, URISyntaxException, ClassNotFoundException {
String dbName = "eva_" + species;
StreamingResponseBody responseBody = getStreamingHeaderResponse(dbName, studies, evaProperties,
new MultivaluedHashMap<>(), response);
return responseBody;
}
@RequestMapping(value = "/block", method = RequestMethod.GET, produces = "application/octet-stream")
public StreamingResponseBody getHtsgetBlocks(
@RequestParam(name = "species") String species,
@RequestParam(name = "studies") List<String> studies,
@RequestParam(name = "region") String chrRegion,
HttpServletResponse response)
throws IllegalAccessException, IllegalOpenCGACredentialsException, InstantiationException, IOException,
StorageManagerException, URISyntaxException, ClassNotFoundException {
String dbName = "eva_" + species;
MultivaluedMap<String, String> queryParameters = new MultivaluedHashMap<>();
queryParameters.put(VariantDBAdaptor.REGION, Collections.singletonList(chrRegion));
StreamingResponseBody responseBody = getStreamingBlockResponse(dbName, studies, evaProperties,
queryParameters, response);
return responseBody;
}
private StreamingResponseBody getStreamingHeaderResponse(String dbName, List<String> studies,
Properties evaProperties,
MultivaluedMap<String, String> queryParameters,
HttpServletResponse response) {
return outputStream -> {
VariantExporterController controller;
try {
controller = new VariantExporterController(dbName, studies, outputStream, evaProperties,
queryParameters);
// tell the client that the file is an attachment, so it will download it instead of showing it
response.addHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment;filename=" + controller.getOutputFileName());
controller.exportHeader();
} catch (Exception e) {
throw new WebApplicationException(e);
}
};
}
private StreamingResponseBody getStreamingBlockResponse(String dbName, List<String> studies,
Properties evaProperties,
MultivaluedMap<String, String> queryParameters,
HttpServletResponse response) {
return outputStream -> {
VariantExporterController controller;
try {
controller = new VariantExporterController(dbName, studies, outputStream, evaProperties,
queryParameters);
// tell the client that the file is an attachment, so it will download it instead of showing it
response.addHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment;filename=" + controller.getOutputFileName());
controller.exportBlock();
} catch (Exception e) {
throw new WebApplicationException(e);
}
};
}
}
| amilamanoj/eva-tools | vcf-dumper/vcf-dumper-ws/src/main/java/uk/ac/ebi/eva/vcfdump/server/HtsgetVcfController.java | Java | apache-2.0 | 11,072 |
package com.akjava.gwt.formant.client;
import com.google.gwt.i18n.client.Constants;
import com.google.gwt.safehtml.shared.SafeHtml;
public interface TextConstants extends Constants {
public String formant();
public String version();
public String notwork();
public String interimResults();
public String start();
public String stop();
public String pushtostart();
public String date();
public String confidence();
public String altenative();
public String altenatives();
public String generate();
public String clear();
public String clearall();
public String language();
public String japanese();
public String english();
public String pushtocsv();
public String recognizing();
public String wordlesson();
public String network();
public String nospeech();
public String notallowed();
public String finished();
public String finished_rec();
public String ready();
public String england();
public String continues();
public String howtouse();
public String simplerecognize();
public String attmpt();
public String matched();
public String avgconf();
public String hit();
public String miss();
public String mode();
public String order();
public String voice();
public String startBt();
public String stopBt();
public String skip();
public String first();
public String prev();
public String next();
public String play();
public String word();
public String time();
public String last();
public String random();
public String missed();
public String result();
public String pronounce();
public String meaning();
public String tofirst();
public String ref();
public String downloadwav();
public String reccordwav();
public String reccordwav_title();
public String mean_language();
public String update_filter();
public String select_all();
public String unselect_all();
public String close();
public String settings();
public String statics();
public String download_csv();
public String generate_download();
public String type();
public String clear_word();
public String number_word();
public String total_word();
public String start_word();
public String contain_word();
public String end_word();
public String fewer_attempt();
public String empty_list();
public String use_rcolor();
public String stop_record();
public String start_record();
public String stop_media();
public String copy_to_right();
public String show_formant();
public String default_value();
public String reset();
public String save();
public String generate_image();
public String generate_csv();
public String download_recorded_audio();
//public String generate_image();
public String base_formant();
//public String show_formant();
public String zoom();
public String font();
public String color();
public String text();
public String inside();
public String background();
public String baseRect();
public String valueRect();
public String memoryLine();
//public String reset();
public String grid();
public String min();
public String max();
public String load();
public String upload();
public String canadian_vowel();
public String average_vowel();
public String name();
public String up();
public String down();
public String newItem();
public String remove();
public String quolity();
public String show_base_on_image();
public String add();
public String update();
}
| akjava/GWTFormantViewer | src/com/akjava/gwt/formant/client/TextConstants.java | Java | apache-2.0 | 3,587 |
/********************************************************************************
* Copyright 2017 Capital One Services, LLC and Bitwise, 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 hydrograph.ui.parametergrid.dialog;
import java.io.IOException;
import java.io.InputStream;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
import java.util.ArrayList;
import java.util.List;
/**
* @author Bitwise
*
*/
public class LookAheadObjectInputStream extends ObjectInputStream{
List<String> acceptedObject = new ArrayList<String>();
public LookAheadObjectInputStream(InputStream inputStream, List<String> acceptedObject)
throws IOException {
super(inputStream);
this.acceptedObject = acceptedObject;
}
/**
* Only deserialize instances of our expected class
*/
@Override
protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException,
ClassNotFoundException {
if (!acceptedObject.contains(desc.getName())) {
throw new InvalidClassException(
"Unauthorized deserialization attempt",
desc.getName());
}
return super.resolveClass(desc);
}
}
| capitalone/Hydrograph | hydrograph.ui/hydrograph.ui.parametergrid/src/main/java/hydrograph/ui/parametergrid/dialog/LookAheadObjectInputStream.java | Java | apache-2.0 | 1,912 |
package ru.r2cloud.satellite.decoder;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import ru.r2cloud.jradio.BeaconOutputStream;
import ru.r2cloud.jradio.RawBeacon;
import ru.r2cloud.model.DecoderResult;
import ru.r2cloud.model.ObservationRequest;
public class R2loraDecoderTest {
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
@Test
public void testSuccess() throws Exception {
RawBeacon beacon = new RawBeacon();
beacon.setBeginMillis(1641987504000L);
beacon.setRawData(new byte[] { 0x11, 0x22 });
File rawFile = new File(tempFolder.getRoot(), UUID.randomUUID().toString() + ".raw");
try (BeaconOutputStream bos = new BeaconOutputStream(new FileOutputStream(rawFile))) {
bos.write(beacon);
}
R2loraDecoder decoder = new R2loraDecoder(RawBeacon.class);
DecoderResult result = decoder.decode(rawFile, new ObservationRequest());
assertNotNull(result);
assertEquals(1, result.getNumberOfDecodedPackets().longValue());
assertNotNull(result.getDataPath());
}
@Test
public void testNoDataOrInvalid() throws Exception {
File rawFile = new File(tempFolder.getRoot(), UUID.randomUUID().toString() + ".raw");
try (FileOutputStream fos = new FileOutputStream(rawFile)) {
fos.write(1);
}
R2loraDecoder decoder = new R2loraDecoder(RawBeacon.class);
DecoderResult result = decoder.decode(rawFile, new ObservationRequest());
assertNotNull(result);
assertEquals(0, result.getNumberOfDecodedPackets().longValue());
assertNull(result.getDataPath());
assertFalse(rawFile.exists());
}
}
| dernasherbrezon/r2cloud | src/test/java/ru/r2cloud/satellite/decoder/R2loraDecoderTest.java | Java | apache-2.0 | 1,845 |
package example.repo;
import example.model.Customer1367;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
public interface Customer1367Repository extends CrudRepository<Customer1367, Long> {
List<Customer1367> findByLastName(String lastName);
}
| spring-projects/spring-data-examples | jpa/deferred/src/main/java/example/repo/Customer1367Repository.java | Java | apache-2.0 | 284 |
/*
* 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.commons.net.ftp.parser;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.apache.commons.net.ftp.FTPClientConfig;
/**
* Special implementation VMSFTPEntryParser with versioning turned on.
* This parser removes all duplicates and only leaves the version with the highest
* version number for each filename.
*
* This is a sample of VMS LIST output
*
* "1-JUN.LIS;1 9/9 2-JUN-1998 07:32:04 [GROUP,OWNER] (RWED,RWED,RWED,RE)",
* "1-JUN.LIS;2 9/9 2-JUN-1998 07:32:04 [GROUP,OWNER] (RWED,RWED,RWED,RE)",
* "DATA.DIR;1 1/9 2-JUN-1998 07:32:04 [GROUP,OWNER] (RWED,RWED,RWED,RE)",
* <P>
*
* @author <a href="[email protected]">Winston Ojeda</a>
* @author <a href="[email protected]">Stephane ESTE-GRACIAS</a>
* @version $Id$
*
* @see org.apache.commons.net.ftp.FTPFileEntryParser FTPFileEntryParser (for usage instructions)
*/
public class VMSVersioningFTPEntryParser extends VMSFTPEntryParser
{
private final Pattern _preparse_pattern_;
private static final String PRE_PARSE_REGEX =
"(.*?);([0-9]+)\\s*.*";
/**
* Constructor for a VMSFTPEntryParser object.
*
* @exception IllegalArgumentException
* Thrown if the regular expression is unparseable. Should not be seen
* under normal conditions. It it is seen, this is a sign that
* <code>REGEX</code> is not a valid regular expression.
*/
public VMSVersioningFTPEntryParser()
{
this(null);
}
/**
* This constructor allows the creation of a VMSVersioningFTPEntryParser
* object with something other than the default configuration.
*
* @param config The {@link FTPClientConfig configuration} object used to
* configure this parser.
* @exception IllegalArgumentException
* Thrown if the regular expression is unparseable. Should not be seen
* under normal conditions. It it is seen, this is a sign that
* <code>REGEX</code> is not a valid regular expression.
* @since 1.4
*/
public VMSVersioningFTPEntryParser(FTPClientConfig config)
{
super();
configure(config);
try
{
//_preparse_matcher_ = new Perl5Matcher();
_preparse_pattern_ = Pattern.compile(PRE_PARSE_REGEX);
}
catch (PatternSyntaxException pse)
{
throw new IllegalArgumentException (
"Unparseable regex supplied: " + PRE_PARSE_REGEX);
}
}
/**
* Implement hook provided for those implementers (such as
* VMSVersioningFTPEntryParser, and possibly others) which return
* multiple files with the same name to remove the duplicates ..
*
* @param original Original list
*
* @return Original list purged of duplicates
*/
@Override
public List<String> preParse(List<String> original) {
HashMap<String, Integer> existingEntries = new HashMap<String, Integer>();
ListIterator<String> iter = original.listIterator();
while (iter.hasNext()) {
String entry = iter.next().trim();
MatchResult result = null;
Matcher _preparse_matcher_ = _preparse_pattern_.matcher(entry);
if (_preparse_matcher_.matches()) {
result = _preparse_matcher_.toMatchResult();
String name = result.group(1);
String version = result.group(2);
Integer nv = Integer.valueOf(version);
Integer existing = existingEntries.get(name);
if (null != existing) {
if (nv.intValue() < existing.intValue()) {
iter.remove(); // removes older version from original list.
continue;
}
}
existingEntries.put(name, nv);
}
}
// we've now removed all entries less than with less than the largest
// version number for each name that were listed after the largest.
// we now must remove those with smaller than the largest version number
// for each name that were found before the largest
while (iter.hasPrevious()) {
String entry = iter.previous().trim();
MatchResult result = null;
Matcher _preparse_matcher_ = _preparse_pattern_.matcher(entry);
if (_preparse_matcher_.matches()) {
result = _preparse_matcher_.toMatchResult();
String name = result.group(1);
String version = result.group(2);
Integer nv = Integer.valueOf(version);
Integer existing = existingEntries.get(name);
if (null != existing) {
if (nv.intValue() < existing.intValue()) {
iter.remove(); // removes older version from original list.
}
}
}
}
return original;
}
@Override
protected boolean isVersioning() {
return true;
}
}
/* Emacs configuration
* Local variables: **
* mode: java **
* c-basic-offset: 4 **
* indent-tabs-mode: nil **
* End: **
*/
| codolutions/commons-net | src/main/java/org/apache/commons/net/ftp/parser/VMSVersioningFTPEntryParser.java | Java | apache-2.0 | 6,283 |
package com.ukefu.webim.web.handler.apps.service;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.elasticsearch.common.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.ukefu.core.UKDataContext;
import com.ukefu.util.Menu;
import com.ukefu.util.UKTools;
import com.ukefu.util.task.export.ExcelExporterProcess;
import com.ukefu.webim.service.repository.AgentServiceRepository;
import com.ukefu.webim.service.repository.ContactsRepository;
import com.ukefu.webim.service.repository.MetadataRepository;
import com.ukefu.webim.service.repository.ServiceSummaryRepository;
import com.ukefu.webim.service.repository.TagRepository;
import com.ukefu.webim.web.handler.Handler;
import com.ukefu.webim.web.model.AgentService;
import com.ukefu.webim.web.model.AgentServiceSummary;
import com.ukefu.webim.web.model.Contacts;
import com.ukefu.webim.web.model.MetadataTable;
@Controller
@RequestMapping("/apps/agent/summary")
public class AgentSummaryController extends Handler{
@Autowired
private ServiceSummaryRepository serviceSummaryRes ;
@Autowired
private MetadataRepository metadataRes ;
@Autowired
private AgentServiceRepository agentServiceRes ;
@Autowired
private TagRepository tagRes ;
@Autowired
private ContactsRepository contactsRes ;
/**
* 按条件查询
* @param map
* @param request
* @param ani
* @param called
* @param begin
* @param end
* @param direction
* @return
*/
@RequestMapping(value = "/index")
@Menu(type = "agent" , subtype = "agentsummary" , access = false)
public ModelAndView index(ModelMap map , HttpServletRequest request , @Valid final String begin , @Valid final String end ) {
Page<AgentServiceSummary> page = serviceSummaryRes.findAll(new Specification<AgentServiceSummary>(){
@Override
public Predicate toPredicate(Root<AgentServiceSummary> root, CriteriaQuery<?> query,
CriteriaBuilder cb) {
List<Predicate> list = new ArrayList<Predicate>();
list.add(cb.equal(root.get("process").as(boolean.class), 0)) ;
list.add(cb.notEqual(root.get("channel").as(String.class), UKDataContext.ChannelTypeEnum.PHONE.toString())) ;
try {
if(!StringUtils.isBlank(begin) && begin.matches("[\\d]{4}-[\\d]{2}-[\\d]{2} [\\d]{2}:[\\d]{2}:[\\d]{2}")){
list.add(cb.greaterThan(root.get("createtime").as(Date.class), UKTools.dateFormate.parse(begin))) ;
}
if(!StringUtils.isBlank(end) && end.matches("[\\d]{4}-[\\d]{2}-[\\d]{2} [\\d]{2}:[\\d]{2}:[\\d]{2}")){
list.add(cb.lessThan(root.get("createtime").as(Date.class), UKTools.dateFormate.parse(end))) ;
}
} catch (ParseException e) {
e.printStackTrace();
}
Predicate[] p = new Predicate[list.size()];
return cb.and(list.toArray(p));
}}, new PageRequest(super.getP(request), super.getPs(request) , Sort.Direction.DESC, "createtime")) ;
map.addAttribute("summaryList", page) ;
map.addAttribute("begin", begin) ;
map.addAttribute("end", end) ;
map.addAttribute("tags", tagRes.findByOrgiAndTagtype(super.getOrgi(request) , UKDataContext.ModelType.SUMMARY.toString())) ;
return request(super.createAppsTempletResponse("/apps/service/summary/index"));
}
@RequestMapping(value = "/process")
@Menu(type = "agent" , subtype = "agentsummary" , access = false)
public ModelAndView process(ModelMap map , HttpServletRequest request , @Valid final String id) {
AgentServiceSummary summary = serviceSummaryRes.findByIdAndOrgi(id, super.getOrgi(request)) ;
map.addAttribute("summary",summary) ;
map.put("summaryTags", tagRes.findByOrgiAndTagtype(super.getOrgi(request) , UKDataContext.ModelType.SUMMARY.toString())) ;
if(summary!=null && !StringUtils.isBlank(summary.getAgentserviceid())){
AgentService service = agentServiceRes.findByIdAndOrgi(summary.getAgentserviceid(), super.getOrgi(request)) ;
map.addAttribute("service",service) ;
if(!StringUtils.isBlank(summary.getContactsid())){
Contacts contacts = contactsRes.findOne(summary.getContactsid()) ;
map.addAttribute("contacts",contacts) ;
}
}
return request(super.createRequestPageTempletResponse("/apps/service/summary/process"));
}
@RequestMapping(value = "/save")
@Menu(type = "agent" , subtype = "agentsummary" , access = false)
public ModelAndView save(ModelMap map , HttpServletRequest request , @Valid final AgentServiceSummary summary) {
AgentServiceSummary oldSummary = serviceSummaryRes.findByIdAndOrgi(summary.getId(), super.getOrgi(request)) ;
if(oldSummary!=null){
oldSummary.setProcess(true);
oldSummary.setUpdatetime(new Date());
oldSummary.setUpdateuser(super.getUser(request).getId());
oldSummary.setProcessmemo(summary.getProcessmemo());
serviceSummaryRes.save(oldSummary) ;
}
return request(super.createRequestPageTempletResponse("redirect:/apps/agent/summary/index.html"));
}
@RequestMapping("/expids")
@Menu(type = "agent" , subtype = "agentsummary" , access = false)
public void expids(ModelMap map , HttpServletRequest request , HttpServletResponse response , @Valid String[] ids) throws IOException {
if(ids!=null && ids.length > 0){
Iterable<AgentServiceSummary> statusEventList = serviceSummaryRes.findAll(Arrays.asList(ids)) ;
MetadataTable table = metadataRes.findByTablename("uk_servicesummary") ;
List<Map<String,Object>> values = new ArrayList<Map<String,Object>>();
for(AgentServiceSummary event : statusEventList){
values.add(UKTools.transBean2Map(event)) ;
}
response.setHeader("content-disposition", "attachment;filename=UCKeFu-Summary-History-"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+".xls");
ExcelExporterProcess excelProcess = new ExcelExporterProcess( values, table, response.getOutputStream()) ;
excelProcess.process();
}
return ;
}
@RequestMapping("/expall")
@Menu(type = "agent" , subtype = "agentsummary" , access = false)
public void expall(ModelMap map , HttpServletRequest request , HttpServletResponse response) throws IOException {
Iterable<AgentServiceSummary> statusEventList = serviceSummaryRes.findByChannelAndOrgi(UKDataContext.ChannelTypeEnum.PHONE.toString() , super.getOrgi(request) , new PageRequest(0, 10000));
MetadataTable table = metadataRes.findByTablename("uk_servicesummary") ;
List<Map<String,Object>> values = new ArrayList<Map<String,Object>>();
for(AgentServiceSummary statusEvent : statusEventList){
values.add(UKTools.transBean2Map(statusEvent)) ;
}
response.setHeader("content-disposition", "attachment;filename=UCKeFu-Summary-History-"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+".xls");
ExcelExporterProcess excelProcess = new ExcelExporterProcess( values, table, response.getOutputStream()) ;
excelProcess.process();
return ;
}
@RequestMapping("/expsearch")
@Menu(type = "agent" , subtype = "agentsummary" , access = false)
public void expall(ModelMap map , HttpServletRequest request , HttpServletResponse response , @Valid final String begin , @Valid final String end ) throws IOException {
Page<AgentServiceSummary> page = serviceSummaryRes.findAll(new Specification<AgentServiceSummary>(){
@Override
public Predicate toPredicate(Root<AgentServiceSummary> root, CriteriaQuery<?> query,
CriteriaBuilder cb) {
List<Predicate> list = new ArrayList<Predicate>();
list.add(cb.and(cb.equal(root.get("process").as(boolean.class), 0))) ;
list.add(cb.and(cb.notEqual(root.get("channel").as(String.class), UKDataContext.ChannelTypeEnum.PHONE.toString()))) ;
try {
if(!StringUtils.isBlank(begin) && begin.matches("[\\d]{4}-[\\d]{2}-[\\d]{2} [\\d]{2}:[\\d]{2}:[\\d]{2}")){
list.add(cb.and(cb.greaterThan(root.get("createtime").as(Date.class), UKTools.dateFormate.parse(begin)))) ;
}
if(!StringUtils.isBlank(end) && end.matches("[\\d]{4}-[\\d]{2}-[\\d]{2} [\\d]{2}:[\\d]{2}:[\\d]{2}")){
list.add(cb.and(cb.lessThan(root.get("createtime").as(Date.class), UKTools.dateFormate.parse(end)))) ;
}
} catch (ParseException e) {
e.printStackTrace();
}
Predicate[] p = new Predicate[list.size()];
return cb.and(list.toArray(p));
}}, new PageRequest(0, 10000 , Sort.Direction.DESC, "createtime")) ;
List<Map<String,Object>> values = new ArrayList<Map<String,Object>>();
for(AgentServiceSummary summary : page){
values.add(UKTools.transBean2Map(summary)) ;
}
response.setHeader("content-disposition", "attachment;filename=UCKeFu-Summary-History-"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+".xls");
MetadataTable table = metadataRes.findByTablename("uk_servicesummary") ;
ExcelExporterProcess excelProcess = new ExcelExporterProcess( values, table, response.getOutputStream()) ;
excelProcess.process();
return ;
}
}
| gtison/kf | src/main/java/com/ukefu/webim/web/handler/apps/service/AgentSummaryController.java | Java | apache-2.0 | 10,167 |
// This is a generated file. Not intended for manual editing.
package org.dylanfoundry.deft.filetypes.lid.psi;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;
public interface LIDValues extends PsiElement {
PsiElement[] getValues();
}
| dylan-foundry/DeftIDEA | gen/org/dylanfoundry/deft/filetypes/lid/psi/LIDValues.java | Java | apache-2.0 | 288 |
package com.dengyuman.getcropimage;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Xingye on 6/16/2015.
*/
public class GetImageUtilsActivity extends Activity {
public static final int REQUSET_CAMERA = 1000;
public static final int REQUEST_CAMERA_CROP = 1001;
public static final int REQUEST_PICK = 1002;
public static final int REQUEST_PICK_CROP = 1003;
private static final int REQUEST_TO_CROP = 2000;
public static final String RESULT_KEY_SAVED_FILE_PATH = "result_saved_file_path";
/**
* NOTE: there is size limitation of Intent Extra, so the size must be small
*/
public static final String RESULT_KEY_THUMBNAIL_BITMAP = "result_thumbnail_bitmap";
public static final String PARRMETER_REQUEST_TYPE = "param_type";
public static final String PARAMETER_PREVIEW_WIDTH = "param_preview_width";
public static final String PARAMETER_PREVIEW_HEIGHT = "param_preview_height";
public static final String PARAMETER_THUMBNAIL_SIZE = "param_thumbnail_size";
/**
* NOTE: if crop image size is above limitation, it will be small (like 250) automatically
*/
public static final String PRRAMETER_CROP_WIDTH = "param_crop_width";
/**
* NOTE: if crop image size is above limitation, it will be small (like 250) automatically
*/
public static final String PRRAMETER_CROP_HEIGHT = "param_crop_height";
private static final int DEFAULT_THUMBNAIL_SIZE = 250;
private static final int DEFAULT_CROP_SIZE = 300;
private static final int DEFAULT_STORE_SIZE_LIMITATION = 800;
private static int storeSizeLimitation = DEFAULT_STORE_SIZE_LIMITATION;
private Uri imageFileUri;
private String cropFilePath;
private String tmpImageFile; // tmp file should be delete before quit
private int getImageRequestType;
private int previewWidth;
private int previewHeight;
private int thumbnailSize;
private int cropWidth;
private int cropHeight;
private static Bitmap previewBitmap;
/**
* get preview bitmap if set preview image size, it's available for take camera and pick picture
*
* @return
*/
public static Bitmap getPreviewBitmap() {
if (previewBitmap == null) {
return null;
}
Bitmap tmp = Bitmap.createBitmap(previewBitmap);
previewBitmap = null;
return tmp;
}
/**
* set default stored image size
*
* @param size
*/
public static void setDefaultStoreSizeLimitation(int size) {
storeSizeLimitation = size;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent inIntent = getIntent();
getImageRequestType = inIntent.getIntExtra(PARRMETER_REQUEST_TYPE, REQUSET_CAMERA);
thumbnailSize = inIntent.getIntExtra(PARAMETER_THUMBNAIL_SIZE, DEFAULT_THUMBNAIL_SIZE);
previewWidth = inIntent.getIntExtra(PARAMETER_PREVIEW_WIDTH, -1);
previewHeight = inIntent.getIntExtra(PARAMETER_PREVIEW_HEIGHT, -1);
cropWidth = inIntent.getIntExtra(PRRAMETER_CROP_WIDTH, DEFAULT_CROP_SIZE);
cropHeight = inIntent.getIntExtra(PRRAMETER_CROP_HEIGHT, DEFAULT_CROP_SIZE);
switch (getImageRequestType) {
case REQUSET_CAMERA:
captureCamera();
break;
case REQUEST_CAMERA_CROP:
captureCameraAndCrop();
break;
case REQUEST_PICK:
pickImage();
break;
case REQUEST_PICK_CROP:
pickImageAndCrop();
break;
}
}
private void captureCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageFileUri = StorageUtils.getNewCacheImageFileUri(this);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
startActivityForResult(intent, REQUSET_CAMERA);
}
private void captureCameraAndCrop() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageFileUri = StorageUtils.getNewCacheImageFileUri(this);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
startActivityForResult(intent, REQUEST_CAMERA_CROP);
}
private void pickImage() {
Intent intent = new Intent();
intent.setType("image/*");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
} else {
intent.setAction(Intent.ACTION_GET_CONTENT);
}
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(
Intent.createChooser(intent, getText(R.string.info_pick_image)),
REQUEST_PICK);
}
private void pickImageAndCrop() {
Intent intent = new Intent();
intent.setType("image/*");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
} else {
intent.setAction(Intent.ACTION_GET_CONTENT);
}
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(
Intent.createChooser(intent, getText(R.string.info_pick_image)),
REQUEST_PICK_CROP);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
boolean isNeedPreview = previewWidth > 0 && previewHeight > 0;
switch (requestCode) {
case REQUSET_CAMERA:
if (resultCode == Activity.RESULT_OK) {
Intent resultData = new Intent();
try {
Bitmap toSaveBitmap = ImageUtils.getResizedBitmap(this, imageFileUri,
false, storeSizeLimitation, storeSizeLimitation);
// quality 80, save file size is around 50 kb
String savedFilePath = StorageUtils.saveCompressedImage(this, toSaveBitmap, 80);
resultData.putExtra(RESULT_KEY_SAVED_FILE_PATH, savedFilePath);
} catch (Exception e) {
e.printStackTrace();
}
// thumbnail
try {
Bitmap thumbnail = ImageUtils.getResizedBitmap(this, imageFileUri,
true, thumbnailSize, thumbnailSize);
resultData.putExtra(RESULT_KEY_THUMBNAIL_BITMAP, thumbnail);
} catch (Exception e) {
e.printStackTrace();
}
// preview
if (isNeedPreview) {
try {
Bitmap preview = ImageUtils.getResizedBitmap(this, imageFileUri,
false, previewWidth, previewHeight);
previewBitmap = preview;
} catch (Exception e) {
e.printStackTrace();
}
}
setResult(Activity.RESULT_OK, resultData);
} else {
setResult(resultCode);
}
tmpImageFile = imageFileUri.getPath();
if (tmpImageFile != null) {
new File(tmpImageFile).delete();
}
finish();
break;
case REQUEST_CAMERA_CROP:
if (resultCode == Activity.RESULT_OK) {
tmpImageFile = imageFileUri.getPath();
doCrop();
} else {
setResult(resultCode);
finish();
}
break;
case REQUEST_PICK:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = data.getData();
Bitmap pickedImage = null;
String pickedImageFilePath = null;
Intent resultData = new Intent();
try {
pickedImage = ImageUtils.getResizedBitmap(this, selectedImageUri, false,
storeSizeLimitation, storeSizeLimitation);
pickedImageFilePath = StorageUtils.saveCompressedImage(this, pickedImage, 80);
pickedImage.recycle();
pickedImage = null;
resultData.putExtra(RESULT_KEY_SAVED_FILE_PATH, pickedImageFilePath);
} catch (Exception e) {
e.printStackTrace();
if (pickedImage == null) {
Toast.makeText(this, R.string.info_picked_image_deleted,
Toast.LENGTH_SHORT).show();
setResult(Activity.RESULT_CANCELED);
finish();
return;
}
}
if (pickedImageFilePath != null) {
// thumbnail
try {
Bitmap thumbnail = ImageUtils.getResizedBitmap(this, selectedImageUri,
true, thumbnailSize, thumbnailSize);
resultData.putExtra(RESULT_KEY_THUMBNAIL_BITMAP, thumbnail);
} catch (Exception e) {
e.printStackTrace();
}
// preview
if (isNeedPreview) {
try {
Bitmap preview = ImageUtils.getResizedBitmap(this, selectedImageUri,
false, previewWidth, previewHeight);
previewBitmap = preview;
} catch (Exception e) {
e.printStackTrace();
}
}
}
setResult(Activity.RESULT_OK, resultData);
} else {
setResult(resultCode);
}
finish();
break;
case REQUEST_PICK_CROP:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = data.getData();
Bitmap pickedImage = null;
Intent resultData = new Intent();
try {
pickedImage = ImageUtils.getResizedBitmap(this, selectedImageUri, false,
storeSizeLimitation, storeSizeLimitation);
tmpImageFile = StorageUtils.saveCompressedImage(this, pickedImage, 100);
pickedImage.recycle();
pickedImage = null;
imageFileUri = Uri.fromFile(new File(tmpImageFile));
doCrop();
} catch (Exception e) {
e.printStackTrace();
if (pickedImage == null) {
Toast.makeText(this, R.string.info_picked_image_deleted,
Toast.LENGTH_SHORT).show();
}
setResult(Activity.RESULT_CANCELED);
finish();
}
} else {
setResult(resultCode);
finish();
}
break;
case REQUEST_TO_CROP:
if (resultCode == Activity.RESULT_OK) {
Intent resultData = new Intent();
if (cropFilePath != null && new File(cropFilePath).exists()) {
resultData.putExtra(RESULT_KEY_SAVED_FILE_PATH, cropFilePath);
// thumbnail
try {
Bitmap thumbnail = ImageUtils.getResizedBitmap(cropFilePath, true,
thumbnailSize, thumbnailSize);
resultData.putExtra(RESULT_KEY_THUMBNAIL_BITMAP, thumbnail);
} catch (Exception e) {
e.printStackTrace();
}
}
setResult(Activity.RESULT_OK, resultData);
cropFilePath = null;
} else {
setResult(resultCode);
cropFilePath = null;
}
if (tmpImageFile != null) {
new File(tmpImageFile).delete();
}
finish();
break;
}
}
private void doCrop() {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities(
intent, 0);
int size = list.size();
if (size == 0) {
// rare condition: unable to find image crop app, resize it directly
fallbackCropToResizeAndReturn();
return;
}
intent.setData(imageFileUri);
intent.putExtra("outputX", cropWidth);
intent.putExtra("outputY", cropHeight);
intent.putExtra("aspectX", cropWidth);
intent.putExtra("aspectY", cropHeight);
intent.putExtra("scale", true);
// intent.putExtra("return-data", true);
intent.putExtra("noFaceDetection", true);
cropFilePath = StorageUtils.getStoredImageFilePath(this);
File f = new File(cropFilePath);
Uri uri = Uri.fromFile(f);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent(new ComponentName(res.activityInfo.packageName,
res.activityInfo.name));
startActivityForResult(i, REQUEST_TO_CROP);
} else {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getPackageManager().getApplicationLabel(
res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(
res.activityInfo.applicationInfo);
co.appIntent = new Intent(intent);
co.appIntent.setComponent(new ComponentName(
res.activityInfo.packageName, res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(
getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.info_pick_app_to_do);
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
startActivityForResult(cropOptions.get(item).appIntent, REQUEST_TO_CROP);
dialog.dismiss();
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
dialog.cancel();
}
});
builder.create().show();
}
}
private void fallbackCropToResizeAndReturn() {
Bitmap bitmap = null;
try {
bitmap = ImageUtils.getBitmapFromUri(this, imageFileUri);
Bitmap resized = Bitmap.createScaledBitmap(bitmap, cropWidth,
cropHeight, true);
String filePath = StorageUtils.saveCompressedImage(this,
resized, 100);
Intent resultData = new Intent();
resultData.putExtra(RESULT_KEY_SAVED_FILE_PATH, filePath);
setResult(Activity.RESULT_OK, resultData);
} catch (Exception e) {
e.printStackTrace();
setResult(Activity.RESULT_CANCELED);
} finally {
finish();
}
}
public class CropOptionAdapter extends ArrayAdapter<CropOption> {
private ArrayList<CropOption> mOptions;
private LayoutInflater mInflater;
public CropOptionAdapter(Context context, ArrayList<CropOption> options) {
super(context, R.layout.list_array_item_crop_selector, options);
mOptions = options;
mInflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup group) {
if (convertView == null) {
convertView = mInflater.inflate(
R.layout.list_array_item_crop_selector, null);
}
CropOption item = mOptions.get(position);
if (item != null) {
((ImageView) convertView.findViewById(R.id.iv_icon))
.setImageDrawable(item.icon);
((TextView) convertView.findViewById(R.id.tv_name))
.setText(item.title);
return convertView;
}
return null;
}
}
public class CropOption {
public CharSequence title;
public Drawable icon;
public Intent appIntent;
}
}
| freshleaf/getcropimage | getcropimage/src/main/java/com/dengyuman/getcropimage/GetImageUtilsActivity.java | Java | apache-2.0 | 18,555 |
package me.lukacat10.UUIDFetcherANDCache;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import me.lukacat10.exampleUUIDFetcherPlugin.MainJavaPlugin;
import org.bukkit.Bukkit;
/**
* This class allows developers to easily get UUIDs from names <br>
* or to do the reverse. <br>
* It has an implemented cache system, which makes sure it doesn't do a lookup <br>
* when not needed.
* <p>
* Date created: 17:13:57 2 apr. 2014
*
* @author Staartvin
*
*/
public class UUIDManager {
private static MainJavaPlugin plugin;
static {
plugin = (MainJavaPlugin) Bukkit.getPluginManager().getPlugin("Main");
}
private static Map<UUID, String> foundPlayers = new HashMap<UUID, String>();
private static Map<String, UUID> foundUUIDs = new HashMap<String, UUID>();
// Whether to use cache or not
private static final boolean useCache = true;
public static void addCachedPlayer(final String playerName, final UUID uuid) {
if (!useCache)
return;
plugin.getUUIDStorage().storeUUID(playerName, uuid);
//System.out.print("Cached " + uuid + " of " + playerName);
/*
cachedUUIDs.put(playerName, uuid);
lastCached.put(playerName, System.currentTimeMillis());*/
}
private static UUID getCachedUUID(final String playerName) {
return plugin.getUUIDStorage().getStoredUUID(playerName);
/*
// Already found
if (cachedUUIDs.containsKey(playerName))
return cachedUUIDs.get(playerName);
// Search for lowercase matches
for (final String loggedName : cachedUUIDs.keySet()) {
if (loggedName.equalsIgnoreCase(playerName)) {
playerName = loggedName;
break;
}
}
if (!cachedUUIDs.containsKey(playerName))
return null;
// Grab UUID
return cachedUUIDs.get(playerName);(*/
}
/**
* Get the Minecraft name of the player that is hooked to this Mojang
* account UUID. <br>
* It uses {@link #getPlayers(List)} to get the player's name.
*
* @param uuid the UUID of the Mojang account
* @return the name of player or null if not found.
*/
public static String getPlayerFromUUID(final UUID uuid) {
if (uuid == null)
return null;
final Map<UUID, String> players = getPlayers(Arrays.asList(uuid));
if (players == null)
return null;
if (players.isEmpty())
return null;
if (players.get(uuid) == null) {
throw new NullPointerException("Could not get player from UUID "
+ uuid + "!");
}
return players.get(uuid);
}
/**
* Get the player names associated with this UUID. <br>
* This method has to run async, because it will use the lookup from the
* Mojang API. <br>
* It also takes care of already cached values. It doesn't lookup new
* players when it still has old, valid ones stored.
*
* @param uuids A list of uuids to get the player names of.
* @return A map containing every player name per UUID.
*/
public static Map<UUID, String> getPlayers(final List<UUID> uuids) {
// Clear names first
foundPlayers.clear();
// A new map to store cached values
final HashMap<UUID, String> players = new HashMap<UUID, String>();
// This is used to check if we need to use the lookup from the mojang website.
boolean useInternetLookup = true;
if (useCache) {
// Check if we have cached values
for (final UUID uuid : uuids) {
final String playerName = plugin.getUUIDStorage()
.getPlayerName(uuid);
if (playerName != null) {
// If cached value is still valid, use it.
if (!plugin.getUUIDStorage().isOutdated(playerName)) {
players.put(uuid, playerName);
}
}
}
// All names were retrieved from cached values
// So we don't need to do a lookup to the Mojang website.
if (players.entrySet().size() == uuids.size()) {
useInternetLookup = false;
}
// No internet lookup needed.
if (!useInternetLookup) {
// Return all cached values.
return players;
}
// From here on we know that didn't have all uuids as cached values.
// So we need to do a lookup.
// We have to make sure we only lookup the players that we haven't got cached values of yet.
// Remove uuids that don't need to be looked up anymore.
// Just for performance sake.
for (final UUID entry : players.keySet()) {
uuids.remove(entry);
}
}
// Now we need to lookup the other players
final Thread fetcherThread = new Thread(new Runnable() {
@Override
public void run() {
final NameFetcher fetcher = new NameFetcher(uuids);
Map<UUID, String> response = null;
try {
response = fetcher.call();
} catch (final Exception e) {
if (e instanceof IOException) {
Bukkit.getLogger()
.warning(
"Tried to contact Mojang page for UUID lookup but failed.");
return;
}
e.printStackTrace();
}
if (response != null) {
foundPlayers = response;
}
}
});
fetcherThread.start();
if (fetcherThread.isAlive()) {
try {
fetcherThread.join();
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
// Update cached entries
for (final Entry<UUID, String> entry : foundPlayers.entrySet()) {
final String playerName = entry.getValue();
final UUID uuid = entry.getKey();
// Add found players to the list of players to return
players.put(uuid, playerName);
if (plugin.getUUIDStorage().isOutdated(playerName)) {
// Update cached values
addCachedPlayer(playerName, uuid);
} else {
// Do not update if it is not needed.
continue;
}
}
// Thread stopped now, collect results
return players;
}
/**
* Get the UUID of the Mojang account associated with this player name <br>
* It uses {@link #getUUIDs(List)} to get the UUID.
*
* @param playerName Name of the player
* @return UUID of the associated Mojang account or null if not found.
*/
public static UUID getUUIDFromPlayer(final String playerName) {
if (playerName == null) {
return null;
}
final Map<String, UUID> uuids = getUUIDs(Arrays.asList(playerName));
if (uuids == null) {
return null;
}
if (uuids.isEmpty()) {
return null;
}
// Search case insensitive
for (final Entry<String, UUID> entry : uuids.entrySet()) {
if (entry.getKey().equalsIgnoreCase(playerName)) {
return entry.getValue();
}
}
throw new NullPointerException("Could not get UUID from player "
+ playerName + "!");
}
/**
* Get the UUIDs of a list of players. <br>
* This method has to run async, because it will use the lookup from the
* Mojang API. <br>
* It also takes care of already cached values. It doesn't lookup new
* players when it still has old, valid ones stored.
*
* @param names A list of playernames that you want the UUIDs of.
* @return A map containing every UUID per player name.
*/
public static Map<String, UUID> getUUIDs(final List<String> names) {
// Clear maps first
foundUUIDs.clear();
// A new map to store cached values
final HashMap<String, UUID> uuids = new HashMap<String, UUID>();
// This is used to check if we need to use the lookup from the mojang website.
boolean useInternetLookup = true;
if (useCache) {
// Check if we have cached values
for (final String playerName : names) {
// If cached value is still valid, use it.
if (!plugin.getUUIDStorage().isOutdated(playerName)) {
uuids.put(playerName, getCachedUUID(playerName));
}
}
// All names were retrieved from cached values
// So we don't need to do a lookup to the Mojang website.
if (uuids.entrySet().size() == names.size()) {
useInternetLookup = false;
}
// No internet lookup needed.
if (!useInternetLookup) {
// Return all cached values.
return uuids;
}
// From here on we know that didn't have all uuids as cached values.
// So we need to do a lookup.
// We have to make sure we only lookup the players that we haven't got cached values of yet.
// Remove players that don't need to be looked up anymore.
// Just for performance sake.
for (final Entry<String, UUID> entry : uuids.entrySet()) {
names.remove(entry.getKey());
}
}
// Now we need to lookup the other players
final Thread fetcherThread = new Thread(new Runnable() {
@Override
public void run() {
final UUIDFetcher fetcher = new UUIDFetcher(names);
Map<String, UUID> response = null;
try {
response = fetcher.call();
} catch (final Exception e) {
if (e instanceof IOException) {
Bukkit.getLogger()
.warning(
"Tried to contact Mojang page for UUID lookup but failed.");
return;
}
e.printStackTrace();
}
if (response != null) {
foundUUIDs = response;
}
}
});
fetcherThread.start();
if (fetcherThread.isAlive()) {
try {
fetcherThread.join();
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
// Update cached entries
for (final Entry<String, UUID> entry : foundUUIDs.entrySet()) {
final String playerName = entry.getKey();
final UUID uuid = entry.getValue();
// Add found uuids to the list of uuids to return
uuids.put(playerName, uuid);
if (plugin.getUUIDStorage().isOutdated(playerName)) {
// Update cached values
addCachedPlayer(playerName, uuid);
} else {
// Do not update if it is not needed.
continue;
}
}
// Thread stopped now, collect results
return uuids;
}
}
| lukacat10/UUIDFetcher-Cache | src/main/java/me/lukacat10/UUIDFetcherANDCache/UUIDManager.java | Java | apache-2.0 | 9,517 |
package com.example.yaoxuehua.tourismattractionsapp.user;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.example.yaoxuehua.tourismattractionsapp.R;
import com.example.yaoxuehua.tourismattractionsapp.parent.activity.BaseLoginOrRegisterActivity;
/**
* Created by yaoxuehua on 16-10-19.
*/
public class RegisterActivity extends BaseLoginOrRegisterActivity {
private EditText phoneNumber, password;
private Button register_Button;
@Override
public void onClick(View v) {
super.onClick(v);
}
@Override
protected int getLayoutResId() {
return R.layout.register_activity;
}
@Override
protected void initView() {
phoneNumber = (EditText) findViewById(R.id.phone_editText);
password = (EditText) findViewById(R.id.password_editText);
register_Button = (Button) findViewById(R.id.register_Button);
}
@Override
protected void initListener() {
super.initListener();
changeStatus(phoneNumber, "phone");
changeStatus(password, "password");
register_Button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
@Override
protected void initData(Bundle savedInstanceState) {
}
/**
* 改变登陆按钮颜色
*/
public void changeButtonColor() {
if (passwordJust && phoneJust) {
register_Button.setBackgroundResource(R.drawable.content_bg_green);
} else {
register_Button.setBackgroundResource(R.drawable.content_bg_cyan);
}
}
}
| xuehuayao/Tourismattractions | app/src/main/java/com/example/yaoxuehua/tourismattractionsapp/user/RegisterActivity.java | Java | apache-2.0 | 1,707 |
package ru.job4j.array;
import java.util.Arrays;
/**
* Package for Array task #255.
*
*@author Idergunov(mailto:[email protected])
*@version $Id$
*@since 31.10.2017.
*/
/**
*Class for ArrayDuplicate.
*/
public class ArrayDuplicate {
/**
*@param array - массив.
*@return - возврат массива.
*/
public String[] remove(String[] array) {
int end = array.length - 1;
for (int i = 0; i < end; i++) {
for (int j = end; j > i; j--) {
if (array[i] == array[j]) {
String temp = array[end];
array[j] = array[end];
array[end] = temp;
end--;
}
}
}
return Arrays.copyOf(array, end + 1);
}
} | borisovich058/Idergunov | chapter_001/src/main/java/ru/job4j/array/ArrayDuplicate.java | Java | apache-2.0 | 646 |
/*
* Copyright 2016 The Sem 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 org.thesemproject.opensem.gui.modelEditor;
import javax.swing.tree.DefaultMutableTreeNode;
/**
*
* @author The Sem Project
*/
public class ClassicationTreeNode extends DefaultMutableTreeNode {
/**
* Contine le info se il nodo è istruito
*/
private boolean trained;
/**
* Crea il nodo
* @param isTrained true se istruito
*/
public ClassicationTreeNode(boolean isTrained) {
this.trained = isTrained;
}
/**
* Crea il nodo
* @param isTrained true se istruito
* @param o oggetto del nodo
*/
public ClassicationTreeNode(boolean isTrained, Object o) {
super(o);
this.trained = isTrained;
}
/**
* Crea il nodo
* @param isTrained true se istruito
* @param o oggetto
* @param bln vedi DefaultMutableTreeNode
*/
public ClassicationTreeNode(boolean isTrained, Object o, boolean bln) {
super(o, bln);
this.trained = isTrained;
}
/**
*
* @return ritorna true se istruito
*/
public boolean isTrained() {
return trained;
}
/**
* Imposta lo stato di istruzione
* @param isTrained true se istruito
*/
public void setTrained(boolean isTrained) {
this.trained = isTrained;
}
}
| fiohol/theSemProject | openSem/src/main/java/org/thesemproject/opensem/gui/modelEditor/ClassicationTreeNode.java | Java | apache-2.0 | 1,923 |
/**
* Copyright (C) 2010-2013 Alibaba Group Holding Limited
*
* 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.alibaba.rocketmq.remoting.exception;
/**
* 异步调用或者Oneway调用,堆积的请求超过信号量最大值
*
* @author shijia.wxr<[email protected]>
* @since 2013-7-13
*/
public class RemotingTooMuchRequestException extends RemotingException {
private static final long serialVersionUID = 4326919581254519654L;
public RemotingTooMuchRequestException(String message) {
super(message);
}
}
| dingjun84/mq-backup | rocketmq-remoting/src/main/java/com/alibaba/rocketmq/remoting/exception/RemotingTooMuchRequestException.java | Java | apache-2.0 | 1,097 |
package com.excelian.mache.events.integration.builder;
import com.excelian.mache.events.MQFactory;
import com.excelian.mache.events.integration.RabbitMQFactory;
import com.excelian.mache.events.integration.RabbitMQConfig;
import com.excelian.mache.events.integration.RabbitMQConfig.RabbitMQConfigBuilder;
import com.excelian.mache.observable.builder.AbstractMessagingProvisioner;
import com.rabbitmq.client.ConnectionFactory;
import javax.jms.JMSException;
import java.io.IOException;
/**
* Provisions Rabbit MQ messaging from config.
*
* @param <K> the key type.
* @param <V> the value type.
*/
public class RabbitMQMessagingProvisioner<K, V> extends AbstractMessagingProvisioner<K, V> {
private final ConnectionFactory connectionFactory;
private final RabbitMQConfig rabbitMqConfig;
private RabbitMQMessagingProvisioner(String topic,
ConnectionFactory connectionFactory,
RabbitMQConfig rabbitMqConfig) {
super(topic);
this.connectionFactory = connectionFactory;
this.rabbitMqConfig = rabbitMqConfig;
}
@Override
public MQFactory<K> getMqFactory() throws IOException, JMSException {
return new RabbitMQFactory<>(connectionFactory, rabbitMqConfig);
}
public static TopicBuilder rabbitMq() {
return topic -> connectionFactory -> new RabbitMqMessagingProvisionerBuilder(topic, connectionFactory);
}
/**
* Enforces topic to be specified.
*/
public interface TopicBuilder {
ConnectionFactoryBuilder withTopic(String topic);
}
/**
* Enforces connection details to be specified.
*/
public interface ConnectionFactoryBuilder {
RabbitMqMessagingProvisionerBuilder withConnectionFactory(ConnectionFactory connectionFactory);
}
/**
* Builder for Rabbit MQ.
*/
public static class RabbitMqMessagingProvisionerBuilder {
private final String topic;
private final ConnectionFactory connectionFactory;
private RabbitMQConfig rabbitMqConfig = RabbitMQConfigBuilder.builder().build();
public RabbitMqMessagingProvisionerBuilder(String topic, ConnectionFactory connectionFactory) {
this.topic = topic;
this.connectionFactory = connectionFactory;
}
public RabbitMqMessagingProvisionerBuilder withRabbitMqConfig(RabbitMQConfig rabbitMqConfig) {
this.rabbitMqConfig = rabbitMqConfig;
return this;
}
public <K, V> RabbitMQMessagingProvisioner<K, V> build() {
connectionFactory.setNetworkRecoveryInterval(rabbitMqConfig.getNetworkRecoveryInterval());
return new RabbitMQMessagingProvisioner<>(topic, connectionFactory, rabbitMqConfig);
}
}
}
| Excelian/Mache | mache-rabbit/src/main/java/com/excelian/mache/events/integration/builder/RabbitMQMessagingProvisioner.java | Java | apache-2.0 | 2,821 |
/*
* Copyright 2019 NAVER Corp.
*
* 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.navercorp.pinpoint.collector.cluster;
import com.google.protobuf.GeneratedMessageV3;
import com.navercorp.pinpoint.collector.receiver.grpc.PinpointGrpcServer;
import com.navercorp.pinpoint.profiler.context.grpc.CommandThriftToGrpcMessageConverter;
import com.navercorp.pinpoint.rpc.DefaultFuture;
import com.navercorp.pinpoint.rpc.Future;
import com.navercorp.pinpoint.rpc.PinpointSocketException;
import com.navercorp.pinpoint.rpc.ResponseMessage;
import com.navercorp.pinpoint.rpc.packet.stream.StreamCode;
import com.navercorp.pinpoint.rpc.stream.ClientStreamChannel;
import com.navercorp.pinpoint.rpc.stream.ClientStreamChannelEventHandler;
import com.navercorp.pinpoint.rpc.stream.StreamException;
import com.navercorp.pinpoint.thrift.dto.command.TRouteResult;
import com.navercorp.pinpoint.thrift.io.TCommandType;
import org.apache.thrift.TBase;
import java.util.List;
import java.util.Objects;
/**
* @author Taejin Koo
*/
public class GrpcAgentConnection implements ClusterPoint<TBase> {
private final CommandThriftToGrpcMessageConverter messageConverter = new CommandThriftToGrpcMessageConverter();
private final PinpointGrpcServer pinpointGrpcServer;
private final List<TCommandType> supportCommandList;
public GrpcAgentConnection(PinpointGrpcServer pinpointGrpcServer, List<Integer> supportCommandServiceKeyList) {
this.pinpointGrpcServer = Objects.requireNonNull(pinpointGrpcServer, "pinpointGrpcServer");
Objects.requireNonNull(supportCommandServiceKeyList, "supportCommandServiceKeyList");
this.supportCommandList = SupportedCommandUtils.newSupportCommandList(supportCommandServiceKeyList);
}
@Override
public Future<ResponseMessage> request(TBase request) {
GeneratedMessageV3 message = messageConverter.toMessage(request);
if (message == null) {
DefaultFuture<ResponseMessage> failedFuture = new DefaultFuture<ResponseMessage>();
failedFuture.setFailure(new PinpointSocketException(TRouteResult.NOT_SUPPORTED_REQUEST.name()));
return failedFuture;
}
return pinpointGrpcServer.request(message);
}
public ClientStreamChannel openStream(TBase request, ClientStreamChannelEventHandler streamChannelEventHandler) throws StreamException {
GeneratedMessageV3 message = messageConverter.toMessage(request);
if (message == null) {
throw new StreamException(StreamCode.TYPE_UNSUPPORT);
}
return pinpointGrpcServer.openStream(message, streamChannelEventHandler);
}
@Override
public AgentInfo getDestAgentInfo() {
return pinpointGrpcServer.getAgentInfo();
}
@Override
public boolean isSupportCommand(TBase command) {
for (TCommandType supportCommand : supportCommandList) {
if (supportCommand.getClazz() == command.getClass()) {
return true;
}
}
return false;
}
@Override
public int hashCode() {
return pinpointGrpcServer.getAgentInfo().hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof GrpcAgentConnection)) {
return false;
}
if (this.pinpointGrpcServer == ((GrpcAgentConnection) obj).pinpointGrpcServer) {
return true;
}
return false;
}
}
| Xylus/pinpoint | collector/src/main/java/com/navercorp/pinpoint/collector/cluster/GrpcAgentConnection.java | Java | apache-2.0 | 4,033 |
package org.apache.maven.plugins.enforcer;
/*
* 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.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.ResolutionScope;
/**
* This goal has been deprecated.
*
* @deprecated
* @author <a href="mailto:[email protected]">Brian Fox</a>
* @version $Id$
*/
@Mojo( name = "enforce-once", defaultPhase = LifecyclePhase.VALIDATE, threadSafe = true,
requiresDependencyResolution = ResolutionScope.TEST )
public class EnforceOnceMojo
extends EnforceMojo
{
public void execute()
throws MojoExecutionException
{
this.getLog().warn( "enforcer:enforce-once is deprecated. Use enforcer:enforce instead. See MENFORCER-11/MENFORCER-12 for more information." );
super.execute();
}
}
| lkwg82/enforcer-maven-plugin | src/main/java/org/apache/maven/plugins/enforcer/EnforceOnceMojo.java | Java | apache-2.0 | 1,686 |
/*
* Copyright (c) 2010-2015 Evolveum
*
* 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.evolveum.midpoint.web.page.admin.configuration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.evolveum.midpoint.web.application.Url;
import com.evolveum.midpoint.web.page.admin.configuration.component.*;
import com.evolveum.midpoint.web.page.admin.configuration.dto.*;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import org.apache.commons.lang.StringUtils;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.markup.html.tabs.AbstractTab;
import org.apache.wicket.extensions.markup.html.tabs.ITab;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.util.string.StringValue;
import com.evolveum.midpoint.gui.api.model.LoadableModel;
import com.evolveum.midpoint.gui.api.util.WebComponentUtil;
import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.delta.DiffUtil;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.schema.GetOperationOptions;
import com.evolveum.midpoint.schema.SelectorOptions;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.security.api.AuthorizationConstants;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.web.application.AuthorizationAction;
import com.evolveum.midpoint.web.application.PageDescriptor;
import com.evolveum.midpoint.web.component.AjaxButton;
import com.evolveum.midpoint.web.component.AjaxSubmitButton;
import com.evolveum.midpoint.web.component.TabbedPanel;
import com.evolveum.midpoint.web.component.form.Form;
import com.evolveum.midpoint.web.page.error.PageError;
import com.evolveum.prism.xml.ns._public.types_3.ItemPathType;
/**
* @author lazyman
*/
@PageDescriptor(
urls = {
@Url(mountUrl = "/admin/config", matchUrlForSecurity = "/admin/config"),
@Url(mountUrl = "/admin/config/system"),
},
action = {
@AuthorizationAction(actionUri = PageAdminConfiguration.AUTH_CONFIGURATION_ALL,
label = PageAdminConfiguration.AUTH_CONFIGURATION_ALL_LABEL,
description = PageAdminConfiguration.AUTH_CONFIGURATION_ALL_DESCRIPTION),
@AuthorizationAction(actionUri = AuthorizationConstants.AUTZ_UI_CONFIGURATION_SYSTEM_CONFIG_URL,
label = "PageSystemConfiguration.auth.configSystemConfiguration.label",
description = "PageSystemConfiguration.auth.configSystemConfiguration.description")
})
public class PageSystemConfiguration extends PageAdminConfiguration {
public static final String SELECTED_TAB_INDEX = "tab";
public static final int CONFIGURATION_TAB_BASIC = 0;
public static final int CONFIGURATION_TAB_NOTIFICATION = 1;
public static final int CONFIGURATION_TAB_LOGGING = 2;
public static final int CONFIGURATION_TAB_PROFILING = 3;
public static final int CONFIGURATION_TAB_ADMIN_GUI = 4;
private static final Trace LOGGER = TraceManager.getTrace(PageSystemConfiguration.class);
private static final String DOT_CLASS = PageSystemConfiguration.class.getName() + ".";
private static final String TASK_GET_SYSTEM_CONFIG = DOT_CLASS + "getSystemConfiguration";
private static final String TASK_UPDATE_SYSTEM_CONFIG = DOT_CLASS + "updateSystemConfiguration";
private static final String ID_MAIN_FORM = "mainForm";
private static final String ID_TAB_PANEL = "tabPanel";
private static final String ID_CANCEL = "cancel";
private static final String ID_SAVE = "save";
public static final String ROOT_APPENDER_INHERITANCE_CHOICE = "(Inherit root)";
private LoggingConfigPanel loggingConfigPanel;
private ProfilingConfigPanel profilingConfigPanel;
private SystemConfigPanel systemConfigPanel;
private AdminGuiConfigPanel adminGuiConfigPanel;
private NotificationConfigPanel notificationConfigPanel;
private LoadableModel<SystemConfigurationDto> model;
private boolean initialized;
public PageSystemConfiguration() {
this(null);
}
public PageSystemConfiguration(PageParameters parameters) {
super(parameters);
model = new LoadableModel<SystemConfigurationDto>(false) {
@Override
protected SystemConfigurationDto load() {
return loadSystemConfiguration();
}
};
initLayout();
}
private SystemConfigurationDto loadSystemConfiguration() {
Task task = createSimpleTask(TASK_GET_SYSTEM_CONFIG);
OperationResult result = new OperationResult(TASK_GET_SYSTEM_CONFIG);
Collection<SelectorOptions<GetOperationOptions>> options = SelectorOptions.createCollection(
GetOperationOptions.createResolve(), SystemConfigurationType.F_DEFAULT_USER_TEMPLATE,
SystemConfigurationType.F_GLOBAL_PASSWORD_POLICY);
SystemConfigurationDto dto = null;
try {
PrismObject<SystemConfigurationType> systemConfig = WebModelServiceUtils.loadObject(
SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), options,
this, task, result);
dto = new SystemConfigurationDto(systemConfig);
result.recordSuccess();
} catch (Exception ex) {
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load system configuration", ex);
result.recordFatalError("Couldn't load system configuration.", ex);
}
// what do you do with null? many components depends on this not to be
// null :)
if (!WebComponentUtil.isSuccessOrHandledError(result) || dto == null) {
showResult(result, false);
throw getRestartResponseException(PageError.class);
}
return dto;
}
private void initLayout() {
Form mainForm = new Form(ID_MAIN_FORM, true);
add(mainForm);
List<ITab> tabs = new ArrayList<>();
tabs.add(new AbstractTab(createStringResource("pageSystemConfiguration.system.title")) {
@Override
public WebMarkupContainer getPanel(String panelId) {
systemConfigPanel = new SystemConfigPanel(panelId, model);
return systemConfigPanel;
}
});
tabs.add(new AbstractTab(createStringResource("pageSystemConfiguration.notifications.title")) {
@Override
public WebMarkupContainer getPanel(String panelId) {
notificationConfigPanel = new NotificationConfigPanel(panelId,
new PropertyModel<NotificationConfigurationDto>(model, "notificationConfig"));
return notificationConfigPanel;
}
});
tabs.add(new AbstractTab(createStringResource("pageSystemConfiguration.logging.title")) {
@Override
public WebMarkupContainer getPanel(String panelId) {
loggingConfigPanel = new LoggingConfigPanel(panelId,
new PropertyModel<LoggingDto>(model, "loggingConfig"));
return loggingConfigPanel;
}
});
tabs.add(new AbstractTab(createStringResource("pageSystemConfiguration.profiling.title")) {
@Override
public WebMarkupContainer getPanel(String panelId) {
profilingConfigPanel = new ProfilingConfigPanel(panelId,
new PropertyModel<ProfilingDto>(model, "profilingDto"), PageSystemConfiguration.this);
return profilingConfigPanel;
}
});
tabs.add(new AbstractTab(createStringResource("pageSystemConfiguration.adminGui.title")) {
@Override
public WebMarkupContainer getPanel(String panelId) {
adminGuiConfigPanel = new AdminGuiConfigPanel(panelId, model);
return adminGuiConfigPanel;
}
});
TabbedPanel tabPanel = new TabbedPanel(ID_TAB_PANEL, tabs) {
@Override
protected void onTabChange(int index) {
PageParameters params = getPageParameters();
params.set(SELECTED_TAB_INDEX, index);
}
};
tabPanel.setOutputMarkupId(true);
mainForm.add(tabPanel);
initButtons(mainForm);
}
@Override
protected void onBeforeRender() {
super.onBeforeRender();
if (!initialized) {
PageParameters params = getPageParameters();
StringValue val = params.get(SELECTED_TAB_INDEX);
String value = null;
if (val != null && !val.isNull()) {
value = val.toString();
}
int index = StringUtils.isNumeric(value) ? Integer.parseInt(value) : CONFIGURATION_TAB_BASIC;
getTabPanel().setSelectedTab(index);
initialized = true;
}
}
private void initButtons(Form mainForm) {
AjaxSubmitButton save = new AjaxSubmitButton(ID_SAVE, createStringResource("PageBase.button.save")) {
@Override
protected void onSubmit(AjaxRequestTarget target,
org.apache.wicket.markup.html.form.Form<?> form) {
savePerformed(target);
}
@Override
protected void onError(AjaxRequestTarget target, org.apache.wicket.markup.html.form.Form form) {
target.add(getFeedbackPanel());
}
};
mainForm.add(save);
AjaxButton cancel = new AjaxButton(ID_CANCEL, createStringResource("PageBase.button.cancel")) {
@Override
public void onClick(AjaxRequestTarget target) {
cancelPerformed(target);
}
};
mainForm.add(cancel);
}
private TabbedPanel getTabPanel() {
return (TabbedPanel) get(createComponentPath(ID_MAIN_FORM, ID_TAB_PANEL));
}
private void savePerformed(AjaxRequestTarget target) {
OperationResult result = new OperationResult(TASK_UPDATE_SYSTEM_CONFIG);
String oid = SystemObjectsType.SYSTEM_CONFIGURATION.value();
Task task = createSimpleTask(TASK_UPDATE_SYSTEM_CONFIG);
try {
SystemConfigurationType newObject = model.getObject().getNewObject();
saveObjectPolicies(newObject);
saveAdminGui(newObject);
ObjectDelta<SystemConfigurationType> delta = DiffUtil.diff(model.getObject().getOldObject(), newObject);
delta.normalize();
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("System configuration delta:\n{}", delta.debugDump());
}
if (!delta.isEmpty()) {
getPrismContext().adopt(delta);
getModelService().executeChanges(WebComponentUtil.createDeltaCollection(delta), null, task, result);
}
result.computeStatusIfUnknown();
} catch (Exception e) {
result.recomputeStatus();
result.recordFatalError("Couldn't save system configuration.", e);
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't save system configuration.", e);
}
showResult(result);
target.add(getFeedbackPanel());
resetPerformed(target);
}
private void saveObjectPolicies(SystemConfigurationType systemConfig) {
if (systemConfigPanel == null) {
return;
}
List<ObjectPolicyConfigurationTypeDto> configList = systemConfigPanel.getModel().getObject()
.getObjectPolicyList();
List<ObjectPolicyConfigurationType> confList = new ArrayList<>();
ObjectPolicyConfigurationType newObjectPolicyConfig;
for (ObjectPolicyConfigurationTypeDto o : configList) {
if (o.isEmpty()){
continue;
}
newObjectPolicyConfig = new ObjectPolicyConfigurationType();
newObjectPolicyConfig.setType(o.getType());
newObjectPolicyConfig.setSubtype(o.getSubtype());
newObjectPolicyConfig.setObjectTemplateRef(o.getTemplateRef());
List<PropertyConstraintType> constraintList = new ArrayList<>();
PropertyConstraintType property;
if (o.getConstraints() != null) {
for (PropertyConstraintTypeDto c : o.getConstraints()) {
if (StringUtils.isNotEmpty(c.getPropertyPath())) {
property = new PropertyConstraintType();
property.setOidBound(c.isOidBound());
property.setPath(new ItemPathType(c.getPropertyPath()));
constraintList.add(property);
}
}
}
newObjectPolicyConfig.getPropertyConstraint().addAll(constraintList);
newObjectPolicyConfig.setConflictResolution(o.getConflictResolution());
confList.add(newObjectPolicyConfig);
}
if (confList.isEmpty()){
if (!systemConfig.getDefaultObjectPolicyConfiguration().isEmpty()){
systemConfig.getDefaultObjectPolicyConfiguration().clear();
}
return;
}
systemConfig.getDefaultObjectPolicyConfiguration().clear();
systemConfig.getDefaultObjectPolicyConfiguration().addAll(confList);
}
private void saveAdminGui(SystemConfigurationType systemConfig) {
if (adminGuiConfigPanel == null) {
return;
}
SystemConfigurationDto linksList = adminGuiConfigPanel.getModel().getObject();
//update userDashboardLink list
systemConfig.getAdminGuiConfiguration().getUserDashboardLink().clear();
systemConfig.getAdminGuiConfiguration().getUserDashboardLink().addAll(linksList.getUserDashboardLink());
//update additionalMenu list
systemConfig.getAdminGuiConfiguration().getAdditionalMenuLink().clear();
systemConfig.getAdminGuiConfiguration().getAdditionalMenuLink().addAll(linksList.getAdditionalMenuLink());
}
private void resetPerformed(AjaxRequestTarget target) {
int index = getTabPanel().getSelectedTab();
PageParameters params = new PageParameters();
params.add(SELECTED_TAB_INDEX, index);
PageSystemConfiguration page = new PageSystemConfiguration(params);
setResponsePage(page);
}
private void cancelPerformed(AjaxRequestTarget target) {
resetPerformed(target);
}
}
| Pardus-Engerek/engerek | gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/PageSystemConfiguration.java | Java | apache-2.0 | 13,604 |
/*
* Copyright 2014-2019 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.medialive.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.medialive.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* HlsBasicPutSettingsMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class HlsBasicPutSettingsMarshaller {
private static final MarshallingInfo<Integer> CONNECTIONRETRYINTERVAL_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("connectionRetryInterval").build();
private static final MarshallingInfo<Integer> FILECACHEDURATION_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("filecacheDuration").build();
private static final MarshallingInfo<Integer> NUMRETRIES_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("numRetries").build();
private static final MarshallingInfo<Integer> RESTARTDELAY_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("restartDelay").build();
private static final HlsBasicPutSettingsMarshaller instance = new HlsBasicPutSettingsMarshaller();
public static HlsBasicPutSettingsMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(HlsBasicPutSettings hlsBasicPutSettings, ProtocolMarshaller protocolMarshaller) {
if (hlsBasicPutSettings == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(hlsBasicPutSettings.getConnectionRetryInterval(), CONNECTIONRETRYINTERVAL_BINDING);
protocolMarshaller.marshall(hlsBasicPutSettings.getFilecacheDuration(), FILECACHEDURATION_BINDING);
protocolMarshaller.marshall(hlsBasicPutSettings.getNumRetries(), NUMRETRIES_BINDING);
protocolMarshaller.marshall(hlsBasicPutSettings.getRestartDelay(), RESTARTDELAY_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| jentfoo/aws-sdk-java | aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/transform/HlsBasicPutSettingsMarshaller.java | Java | apache-2.0 | 3,044 |
package com.coolweather.android.db;
import org.litepal.crud.DataSupport;
/**
* Created by 子文 on 2017/5/15.
*/
public class City extends DataSupport{
private int id;
private String cityName;
private int cityCode;
private int provinceId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public int getCityCode() {
return cityCode;
}
public void setCityCode(int cityCode) {
this.cityCode = cityCode;
}
public int getProvinceId() {
return provinceId;
}
public void setProvinceId(int provinceId) {
this.provinceId = provinceId;
}
}
| zhaowenzi/coolweather | app/src/main/java/com/coolweather/android/db/City.java | Java | apache-2.0 | 837 |
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.roots.ui.configuration;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.roots.impl.RootConfigurationAccessor;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.ui.configuration.projectRoot.ModuleStructureConfigurable;
import com.intellij.openapi.roots.ui.configuration.projectRoot.ProjectJdksModel;
import com.intellij.openapi.roots.ui.configuration.projectRoot.StructureConfigurableContext;
import org.jetbrains.annotations.Nullable;
/**
* @author yole
*/
public class UIRootConfigurationAccessor extends RootConfigurationAccessor {
private final Project myProject;
public UIRootConfigurationAccessor(final Project project) {
myProject = project;
}
@Nullable
public Library getLibrary(Library library, final String libraryName, final String libraryLevel) {
final StructureConfigurableContext context = ProjectStructureConfigurable.getInstance(myProject).getContext();
if (library == null) {
if (libraryName != null) {
library = context.getLibrary(libraryName, libraryLevel);
}
} else {
library = context.getLibrary(library.getName(), library.getTable().getTableLevel());
}
return library;
}
@Nullable
public Sdk getSdk(final Sdk sdk, final String sdkName) {
final ProjectJdksModel model = ProjectStructureConfigurable.getInstance(myProject).getJdkConfig().getJdksTreeModel();
return sdkName != null ? model.findSdk(sdkName) : sdk;
}
public Module getModule(final Module module, final String moduleName) {
if (module == null) {
return ModuleStructureConfigurable.getInstance(myProject).getModule(moduleName);
}
return module;
}
public Sdk getProjectSdk(final Project project) {
return ProjectJdksModel.getInstance(project).getProjectJdk();
}
public String getProjectSdkName(final Project project) {
final String projectJdkName = ProjectRootManager.getInstance(project).getProjectJdkName();
final Sdk projectJdk = getProjectSdk(project);
if (projectJdk != null) {
return projectJdk.getName();
}
else {
return ProjectJdksModel.getInstance(project).findSdk(projectJdkName) == null ? projectJdkName : null;
}
}
}
| jexp/idea2 | java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/UIRootConfigurationAccessor.java | Java | apache-2.0 | 3,000 |
/*
* Copyright 2016 "Henry Tao <[email protected]>"
*
* 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 me.henrytao.mddemo.activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import butterknife.Bind;
import butterknife.ButterKnife;
import me.henrytao.mddemo.R;
/**
* Created by henrytao on 5/5/16.
*/
public class TextFieldActivity extends BaseActivity {
@Bind(R.id.toolbar)
Toolbar vToolbar;
@Override
protected int getDefaultLayout() {
return R.layout.activity_text_field;
}
@Override
protected int getMdCoreLayout() {
return R.layout.activity_text_field;
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ButterKnife.bind(this);
setSupportActionBar(vToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
vToolbar.setNavigationOnClickListener(v -> onBackPressed());
}
}
| henrytao-me/android-md-core | sample/src/main/java/me/henrytao/mddemo/activity/TextFieldActivity.java | Java | apache-2.0 | 1,491 |
/*
* #%L
* Conserve Concept Server
* %%
* Copyright (C) 2010 - 2011 KMR
* %%
* 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.
* #L%
*/
package se.kth.csc.kmr.conserve.data.jpa;
import java.util.UUID;
public class ConceptId {
public final UUID uuid;
public final UUID entry;
public ConceptId(UUID uuid, UUID entry) {
this.uuid = uuid;
this.entry = entry;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((entry == null) ? 0 : entry.hashCode());
result = prime * result + ((uuid == null) ? 0 : uuid.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ConceptId other = (ConceptId) obj;
if (entry == null) {
if (other.entry != null)
return false;
} else if (!entry.equals(other.entry))
return false;
if (uuid == null) {
if (other.uuid != null)
return false;
} else if (!uuid.equals(other.uuid))
return false;
return true;
}
}
| rwth-acis/ROLE-SDK | services/conserve-service/src/main/java/se/kth/csc/kmr/conserve/data/jpa/ConceptId.java | Java | apache-2.0 | 1,603 |
/**
* Apache License
* Version 2.0, January 2004
* http://www.apache.org/licenses/
*
* TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
*
* 1. Definitions.
*
* "License" shall mean the terms and conditions for use, reproduction,
* and distribution as defined by Sections 1 through 9 of this document.
*
* "Licensor" shall mean the copyright owner or entity authorized by
* the copyright owner that is granting the License.
*
* "Legal Entity" shall mean the union of the acting entity and all
* other entities that control, are controlled by, or are under common
* control with that entity. For the purposes of this definition,
* "control" means (i) the power, direct or indirect, to cause the
* direction or management of such entity, whether by contract or
* otherwise, or (ii) ownership of fifty percent (50%) or more of the
* outstanding shares, or (iii) beneficial ownership of such entity.
*
* "You" (or "Your") shall mean an individual or Legal Entity
* exercising permissions granted by this License.
*
* "Source" form shall mean the preferred form for making modifications,
* including but not limited to software source code, documentation
* source, and configuration files.
*
* "Object" form shall mean any form resulting from mechanical
* transformation or translation of a Source form, including but
* not limited to compiled object code, generated documentation,
* and conversions to other media types.
*
* "Work" shall mean the work of authorship, whether in Source or
* Object form, made available under the License, as indicated by a
* copyright notice that is included in or attached to the work
* (an example is provided in the Appendix below).
*
* "Derivative Works" shall mean any work, whether in Source or Object
* form, that is based on (or derived from) the Work and for which the
* editorial revisions, annotations, elaborations, or other modifications
* represent, as a whole, an original work of authorship. For the purposes
* of this License, Derivative Works shall not include works that remain
* separable from, or merely link (or bind by name) to the interfaces of,
* the Work and Derivative Works thereof.
*
* "Contribution" shall mean any work of authorship, including
* the original version of the Work and any modifications or additions
* to that Work or Derivative Works thereof, that is intentionally
* submitted to Licensor for inclusion in the Work by the copyright owner
* or by an individual or Legal Entity authorized to submit on behalf of
* the copyright owner. For the purposes of this definition, "submitted"
* means any form of electronic, verbal, or written communication sent
* to the Licensor or its representatives, including but not limited to
* communication on electronic mailing lists, source code control systems,
* and issue tracking systems that are managed by, or on behalf of, the
* Licensor for the purpose of discussing and improving the Work, but
* excluding communication that is conspicuously marked or otherwise
* designated in writing by the copyright owner as "Not a Contribution."
*
* "Contributor" shall mean Licensor and any individual or Legal Entity
* on behalf of whom a Contribution has been received by Licensor and
* subsequently incorporated within the Work.
*
* 2. Grant of Copyright License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* copyright license to reproduce, prepare Derivative Works of,
* publicly display, publicly perform, sublicense, and distribute the
* Work and such Derivative Works in Source or Object form.
*
* 3. Grant of Patent License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* (except as stated in this section) patent license to make, have made,
* use, offer to sell, sell, import, and otherwise transfer the Work,
* where such license applies only to those patent claims licensable
* by such Contributor that are necessarily infringed by their
* Contribution(s) alone or by combination of their Contribution(s)
* with the Work to which such Contribution(s) was submitted. If You
* institute patent litigation against any entity (including a
* cross-claim or counterclaim in a lawsuit) alleging that the Work
* or a Contribution incorporated within the Work constitutes direct
* or contributory patent infringement, then any patent licenses
* granted to You under this License for that Work shall terminate
* as of the date such litigation is filed.
*
* 4. Redistribution. You may reproduce and distribute copies of the
* Work or Derivative Works thereof in any medium, with or without
* modifications, and in Source or Object form, provided that You
* meet the following conditions:
*
* (a) You must give any other recipients of the Work or
* Derivative Works a copy of this License; and
*
* (b) You must cause any modified files to carry prominent notices
* stating that You changed the files; and
*
* (c) You must retain, in the Source form of any Derivative Works
* that You distribute, all copyright, patent, trademark, and
* attribution notices from the Source form of the Work,
* excluding those notices that do not pertain to any part of
* the Derivative Works; and
*
* (d) If the Work includes a "NOTICE" text file as part of its
* distribution, then any Derivative Works that You distribute must
* include a readable copy of the attribution notices contained
* within such NOTICE file, excluding those notices that do not
* pertain to any part of the Derivative Works, in at least one
* of the following places: within a NOTICE text file distributed
* as part of the Derivative Works; within the Source form or
* documentation, if provided along with the Derivative Works; or,
* within a display generated by the Derivative Works, if and
* wherever such third-party notices normally appear. The contents
* of the NOTICE file are for informational purposes only and
* do not modify the License. You may add Your own attribution
* notices within Derivative Works that You distribute, alongside
* or as an addendum to the NOTICE text from the Work, provided
* that such additional attribution notices cannot be construed
* as modifying the License.
*
* You may add Your own copyright statement to Your modifications and
* may provide additional or different license terms and conditions
* for use, reproduction, or distribution of Your modifications, or
* for any such Derivative Works as a whole, provided Your use,
* reproduction, and distribution of the Work otherwise complies with
* the conditions stated in this License.
*
* 5. Submission of Contributions. Unless You explicitly state otherwise,
* any Contribution intentionally submitted for inclusion in the Work
* by You to the Licensor shall be under the terms and conditions of
* this License, without any additional terms or conditions.
* Notwithstanding the above, nothing herein shall supersede or modify
* the terms of any separate license agreement you may have executed
* with Licensor regarding such Contributions.
*
* 6. Trademarks. This License does not grant permission to use the trade
* names, trademarks, service marks, or product names of the Licensor,
* except as required for reasonable and customary use in describing the
* origin of the Work and reproducing the content of the NOTICE file.
*
* 7. Disclaimer of Warranty. Unless required by applicable law or
* agreed to in writing, Licensor provides the Work (and each
* Contributor provides its Contributions) on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied, including, without limitation, any warranties or conditions
* of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
* PARTICULAR PURPOSE. You are solely responsible for determining the
* appropriateness of using or redistributing the Work and assume any
* risks associated with Your exercise of permissions under this License.
*
* 8. Limitation of Liability. In no event and under no legal theory,
* whether in tort (including negligence), contract, or otherwise,
* unless required by applicable law (such as deliberate and grossly
* negligent acts) or agreed to in writing, shall any Contributor be
* liable to You for damages, including any direct, indirect, special,
* incidental, or consequential damages of any character arising as a
* result of this License or out of the use or inability to use the
* Work (including but not limited to damages for loss of goodwill,
* work stoppage, computer failure or malfunction, or any and all
* other commercial damages or losses), even if such Contributor
* has been advised of the possibility of such damages.
*
* 9. Accepting Warranty or Additional Liability. While redistributing
* the Work or Derivative Works thereof, You may choose to offer,
* and charge a fee for, acceptance of support, warranty, indemnity,
* or other liability obligations and/or rights consistent with this
* License. However, in accepting such obligations, You may act only
* on Your own behalf and on Your sole responsibility, not on behalf
* of any other Contributor, and only if You agree to indemnify,
* defend, and hold each Contributor harmless for any liability
* incurred by, or claims asserted against, such Contributor by reason
* of your accepting any such warranty or additional liability.
*
* END OF TERMS AND CONDITIONS
*
* APPENDIX: How to apply the Apache License to your work.
*
* To apply the Apache License to your work, attach the following
* boilerplate notice, with the fields enclosed by brackets "{}"
* replaced with your own identifying information. (Don't include
* the brackets!) The text should be enclosed in the appropriate
* comment syntax for the file format. We also recommend that a
* file or class name and description of purpose be included on the
* same "printed page" as the copyright notice for easier
* identification within third-party archives.
*
* Copyright {yyyy} {name of copyright owner}
*
* 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.deleidos.rtws.commons.dao.type.sql;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import com.deleidos.rtws.commons.dao.exception.DataAccessException;
import com.deleidos.rtws.commons.dao.exception.DataRetrievalException;
import com.deleidos.rtws.commons.dao.exception.DataStorageException;
public class NumberHandler extends SqlTypeHandler<Number> {
public NumberHandler() {
super("NUMBER", Number.class);
}
@Override
public Number get(ResultSet object, String field) {
try {
double value = object.getDouble(field);
if(object.wasNull()) {
return null;
} else {
return value;
}
} catch (SQLException e) {
throw new DataRetrievalException(e);
} catch (Exception e) {
throw new DataAccessException("Unexpected error.", e);
}
}
@Override
public void set(ResultSet record, String field, Number value) {
try {
if (value == null) {
record.updateNull(field);
} else {
record.updateDouble(field, value.doubleValue());
}
} catch (SQLException e) {
throw new DataStorageException(e);
} catch (Exception e) {
throw new DataAccessException("Unexpected error.", e);
}
}
@Override
public Number get(ResultSet object, int field) {
try {
double value = object.getDouble(field);
if(object.wasNull()) {
return null;
} else {
return value;
}
} catch (SQLException e) {
throw new DataRetrievalException(e);
} catch (Exception e) {
throw new DataAccessException("Unexpected error.", e);
}
}
@Override
public void set(ResultSet record, int field, Number value) {
try {
if (value == null) {
record.updateNull(field);
} else {
record.updateDouble(field, value.doubleValue());
}
} catch (SQLException e) {
throw new DataStorageException(e);
} catch (Exception e) {
throw new DataAccessException("Unexpected error.", e);
}
}
@Override
public void set(PreparedStatement record, int field, Number value) {
try {
if (value == null) {
record.setNull(field, Types.NUMERIC);
} else {
record.setDouble(field, value.doubleValue());
}
} catch (SQLException e) {
throw new DataStorageException(e);
} catch (Exception e) {
throw new DataAccessException("Unexpected error.", e);
}
}
}
| deleidos/digitaledge-platform | commons-core/src/main/java/com/deleidos/rtws/commons/dao/type/sql/NumberHandler.java | Java | apache-2.0 | 14,257 |
/**
* Copyright 2011-2019 Asakusa Framework Team.
*
* 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.asakusafw.lang.compiler.planning.basic;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import com.asakusafw.lang.compiler.common.util.EnumUtil;
import com.asakusafw.lang.compiler.model.graph.MarkerOperator;
import com.asakusafw.lang.compiler.model.graph.Operator;
import com.asakusafw.lang.compiler.model.graph.OperatorConstraint;
import com.asakusafw.lang.compiler.model.graph.OperatorInput;
import com.asakusafw.lang.compiler.model.graph.OperatorOutput;
import com.asakusafw.lang.compiler.model.graph.Operators;
import com.asakusafw.lang.compiler.planning.PlanMarker;
import com.asakusafw.lang.compiler.planning.PlanMarkers;
import com.asakusafw.lang.compiler.planning.SubPlan;
import com.asakusafw.lang.compiler.planning.basic.BasicSubPlan.BasicInput;
/**
* A group of isomorphic operators.
*/
final class OperatorGroup {
private final BasicSubPlan owner;
private final Set<Operator> operators;
private final BitSet broadcastInputIndices;
private final Set<Attribute> attributes;
OperatorGroup(
BasicSubPlan owner, Set<Operator> operators,
BitSet broadcastInputIndices, Set<Attribute> attributes) {
this.owner = owner;
this.operators = new LinkedHashSet<>(operators);
this.broadcastInputIndices = (BitSet) broadcastInputIndices.clone();
this.attributes = EnumUtil.freeze(attributes);
}
public static Set<Attribute> getAttributes(SubPlan owner, Operator operator) {
Set<Attribute> results = EnumSet.noneOf(Attribute.class);
if (isExtractKind(owner, operator)) {
results.add(Attribute.EXTRACT_KIND);
}
if (operator.getConstraints().contains(OperatorConstraint.GENERATOR)) {
results.add(Attribute.GENERATOR);
}
if (operator.getConstraints().contains(OperatorConstraint.AT_LEAST_ONCE)) {
results.add(Attribute.CONSUMER);
}
if (owner.findInput(operator) != null) {
results.add(Attribute.INPUT);
}
if (owner.findOutput(operator) != null) {
results.add(Attribute.OUTPUT);
}
PlanMarker marker = PlanMarkers.get(operator);
if (marker != null) {
switch (marker) {
case BEGIN:
results.add(Attribute.BEGIN);
break;
case END:
results.add(Attribute.END);
break;
case CHECKPOINT:
results.add(Attribute.CHECKPOINT);
break;
case GATHER:
results.add(Attribute.GATHER);
break;
case BROADCAST:
results.add(Attribute.BROADCAST);
break;
default:
// ignore unknown markers
break;
}
}
return results;
}
private static boolean isExtractKind(SubPlan owner, Operator operator) {
// for safety, we assumes that GATHER (input) is not extract kind
if (PlanMarkers.get(operator) == PlanMarker.GATHER
&& owner.findInput(operator) != null) {
return false;
}
// operator following GATHER is not extract kind
for (Operator pred : Operators.getPredecessors(operator)) {
if (PlanMarkers.get(pred) == PlanMarker.GATHER) {
return false;
}
}
return true;
}
public boolean isEmpty() {
return operators.isEmpty();
}
public boolean has(Attribute attribute) {
return attributes.contains(attribute);
}
public void remove(Operator operator) {
if (operators.remove(operator)) {
owner.removeOperator(operator);
}
}
public boolean applyRedundantOutputElimination() {
return applyCombination((base, target) -> applyRedundantOutputElimination(base, target));
}
boolean applyRedundantOutputElimination(Operator base, Operator target) {
// a +-- $ --- b
// \- $ --- c
// >>>
// a --- $ +-- b
// \- $ \- c
if (hasSameInputs(base, target) == false) {
return false;
}
if (attributes.contains(Attribute.OUTPUT)) {
BasicSubPlan.BasicOutput baseOut = owner.findOutput(base);
BasicSubPlan.BasicOutput targetOut = owner.findOutput(target);
assert baseOut != null;
assert targetOut != null;
Set<BasicInput> downstreams = targetOut.getOpposites();
if (downstreams.isEmpty()) {
return false;
}
for (BasicSubPlan.BasicInput downstream : downstreams) {
baseOut.connect(downstream);
}
targetOut.disconnectAll();
return true;
} else {
if (Operators.hasSuccessors(target) == false) {
return false;
}
List<OperatorOutput> sources = target.getOutputs();
List<OperatorOutput> destinations = base.getOutputs();
assert sources.size() == destinations.size();
for (int i = 0, n = sources.size(); i < n; i++) {
OperatorOutput source = sources.get(i);
OperatorOutput destination = destinations.get(i);
assert source.getDataType().equals(destination.getDataType());
Collection<OperatorInput> downstreams = source.getOpposites();
if (downstreams.isEmpty() == false) {
Operators.connectAll(destination, downstreams);
source.disconnectAll();
}
}
return true;
}
}
public boolean applyUnionPushDown() {
if (attributes.contains(Attribute.EXTRACT_KIND) == false
|| attributes.contains(Attribute.GENERATOR)) {
return false;
}
return applyCombination((base, target) -> applyUnionPushDown(base, target));
}
boolean applyUnionPushDown(Operator base, Operator target) {
if (hasSameOutputs(base, target) == false || hasSameBroadcastInputs(base, target) == false) {
return false;
}
// a --- $ --+ c
// b --- $ -/
// >>>
// a --+ $ --+ c
// b -/ $ -/
if (attributes.contains(Attribute.INPUT)) {
BasicSubPlan.BasicInput baseIn = owner.findInput(base);
BasicSubPlan.BasicInput targetIn = owner.findInput(target);
assert baseIn != null;
assert targetIn != null;
Set<BasicSubPlan.BasicOutput> upstreams = targetIn.getOpposites();
if (upstreams.isEmpty()) {
return false;
}
for (BasicSubPlan.BasicOutput upstream : upstreams) {
baseIn.connect(upstream);
}
targetIn.disconnectAll();
return true;
} else {
if (Operators.hasPredecessors(target) == false) {
return false;
}
List<OperatorInput> sources = target.getInputs();
List<OperatorInput> destinations = base.getInputs();
assert sources.size() == destinations.size();
for (int i = 0, n = sources.size(); i < n; i++) {
OperatorInput source = sources.get(i);
if (broadcastInputIndices.get(i) == false) {
OperatorInput destination = destinations.get(i);
assert source.getDataType().equals(destination.getDataType());
Collection<OperatorOutput> upstreams = source.getOpposites();
Operators.connectAll(upstreams, destination);
}
source.disconnectAll();
}
return true;
}
}
private boolean applyCombination(Applier applier) {
if (operators.size() <= 1) {
return false;
}
boolean changed = false;
BitSet applied = new BitSet();
Operator[] ops = operators.toArray(new Operator[operators.size()]);
for (int baseIndex = 0; baseIndex < ops.length - 1; baseIndex++) {
if (applied.get(baseIndex)) {
continue;
}
Operator base = ops[baseIndex];
for (int targetIndex = baseIndex + 1; targetIndex < ops.length; targetIndex++) {
if (applied.get(targetIndex)) {
continue;
}
Operator target = ops[targetIndex];
if (applier.apply(base, target)) {
applied.set(targetIndex);
changed = true;
}
}
}
return changed;
}
public boolean applyTrivialOutputElimination() {
if (operators.isEmpty()) {
return false;
}
// NOTE this never change sub-plan inputs/outputs
// non-extract/generator/consumer is checked later
if (attributes.contains(Attribute.INPUT)
|| attributes.contains(Attribute.OUTPUT)) {
return false;
}
boolean changed = false;
for (Operator operator : operators) {
changed |= applyTrivialOutputElimination(operator);
}
return changed;
}
private boolean applyTrivialOutputElimination(Operator operator) {
if (Operators.hasSuccessors(operator) == false) {
return false;
}
// () ===> a --- $ --- b
// >>>
// () ===> a +-------- b
// \- $
boolean changed = false;
// shrink trivial upstream operators
// but here we keep at least one upstream per port
List<OperatorInput> inputs = operator.getInputs();
for (int i = 0, n = inputs.size(); i < n; i++) {
changed |= shrinkTrivialUpstreams(inputs.get(i));
}
// never remove non-extract/generator/consumer operators
if (attributes.contains(Attribute.EXTRACT_KIND) == false
|| attributes.contains(Attribute.GENERATOR)
|| attributes.contains(Attribute.CONSUMER)) {
return changed;
}
// try remove operator itself
MarkerOperator primary = null;
for (int i = 0, n = inputs.size(); i < n; i++) {
// ignores broadcast inputs
if (broadcastInputIndices.get(i)) {
continue;
}
OperatorInput input = inputs.get(i);
for (OperatorOutput upstream : input.getOpposites()) {
SubPlan.Input in = owner.findInput(upstream.getOwner());
if (in != null && in.getOpposites().isEmpty()) {
if (primary == null) {
primary = in.getOperator();
}
} else {
// operator is not empty
return changed;
}
}
}
if (primary != null) {
// try bypass upstream and downstream
Set<OperatorInput> downstreams = new HashSet<>();
for (OperatorOutput output : operator.getOutputs()) {
downstreams.addAll(output.getOpposites());
}
Operators.connectAll(primary.getOutput(), downstreams);
}
operator.disconnectAll();
return true;
}
private boolean shrinkTrivialUpstreams(OperatorInput port) {
Collection<OperatorOutput> upstreams = port.getOpposites();
if (upstreams.isEmpty()) {
return false;
}
List<MarkerOperator> trivials = new ArrayList<>(upstreams.size());
boolean sawNonTrivial = false;
for (OperatorOutput upstream : upstreams) {
SubPlan.Input in = owner.findInput(upstream.getOwner());
if (in != null && in.getOpposites().isEmpty()) {
trivials.add(in.getOperator());
} else {
sawNonTrivial = true;
}
}
if (trivials.isEmpty()) {
return false;
}
boolean changed = false;
if (sawNonTrivial) {
for (MarkerOperator trivial : trivials) {
assert port.isConnected(trivial.getOutput());
port.disconnect(trivial.getOutput());
changed = true;
}
} else {
long minId = trivials.get(0).getSerialNumber();
for (int i = 1, n = trivials.size(); i < n; i++) {
minId = Math.min(minId, trivials.get(i).getSerialNumber());
}
for (MarkerOperator trivial : trivials) {
// disconnect from operator expect which has minimum serial number (for stable operations)
if (trivial.getSerialNumber() == minId) {
continue;
}
port.disconnect(trivial.getOutput());
changed = true;
}
}
return changed;
}
public boolean applyDuplicateCheckpointElimination() {
if (operators.isEmpty()) {
return false;
}
if (attributes.contains(Attribute.INPUT) == false
|| attributes.contains(Attribute.CHECKPOINT) == false) {
return false;
}
boolean changed = false;
for (Operator operator : operators) {
changed |= applyDuplicateCheckpointElimination(operator);
}
return changed;
}
private boolean applyDuplicateCheckpointElimination(Operator operator) {
if (Operators.hasSuccessors(operator) == false) {
return false;
}
// c0 ===> $ +--------+ c1 ===> c1
// \- o0 -/
// >>>
// c0 +======================+> c1
// \=> $ --- o0 --- c1 =/
boolean changed = false;
BasicSubPlan.BasicInput input = owner.findInput(operator);
assert input != null;
Set<BasicSubPlan.BasicOutput> upstreams = input.getOpposites();
OperatorOutput port = input.getOperator().getOutput();
for (OperatorInput opposite : port.getOpposites()) {
Operator succ = opposite.getOwner();
BasicSubPlan.BasicOutput output = owner.findOutput(succ);
if (output == null) {
continue;
}
if (PlanMarkers.get(succ) != PlanMarker.CHECKPOINT) {
continue;
}
Set<BasicSubPlan.BasicInput> downstreams = output.getOpposites();
for (BasicSubPlan.BasicOutput upstream : upstreams) {
for (BasicSubPlan.BasicInput downstream : downstreams) {
assert upstream.isConnected(downstream) == false;
upstream.connect(downstream);
}
}
port.disconnect(opposite);
changed = true;
}
return changed;
}
// has-same-inputs and is-isomorphic => has-equivalent-outputs
private boolean hasSameInputs(Operator a, Operator b) {
assert operators.contains(a);
assert operators.contains(b);
if (attributes.contains(Attribute.INPUT)) {
SubPlan.Input aPort = owner.findInput(a);
SubPlan.Input bPort = owner.findInput(b);
assert aPort != null;
assert bPort != null;
return aPort.getOpposites().equals(bPort.getOpposites());
} else {
List<OperatorInput> aPorts = a.getInputs();
List<OperatorInput> bPorts = b.getInputs();
assert aPorts.size() == bPorts.size();
for (int i = 0, n = aPorts.size(); i < n; i++) {
OperatorInput aPort = aPorts.get(i);
OperatorInput bPort = bPorts.get(i);
if (aPort.hasSameOpposites(bPort) == false) {
return false;
}
}
return true;
}
}
private boolean hasSameBroadcastInputs(Operator a, Operator b) {
assert operators.contains(a);
assert operators.contains(b);
BitSet indices = broadcastInputIndices;
if (indices.isEmpty()) {
return true;
}
// sub-plan inputs must not have any broadcast inputs
assert attributes.contains(Attribute.INPUT) == false;
List<OperatorInput> aPorts = a.getInputs();
List<OperatorInput> bPorts = b.getInputs();
assert aPorts.size() == bPorts.size();
for (int i = indices.nextSetBit(0), n = aPorts.size(); i >= 0 && i < n; i = indices.nextSetBit(i + 1)) {
OperatorInput aPort = aPorts.get(i);
OperatorInput bPort = bPorts.get(i);
if (aPort.hasSameOpposites(bPort) == false) {
return false;
}
}
return true;
}
private boolean hasSameOutputs(Operator a, Operator b) {
assert operators.contains(a);
assert operators.contains(b);
if (attributes.contains(Attribute.OUTPUT)) {
SubPlan.Output aPort = owner.findOutput(a);
SubPlan.Output bPort = owner.findOutput(b);
assert aPort != null;
assert bPort != null;
return aPort.getOpposites().equals(bPort.getOpposites());
} else {
List<OperatorOutput> aPorts = a.getOutputs();
List<OperatorOutput> bPorts = b.getOutputs();
assert aPorts.size() == bPorts.size();
for (int i = 0, n = aPorts.size(); i < n; i++) {
OperatorOutput aPort = aPorts.get(i);
OperatorOutput bPort = bPorts.get(i);
if (aPort.hasSameOpposites(bPort) == false) {
return false;
}
}
return true;
}
}
@Override
public String toString() {
if (operators.isEmpty()) {
return "OperatorGroup(+0)"; //$NON-NLS-1$
} else {
Operator first = operators.iterator().next();
return MessageFormat.format(
"OperatorGroup{2}({0}+{1})", //$NON-NLS-1$
first,
operators.size() - 1,
attributes);
}
}
@FunctionalInterface
private interface Applier {
boolean apply(Operator base, Operator target);
}
public static final class GroupInfo {
final Object id;
final BitSet broadcastInputIndices;
final Set<Attribute> attributes;
GroupInfo(Object id, BitSet broadcastInputIndices, Set<Attribute> attributes) {
this.id = id;
this.broadcastInputIndices = broadcastInputIndices;
this.attributes = attributes;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Objects.hashCode(id);
result = prime * result + broadcastInputIndices.hashCode();
result = prime * result + attributes.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
GroupInfo other = (GroupInfo) obj;
if (!Objects.equals(id, other.id)) {
return false;
}
if (!broadcastInputIndices.equals(other.broadcastInputIndices)) {
return false;
}
if (!attributes.equals(other.attributes)) {
return false;
}
return true;
}
@Override
public String toString() {
return MessageFormat.format("Group({0})", id); //$NON-NLS-1$
}
}
public enum Attribute {
/**
* Is extract kind.
*/
EXTRACT_KIND,
/**
* Is sub-plan inputs.
*/
INPUT,
/**
* Is sub-plan outputs.
*/
OUTPUT,
/**
* Is generator.
*/
GENERATOR,
/**
* Is consumer.
*/
CONSUMER,
/**
* Is BEGIN plan markers.
*/
BEGIN,
/**
* Is END plan markers.
*/
END,
/**
* Is CHECKPOINT plan markers.
*/
CHECKPOINT,
/**
* Is GATHER plan markers.
*/
GATHER,
/**
* Is BROADCAST plan markers.
*/
BROADCAST,
}
}
| ashigeru/asakusafw-compiler | compiler-project/plan/src/main/java/com/asakusafw/lang/compiler/planning/basic/OperatorGroup.java | Java | apache-2.0 | 21,569 |
/*
* Copyright 2014-2019 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.iot.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.iot.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* SetV2LoggingLevelResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SetV2LoggingLevelResultJsonUnmarshaller implements Unmarshaller<SetV2LoggingLevelResult, JsonUnmarshallerContext> {
public SetV2LoggingLevelResult unmarshall(JsonUnmarshallerContext context) throws Exception {
SetV2LoggingLevelResult setV2LoggingLevelResult = new SetV2LoggingLevelResult();
return setV2LoggingLevelResult;
}
private static SetV2LoggingLevelResultJsonUnmarshaller instance;
public static SetV2LoggingLevelResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new SetV2LoggingLevelResultJsonUnmarshaller();
return instance;
}
}
| jentfoo/aws-sdk-java | aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/transform/SetV2LoggingLevelResultJsonUnmarshaller.java | Java | apache-2.0 | 1,637 |
class Solution {
public int strStr(String haystack, String needle) {
int lengthA = haystack.length();
int lengthB = needle.length();
if(lengthB > lengthA) {
return -1;
}
for(int i = 0; i + lengthB - 1 < lengthA;i++) {
boolean bFound = true;
for(int k = i, j = 0; j < lengthB;j++, k++) {
if(haystack.charAt(k) != needle.charAt(j)) {
bFound = false;
break;
}
}
if(bFound) {
return i;
}
}
return -1;
}
}
| iamlrf/leetcode | string/028_implement_strstr/solution.java | Java | apache-2.0 | 629 |
/*******************************************************************************
* Copyright (C) 2015 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.cloud.dataflow.sdk.util.common;
import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MAX;
import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SET;
import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SUM;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Unit tests for {@link CounterSet}.
*/
@RunWith(JUnit4.class)
public class CounterSetTest {
@Test
public void testSet() {
CounterSet set = new CounterSet();
assertTrue(set.add(Counter.longs("c1", SUM)));
assertFalse(set.add(Counter.longs("c1", SUM)));
assertTrue(set.add(Counter.longs("c2", MAX)));
assertEquals(2, set.size());
}
@Test
public void testAddCounterMutator() {
CounterSet set = new CounterSet();
Counter c1 = Counter.longs("c1", SUM);
Counter c1SecondInstance = Counter.longs("c1", SUM);
Counter c1IncompatibleInstance = Counter.longs("c1", SET);
Counter c2 = Counter.longs("c2", MAX);
Counter c2IncompatibleInstance = Counter.doubles("c2", MAX);
assertEquals(c1, set.getAddCounterMutator().addCounter(c1));
assertEquals(c2, set.getAddCounterMutator().addCounter(c2));
assertEquals(c1, set.getAddCounterMutator().addCounter(c1SecondInstance));
try {
set.getAddCounterMutator().addCounter(c1IncompatibleInstance);
fail("should have failed");
} catch (IllegalArgumentException exn) {
// Expected.
}
try {
set.getAddCounterMutator().addCounter(c2IncompatibleInstance);
fail("should have failed");
} catch (IllegalArgumentException exn) {
// Expected.
}
assertEquals(2, set.size());
}
}
| chamikaramj/MyDataflowJavaSDK | sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterSetTest.java | Java | apache-2.0 | 2,659 |
package fxreload;
import java.nio.file.Path;
import java.util.Collections;
import org.asciidoctor.Asciidoctor;
import org.markdown4j.Markdown4jProcessor;
public enum Processor {
MARKDOWN {
Markdown4jProcessor markdown;
@Override
public String process(String content) throws Exception {
if (markdown == null) {
markdown = new Markdown4jProcessor();
}
return markdown.process(content);
}
},
ASCIIDOC {
Asciidoctor asciiDoc;
public String process(String content) throws Exception {
if (asciiDoc == null) {
asciiDoc = Asciidoctor.Factory.create();
}
return asciiDoc.convert(content, Collections.emptyMap());
}
},
NO_PROCESSOR {
public String process(String content) throws Exception {
return null;
}
@Override
public boolean needsContent() {
return false;
}
};
public abstract String process(String content) throws Exception;
public static Processor find(Path path) {
String pathh = path.toString();
if (pathh.endsWith(".md")) {
return MARKDOWN;
} else if (pathh.endsWith(".adoc")) {
return ASCIIDOC;
}
return NO_PROCESSOR;
}
public static void preload() {
new Thread("Processor preload") {
@Override
public void run() {
try {
for (Processor it : values()) {
it.process("a");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
public boolean needsContent() {
return true;
}
}
| krizzdewizz/fxreload | src/main/java/fxreload/Processor.java | Java | apache-2.0 | 1,429 |
package com.yiqiniu.easytrans.executor;
import java.io.Serializable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.yiqiniu.easytrans.context.LogProcessContext;
import com.yiqiniu.easytrans.context.event.DemiLogEventHandler;
import com.yiqiniu.easytrans.core.EasyTransSynchronizer;
import com.yiqiniu.easytrans.core.EasytransConstant;
import com.yiqiniu.easytrans.core.LogProcessor;
import com.yiqiniu.easytrans.core.RemoteServiceCaller;
import com.yiqiniu.easytrans.filter.MetaDataFilter;
import com.yiqiniu.easytrans.log.vo.Content;
import com.yiqiniu.easytrans.log.vo.saga.PreSagaTccCallContent;
import com.yiqiniu.easytrans.log.vo.saga.SagaTccCallCancelledContent;
import com.yiqiniu.easytrans.log.vo.saga.SagaTccCallConfirmedContent;
import com.yiqiniu.easytrans.protocol.BusinessIdentifer;
import com.yiqiniu.easytrans.protocol.EasyTransRequest;
import com.yiqiniu.easytrans.protocol.SerializableVoid;
import com.yiqiniu.easytrans.protocol.saga.SagaTccMethod;
import com.yiqiniu.easytrans.util.ReflectUtil;
@RelativeInterface(SagaTccMethod.class)
public class SagaTccMethodExecutor implements EasyTransExecutor,LogProcessor,DemiLogEventHandler {
private EasyTransSynchronizer transSynchronizer;
private RemoteServiceCaller rpcClient;
@SuppressWarnings("rawtypes")
private Future nullObject;
public SagaTccMethodExecutor(EasyTransSynchronizer transSynchronizer, RemoteServiceCaller rpcClient) {
super();
this.transSynchronizer = transSynchronizer;
this.rpcClient = rpcClient;
CompletableFuture<Object> completableFuture = new CompletableFuture<>();
completableFuture.complete(SerializableVoid.SINGLETON);
this.nullObject = completableFuture;
}
private Logger LOG = LoggerFactory.getLogger(this.getClass());
@SuppressWarnings("unchecked")
@Override
public <P extends EasyTransRequest<R,E>,E extends EasyTransExecutor,R extends Serializable> Future<R> execute(final Integer callSeq, final P params) {
final LogProcessContext logProcessContext = transSynchronizer.getLogProcessContext();
//check parent transaction, SAGA-TCC is not support in subTransaction
if(MetaDataFilter.getMetaData(EasytransConstant.CallHeadKeys.PARENT_TRX_ID_KEY) != null) {
throw new RuntimeException("Saga-tcc is only allow in master transaction");
}
//save the SAGA calling request, for the SAGA handling after the master transaction
PreSagaTccCallContent content = new PreSagaTccCallContent();
content.setParams(params);
content.setCallSeq(callSeq);
logProcessContext.getLogCache().cacheLog(content);
//SAGA do not return message synchronous, just return a Meaningless result
return nullObject;
}
@Override
public boolean preLogProcess(LogProcessContext ctx, Content currentContent) {
// call the remote sagaTry method when transactionStatus is unknown.
// if transactionStatus is not null, it means the method below has already called
if(ctx.getMasterTransactionStatusVotter().getTransactionStatus() == null) {
PreSagaTccCallContent sagaLog = (PreSagaTccCallContent) currentContent;
EasyTransRequest<?, ?> params = sagaLog.getParams();
BusinessIdentifer businessIdentifer = ReflectUtil.getBusinessIdentifer(params.getClass());
try {
rpcClient.call(businessIdentifer.appId(), businessIdentifer.busCode(), sagaLog.getCallSeq(), SagaTccMethod.SAGA_TRY, params,ctx);
} catch (Exception e) {
LOG.warn("saga try call failed" + sagaLog,e);
//execute failed, vote to roll back
ctx.getMasterTransactionStatusVotter().veto();
}
}
return true;
}
@Override
public boolean logProcess(LogProcessContext ctx, Content currentContent) {
if(currentContent instanceof PreSagaTccCallContent){
PreSagaTccCallContent preCallContent = (PreSagaTccCallContent) currentContent;
//register DemiLogEvent
ctx.getDemiLogManager().registerSemiLogEventListener(preCallContent, this);
}
return true;
}
@Override
public boolean onMatch(LogProcessContext logCtx, Content leftContent, Content rightContent) {
return true;// do nothig
}
@Override
public boolean onDismatch(LogProcessContext logCtx, Content leftContent) {
PreSagaTccCallContent preCallContent = (PreSagaTccCallContent) leftContent;
EasyTransRequest<?,?> params = preCallContent.getParams();
BusinessIdentifer businessIdentifer = ReflectUtil.getBusinessIdentifer(params.getClass());
if(logCtx.getFinalMasterTransStatus() == null){
LOG.info("final trans status unknown,process later." + logCtx.getLogCollection());
return false;//unknown,process later
}else if(logCtx.getFinalMasterTransStatus()){
//commit
//execute confirm and then write Log
rpcClient.callWithNoReturn(businessIdentifer.appId(), businessIdentifer.busCode(), preCallContent.getCallSeq(), SagaTccMethod.SAGA_CONFIRM, preCallContent.getParams(),logCtx);
SagaTccCallConfirmedContent tccCallConfirmedContent = new SagaTccCallConfirmedContent();
tccCallConfirmedContent.setLeftDemiConentId(leftContent.getcId());
logCtx.getLogCache().cacheLog(tccCallConfirmedContent);
return true;
}else{
//roll back
//execute cancel and then write Log
rpcClient.callWithNoReturn(businessIdentifer.appId(), businessIdentifer.busCode(), preCallContent.getCallSeq(), SagaTccMethod.SAGA_CANCEL, preCallContent.getParams(),logCtx);
SagaTccCallCancelledContent tccCallCanceledContent = new SagaTccCallCancelledContent();
tccCallCanceledContent.setLeftDemiConentId(leftContent.getcId());
logCtx.getLogCache().cacheLog(tccCallCanceledContent);
return true;
}
}
}
| QNJR-GROUP/EasyTransaction | easytrans-core/src/main/java/com/yiqiniu/easytrans/executor/SagaTccMethodExecutor.java | Java | apache-2.0 | 5,775 |
package org.frameworkset.persitent.type;
/**
* Copyright 2022 bboss
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 com.frameworkset.common.poolman.Param;
import com.frameworkset.common.poolman.StatementInfo;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
/**
* <p>Description: </p>
* <p></p>
* <p>Copyright (c) 2020</p>
* @Date 2022/3/2
* @author biaoping.yin
* @version 1.0
*/
public class BigDecimalTypeMethod extends BaseTypeMethod{
@Override
public void action(StatementInfo stmtInfo, Param param, PreparedStatement statement, PreparedStatement statement_count, List resources) throws SQLException {
statement.setBigDecimal(param.getIndex(), (BigDecimal)param.getData());
if(statement_count != null)
{
statement_count.setBigDecimal(param.getIndex(), (BigDecimal)param.getData());
}
}
}
| bbossgroups/bboss | bboss-persistent/src/org/frameworkset/persitent/type/BigDecimalTypeMethod.java | Java | apache-2.0 | 1,417 |
/*
* Copyright 2012 Amazon Technologies, Inc. or its affiliates.
* Amazon, Amazon.com and Carbonado are trademarks or registered trademarks
* of Amazon Technologies, 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.
* 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.amazon.carbonado.repo.sleepycat;
import java.util.concurrent.locks.Lock;
import com.sleepycat.db.Database;
import com.sleepycat.db.DatabaseException;
import com.sleepycat.db.Transaction;
import com.amazon.carbonado.FetchException;
import com.amazon.carbonado.Storable;
import com.amazon.carbonado.txn.TransactionScope;
/**
*
*
* @author Brian S O'Neill
* @see DBX_Storage
*/
class DBX_Cursor<S extends Storable> extends DB_Cursor<S> {
private final Lock mLock;
DBX_Cursor(TransactionScope<Transaction> scope,
byte[] startBound, boolean inclusiveStart,
byte[] endBound, boolean inclusiveEnd,
int maxPrefix,
boolean reverse,
DBX_Storage<S> storage,
Database database)
throws DatabaseException, FetchException
{
super(scope, startBound, inclusiveStart, endBound, inclusiveEnd,
maxPrefix, reverse, storage, database);
mLock = storage.mRWLock.readLock();
}
@Override
protected boolean cursor_getCurrent() throws Exception {
mLock.lock();
try {
return super.cursor_getCurrent();
} finally {
mLock.unlock();
}
}
@Override
protected boolean cursor_getFirst() throws Exception {
mLock.lock();
try {
return super.cursor_getFirst();
} finally {
mLock.unlock();
}
}
@Override
protected boolean cursor_getLast() throws Exception {
mLock.lock();
try {
return super.cursor_getLast();
} finally {
mLock.unlock();
}
}
@Override
protected boolean cursor_getSearchKeyRange() throws Exception {
mLock.lock();
try {
return super.cursor_getSearchKeyRange();
} finally {
mLock.unlock();
}
}
@Override
protected boolean cursor_getNext() throws Exception {
mLock.lock();
try {
return super.cursor_getNext();
} finally {
mLock.unlock();
}
}
@Override
protected boolean cursor_getNextDup() throws Exception {
mLock.lock();
try {
return super.cursor_getNextDup();
} finally {
mLock.unlock();
}
}
@Override
protected boolean cursor_getPrev() throws Exception {
mLock.lock();
try {
return super.cursor_getPrev();
} finally {
mLock.unlock();
}
}
@Override
protected boolean cursor_getPrevNoDup() throws Exception {
mLock.lock();
try {
return super.cursor_getPrevNoDup();
} finally {
mLock.unlock();
}
}
}
| Carbonado/CarbonadoSleepycatDB | src/main/java/com/amazon/carbonado/repo/sleepycat/DBX_Cursor.java | Java | apache-2.0 | 3,706 |
package me.pjq.pushup.lan;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteOrder;
/**
* Created by kicoolzhang on 11/12/13.
*/
public class WifiNetworkHelper {
private static final String TAG = "WifiNetworkHelper";
WifiManager mWifiManager;
WifiManager.WifiLock mWifiLock;
public WifiNetworkHelper(Context ctx) {
mWifiManager = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
mWifiLock = mWifiManager.createWifiLock(
android.os.Build.VERSION.SDK_INT >= 12
? WifiManager.WIFI_MODE_FULL_HIGH_PERF
: WifiManager.WIFI_MODE_FULL, getClass().getName());
WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
Log.i(TAG, "Own IP Address: " + wifiIpAddress(wifiInfo.getIpAddress()) + "Network SSID: " + wifiInfo.getSSID() + "Netword ID: " + wifiInfo.getNetworkId());
}
public WifiNetworkInfo getWifiInfo() {
WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
return new WifiNetworkInfo(wifiInfo);
}
protected static String wifiIpAddress(int ipAddress) {
// Convert little-endian to big-endianif needed
if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
ipAddress = Integer.reverseBytes(ipAddress);
}
byte[] ipByteArray = BigInteger.valueOf(ipAddress).toByteArray();
String ipAddressString;
try {
ipAddressString = InetAddress.getByAddress(ipByteArray).getHostAddress();
} catch (UnknownHostException ex) {
Log.e(TAG, "Unable to get host address.");
ipAddressString = null;
}
Log.i(TAG, "Wifi IP:" + ipAddressString);
return ipAddressString;
}
public void lock() {
mWifiLock.acquire();
}
public void unlock() {
mWifiLock.release();
}
public static class WifiNetworkInfo {
WifiInfo wifiInfo;
String wifiIpAddress;
public WifiNetworkInfo(WifiInfo wifiInfo) {
this.wifiInfo = wifiInfo;
wifiIpAddress = wifiIpAddress(wifiInfo.getIpAddress());
}
public String getWifiIpAddress() {
return wifiIpAddress;
}
public String getSSID() {
return wifiInfo.getSSID();
}
public String getNetwordId() {
return Integer.toString(wifiInfo.getNetworkId());
}
}
}
| pjq/pushup | PushUp/src/main/java/me/pjq/pushup/lan/WifiNetworkHelper.java | Java | apache-2.0 | 2,631 |
/*
* Copyright 1999-2020 Alibaba Group Holding 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.alibaba.nacos.core.cluster.remote;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.remote.RemoteConstants;
import com.alibaba.nacos.api.remote.RequestCallBack;
import com.alibaba.nacos.api.remote.request.Request;
import com.alibaba.nacos.api.remote.response.Response;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.remote.ConnectionType;
import com.alibaba.nacos.common.remote.client.RpcClient;
import com.alibaba.nacos.common.remote.client.RpcClientFactory;
import com.alibaba.nacos.common.remote.client.ServerListFactory;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.core.cluster.Member;
import com.alibaba.nacos.core.cluster.MemberChangeListener;
import com.alibaba.nacos.core.cluster.MemberUtil;
import com.alibaba.nacos.core.cluster.MembersChangeEvent;
import com.alibaba.nacos.core.cluster.ServerMemberManager;
import com.alibaba.nacos.core.utils.Loggers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static com.alibaba.nacos.api.exception.NacosException.CLIENT_INVALID_PARAM;
/**
* cluster rpc client proxy.
*
* @author liuzunfei
* @version $Id: ClusterRpcClientProxy.java, v 0.1 2020年08月11日 2:11 PM liuzunfei Exp $
*/
@Service
public class ClusterRpcClientProxy extends MemberChangeListener {
private static final long DEFAULT_REQUEST_TIME_OUT = 3000L;
@Autowired
ServerMemberManager serverMemberManager;
/**
* init after constructor.
*/
@PostConstruct
public void init() {
try {
NotifyCenter.registerSubscriber(this);
List<Member> members = serverMemberManager.allMembersWithoutSelf();
refresh(members);
Loggers.CLUSTER
.warn("[ClusterRpcClientProxy] success to refresh cluster rpc client on start up,members ={} ",
members);
} catch (NacosException e) {
Loggers.CLUSTER.warn("[ClusterRpcClientProxy] fail to refresh cluster rpc client,{} ", e.getMessage());
}
}
/**
* init cluster rpc clients.
*
* @param members cluster server list member list.
*/
private void refresh(List<Member> members) throws NacosException {
//ensure to create client of new members
for (Member member : members) {
if (MemberUtil.isSupportedLongCon(member)) {
createRpcClientAndStart(member, ConnectionType.GRPC);
}
}
//shutdown and remove old members.
Set<Map.Entry<String, RpcClient>> allClientEntrys = RpcClientFactory.getAllClientEntries();
Iterator<Map.Entry<String, RpcClient>> iterator = allClientEntrys.iterator();
List<String> newMemberKeys = members.stream().filter(MemberUtil::isSupportedLongCon)
.map(this::memberClientKey).collect(Collectors.toList());
while (iterator.hasNext()) {
Map.Entry<String, RpcClient> next1 = iterator.next();
if (next1.getKey().startsWith("Cluster-") && !newMemberKeys.contains(next1.getKey())) {
Loggers.CLUSTER.info("member leave,destroy client of member - > : {}", next1.getKey());
RpcClientFactory.getClient(next1.getKey()).shutdown();
iterator.remove();
}
}
}
private String memberClientKey(Member member) {
return "Cluster-" + member.getAddress();
}
private void createRpcClientAndStart(Member member, ConnectionType type) throws NacosException {
Map<String, String> labels = new HashMap<String, String>(2);
labels.put(RemoteConstants.LABEL_SOURCE, RemoteConstants.LABEL_SOURCE_CLUSTER);
String memberClientKey = memberClientKey(member);
RpcClient client = RpcClientFactory.createClusterClient(memberClientKey, type, labels);
if (!client.getConnectionType().equals(type)) {
Loggers.CLUSTER.info(",connection type changed,destroy client of member - > : {}", member);
RpcClientFactory.destroyClient(memberClientKey);
client = RpcClientFactory.createClusterClient(memberClientKey, type, labels);
}
if (client.isWaitInitiated()) {
Loggers.CLUSTER.info("start a new rpc client to member - > : {}", member);
//one fixed server
client.serverListFactory(new ServerListFactory() {
@Override
public String genNextServer() {
return member.getAddress();
}
@Override
public String getCurrentServer() {
return member.getAddress();
}
@Override
public List<String> getServerList() {
return CollectionUtils.list(member.getAddress());
}
});
client.start();
}
}
/**
* send request to member.
*
* @param member member of server.
* @param request request.
* @return Response response.
* @throws NacosException exception may throws.
*/
public Response sendRequest(Member member, Request request) throws NacosException {
return sendRequest(member, request, DEFAULT_REQUEST_TIME_OUT);
}
/**
* send request to member.
*
* @param member member of server.
* @param request request.
* @return Response response.
* @throws NacosException exception may throws.
*/
public Response sendRequest(Member member, Request request, long timeoutMills) throws NacosException {
RpcClient client = RpcClientFactory.getClient(memberClientKey(member));
if (client != null) {
return client.request(request, timeoutMills);
} else {
throw new NacosException(CLIENT_INVALID_PARAM, "No rpc client related to member: " + member);
}
}
/**
* aync send request to member with callback.
*
* @param member member of server.
* @param request request.
* @param callBack RequestCallBack.
* @throws NacosException exception may throws.
*/
public void asyncRequest(Member member, Request request, RequestCallBack callBack) throws NacosException {
RpcClient client = RpcClientFactory.getClient(memberClientKey(member));
if (client != null) {
client.asyncRequest(request, callBack);
} else {
throw new NacosException(CLIENT_INVALID_PARAM, "No rpc client related to member: " + member);
}
}
/**
* send request to member.
*
* @param request request.
* @throws NacosException exception may throw.
*/
public void sendRequestToAllMembers(Request request) throws NacosException {
List<Member> members = serverMemberManager.allMembersWithoutSelf();
for (Member member1 : members) {
sendRequest(member1, request);
}
}
@Override
public void onEvent(MembersChangeEvent event) {
try {
List<Member> members = serverMemberManager.allMembersWithoutSelf();
refresh(members);
} catch (NacosException e) {
Loggers.CLUSTER.warn("[serverlist] fail to refresh cluster rpc client, event:{}, msg: {} ", event, e.getMessage());
}
}
}
| alibaba/nacos | core/src/main/java/com/alibaba/nacos/core/cluster/remote/ClusterRpcClientProxy.java | Java | apache-2.0 | 8,385 |
package io.dashbase.clue.api;
public interface BytesRefDisplay {
BytesRefPrinter getBytesRefPrinter(String field);
}
| javasoze/clue | src/main/java/io/dashbase/clue/api/BytesRefDisplay.java | Java | apache-2.0 | 120 |
package org.manam.webapp.rest.dto;
/**
* Created by kasar on 12/21/2017.
*/
public class PeopleDTO {
private Long id;
private String firstName;
private String lastName;
private String mailId;
private Long number;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMailId() {
return mailId;
}
public void setMailId(String mailId) {
this.mailId = mailId;
}
public Long getNumber() {
return number;
}
public void setNumber(Long number) {
this.number = number;
}
}
| ManamFoundation/manamfoundation | src/main/java/org/manam/webapp/rest/dto/PeopleDTO.java | Java | apache-2.0 | 1,087 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.